<?php
require_once '../includes/auth.php';
require_once '../includes/functions.php';

require_login('ground_handler');
$page_title = 'Invoice - ANATL Portal';
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validate_csrf($_POST['csrf_token'] ?? '')) {
        die('Invalid request');
    }

    $invoice_id = intval($_POST['invoice_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if ($action === 'confirm' && $invoice_id) {
        $stmt = $conn->prepare('UPDATE invoices SET status = "paid", confirmed_at = NOW() WHERE id = ? AND vendor_id = ?');
        $stmt->bind_param('ii', $invoice_id, $user_id);
        $stmt->execute();
        $stmt->close();

        set_flash('success', 'Invoice berhasil dikonfirmasi sebagai pembayaran');
    }

    header('Location: ' . BASE_URL . '/ground-handling/invoice.php');
    exit;
}

// Get invoices
$invoices = [];
$result = $conn->query("
    SELECT i.*, if_.flight_no, if_.airline
    FROM invoices i
    JOIN irregular_flights if_ ON i.flight_id = if_.id
    WHERE i.vendor_id = $user_id
    ORDER BY i.created_at DESC
");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $invoices[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
</head>
<body>
<?php require '../includes/header.php'; ?>

<div class="main">
    <div class="portal">
        <div class="portal__sidebar">
            <div class="sidebar__title">Menu Ground Handling</div>
            <a href="<?= BASE_URL ?>/ground-handling/index.php" class="sidebar-item">📊 Dashboard</a>
            <a href="<?= BASE_URL ?>/ground-handling/notif.php" class="sidebar-item">📢 Penerbangan</a>
            <a href="<?= BASE_URL ?>/ground-handling/invoice.php" class="sidebar-item sidebar-item--active">💰 Invoice</a>
        </div>

        <div class="portal__content">
            <h1 style="color: #003A70; margin-bottom: 32px;">Invoice</h1>

            <?php if ($flash = get_flash()): ?>
            <div class="alert alert--<?= esc($flash['type']) ?>">
                <?= esc($flash['msg']) ?>
            </div>
            <?php endif; ?>

            <?php if (empty($invoices)): ?>
            <div class="empty-state">
                <div class="empty-state__message">Tidak ada invoice</div>
            </div>
            <?php else: ?>

            <div class="grid grid--1">
                <?php foreach ($invoices as $invoice): ?>
                <div class="card">
                    <div class="card__header">
                        <div>
                            <div class="card__title"><?= esc($invoice['flight_no']) ?> - <?= esc($invoice['airline']) ?></div>
                        </div>
                        <span class="badge badge--<?= $invoice['status'] === 'paid' ? 'approved' : 'rejected' ?>">
                            <?= $invoice['status'] === 'paid' ? 'Dibayar' : 'Unpaid' ?>
                        </span>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
                        <div>
                            <p style="color: #5A6A7A; font-size: 12px;">Jumlah</p>
                            <p style="font-weight: 600; font-size: 18px; color: #003A70;">
                                Rp <?= number_format($invoice['amount'], 0, ',', '.') ?>
                            </p>
                        </div>
                        <div>
                            <p style="color: #5A6A7A; font-size: 12px;">Due Date</p>
                            <p style="font-weight: 600;"><?= format_date($invoice['due_date']) ?></p>
                        </div>
                    </div>

                    <?php if ($invoice['status'] === 'unpaid'): ?>
                    <form method="POST" style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
                        <input type="hidden" name="invoice_id" value="<?= $invoice['id'] ?>">
                        <input type="hidden" name="action" value="confirm">
                        <button type="submit" class="btn btn--success">Konfirmasi Pembayaran</button>
                        <a href="#" class="btn btn--secondary">Download PDF</a>
                    </form>
                    <?php else: ?>
                    <div style="color: #059669; font-size: 14px; font-weight: 500;">
                        ✓ Dibayar pada <?= format_datetime($invoice['confirmed_at']) ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>

            <?php endif; ?>
        </div>
    </div>
</div>

<?php require '../includes/footer.php'; ?>
