<?php
$pageTitle = 'Buat Invoice Pembayaran';
$activeMenu = 'payments';
require_once __DIR__ . '/../../includes/header.php';

$db = get_db_connection();
$clients = get_client_options();
$errors = [];
$formData = [
    'invoice_number' => generate_invoice_number(),
    'client_id' => '',
    'amount' => '',
    'payment_status' => 'pending',
    'invoice_date' => date('Y-m-d'),
    'due_date' => date('Y-m-d', strtotime('+7 days')),
    'payment_date' => '',
];
$statuses = ['pending', 'paid', 'overdue'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!validate_csrf_token($token)) {
        $errors[] = 'Token tidak sah. Silakan coba lagi.';
    }

    $formData['invoice_number'] = sanitize_input($_POST['invoice_number'] ?? '');
    $formData['client_id'] = (int) ($_POST['client_id'] ?? 0);
    $formData['amount'] = sanitize_input($_POST['amount'] ?? '0');
    $formData['payment_status'] = sanitize_input($_POST['payment_status'] ?? 'pending');
    $formData['invoice_date'] = $_POST['invoice_date'] ?? date('Y-m-d');
    $formData['due_date'] = $_POST['due_date'] ?? date('Y-m-d');
    $formData['payment_date'] = $_POST['payment_date'] ?? '';

    if ($formData['invoice_number'] === '') {
        $errors[] = 'Nomor invoice wajib diisi.';
    }
    if ($formData['client_id'] <= 0) {
        $errors[] = 'Pilih pelanggan.';
    }
    if (!is_numeric($formData['amount']) || (float) $formData['amount'] <= 0) {
        $errors[] = 'Nominal harus lebih dari 0.';
    }
    if (!in_array($formData['payment_status'], $statuses, true)) {
        $errors[] = 'Status pembayaran tidak valid.';
    }
    if ($formData['invoice_date'] === '' || $formData['due_date'] === '') {
        $errors[] = 'Tanggal invoice dan jatuh tempo wajib diisi.';
    }
    if ($formData['payment_status'] === 'paid' && $formData['payment_date'] === '') {
        $errors[] = 'Tanggal pembayaran wajib diisi untuk status paid.';
    }

    $stmtCheck = $db->prepare('SELECT id FROM payments WHERE invoice_number = ? LIMIT 1');
    if ($stmtCheck) {
        $stmtCheck->bind_param('s', $formData['invoice_number']);
        $stmtCheck->execute();
        $stmtCheck->store_result();
        if ($stmtCheck->num_rows > 0) {
            $errors[] = 'Nomor invoice sudah digunakan.';
        }
    }

    if (empty($errors)) {
        $sql = 'INSERT INTO payments (invoice_number, client_id, amount, payment_status, invoice_date, due_date, payment_date, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())';
        $stmt = $db->prepare($sql);
        if ($stmt) {
            $paymentDate = $formData['payment_date'] !== '' ? $formData['payment_date'] : null;
            $amount = (float) $formData['amount'];
            $stmt->bind_param(
                'sidssss',
                $formData['invoice_number'],
                $formData['client_id'],
                $amount,
                $formData['payment_status'],
                $formData['invoice_date'],
                $formData['due_date'],
                $paymentDate
            );
            if ($stmt->execute()) {
                redirect_with_message('index.php', 'Invoice berhasil dibuat.');
            } else {
                $errors[] = 'Gagal menyimpan data pembayaran.';
            }
        } else {
            $errors[] = 'Terjadi kesalahan pada database.';
        }
    }
}

$token = csrf_token();
?>
<div class="card card-metric p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <small class="text-muted">Silakan isi informasi pembayaran dengan lengkap.</small>
        </div>
        <a href="index.php" class="btn btn-outline-secondary"><i class="fa-solid fa-arrow-left me-2"></i>Kembali</a>
    </div>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    <form method="POST" class="row gy-3 needs-validation" novalidate>
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
        <div class="col-md-6">
            <label class="form-label">Nomor Invoice</label>
            <input type="text" name="invoice_number" class="form-control" value="<?php echo htmlspecialchars($formData['invoice_number']); ?>" required>
            <div class="invalid-feedback">Nomor invoice wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Pelanggan</label>
            <select name="client_id" class="form-select" required>
                <option value="">-- pilih pelanggan --</option>
                <?php foreach ($clients as $client): ?>
                    <option value="<?php echo $client['id']; ?>" <?php echo (int) $formData['client_id'] === (int) $client['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($client['full_name']); ?></option>
                <?php endforeach; ?>
            </select>
            <div class="invalid-feedback">Pilih pelanggan.</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Nominal (Rp)</label>
            <input type="number" step="0.01" min="0" name="amount" class="form-control" value="<?php echo htmlspecialchars($formData['amount']); ?>" required>
            <div class="invalid-feedback">Masukkan nominal pembayaran.</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Status Pembayaran</label>
            <select name="payment_status" class="form-select" required>
                <?php foreach ($statuses as $status): ?>
                    <option value="<?php echo $status; ?>" <?php echo $formData['payment_status'] === $status ? 'selected' : ''; ?>><?php echo ucfirst($status); ?></option>
                <?php endforeach; ?>
            </select>
            <div class="invalid-feedback">Pilih status pembayaran.</div>
        </div>
        <div class="col-md-4">
            <label class="form-label">Tanggal Pembayaran</label>
            <input type="date" name="payment_date" class="form-control" value="<?php echo htmlspecialchars($formData['payment_date']); ?>">
        </div>
        <div class="col-md-6">
            <label class="form-label">Tanggal Invoice</label>
            <input type="date" name="invoice_date" class="form-control" value="<?php echo htmlspecialchars($formData['invoice_date']); ?>" required>
            <div class="invalid-feedback">Tanggal invoice wajib diisi.</div>
        </div>
        <div class="col-md-6">
            <label class="form-label">Tanggal Jatuh Tempo</label>
            <input type="date" name="due_date" class="form-control" value="<?php echo htmlspecialchars($formData['due_date']); ?>" required>
            <div class="invalid-feedback">Tanggal jatuh tempo wajib diisi.</div>
        </div>
        <div class="col-12">
            <button type="submit" class="btn btn-primary">Simpan</button>
        </div>
    </form>
</div>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>