<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
include '../../includes/header.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Invoice.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';

$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
$invoice = new invoice($conn);
$branch = new Branch($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$branchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;
$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

if ($isSuperAdmin) {

    if (!$branchId) {

        header('Location: ../admin/invoices/invoice_branch_selection.php?error=' . urlencode('Please select a branch.'));
        exit();
    }

    $branches = $branch->getAllBranches();
    $validBranch = false;
    foreach ($branches->fetchAll(PDO::FETCH_ASSOC) as $b) {
        if ($b['branch_id'] == $branchId) {
            $validBranch = true;
            break;
        }
    }
    if (!$validBranch) {
        header('Location: ../admin/invoices/invoice_branch_selection.php?error=' . urlencode('Invalid branch selected.'));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
} else {

    $branchId = $userBranchId;
    if (!$branchId) {
        header('Location: ../../login.php?error=' . urlencode('No branch assigned to this user.'));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
}


$isUserAssignedBranch = ($branchId == $userBranchId);


$invoices = $invoice->getinvoicesByBranch($branchId);

function getStatus($created_at, $valid_until, $status) {
    $now = new DateTime();
    $validUntil = new DateTime($valid_until);
    if ($now > $validUntil) {
        return 'expired';
    }
    return $status;
}

$statusStyles = [
    'draft'     => ['bg' => '#F4F4F5', 'fg' => '#52525B'],
    'pending'   => ['bg' => '#FEF9C3', 'fg' => '#854D0E'],
    'approved'  => ['bg' => '#DCFCE7', 'fg' => '#166534'],
    'converted' => ['bg' => '#EDE9FE', 'fg' => '#5B21B6'],
    'expired'   => ['bg' => '#FEE2E2', 'fg' => '#991B1B'],
];
?>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap');

        :root { --accent: #7C3AED; --accent-dark: #5B21B6; --ink: #18181B; --sub: #71717A; --line: #E4E4E7; }

        .invoices-page { font-family: 'Manrope', system-ui, -apple-system, sans-serif; color: var(--ink); max-width: 1100px; margin: 0 auto; padding: 24px 16px 60px; }

        .invoices-head { display: flex; justify-content: space-between; align-items: flex-end; flex-wrap: wrap; gap: 16px; margin-bottom: 26px; padding-bottom: 22px; border-bottom: 1px solid var(--line); }
        .invoices-head .eyebrow { font-size: .74rem; font-weight: 700; letter-spacing: .1em; text-transform: uppercase; color: var(--accent); margin-bottom: 6px; }
        .invoices-head h1 { font-size: 1.6rem; font-weight: 800; letter-spacing: -.02em; margin: 0; }
        .invoices-head .sub { font-size: .86rem; color: var(--sub); margin-top: 4px; }

        .alert-manrope { padding: 12px 16px; margin-bottom: 22px; font-size: .86rem; border-radius: 8px; display: flex; gap: 8px; }
        .alert-manrope.ok { background: #F0FDF4; color: #166534; }
        .alert-manrope.err { background: #FEF2F2; color: #B91C1C; }

        .table-wrap { width: 100%; overflow-x: auto; border: 1px solid var(--line); border-radius: 10px; }
        .invoices-table { width: 100%; border-collapse: collapse; font-size: .86rem; }
        .invoices-table th, .invoices-table td { padding: 12px 14px; text-align: left; white-space: nowrap; }
        .invoices-table th { font-weight: 700; text-transform: uppercase; font-size: .68rem; letter-spacing: .04em; color: var(--sub); background: #FAFAFA; border-bottom: 1px solid var(--line); }
        .invoices-table tbody tr { border-bottom: 1px solid var(--line); cursor: pointer; transition: background .1s; }
        .invoices-table tbody tr:last-child { border-bottom: none; }
        .invoices-table tbody tr:hover { background: #FAFAFA; }
        .invoices-table .empty-row td { text-align: center; color: var(--sub); white-space: normal; cursor: default; }
        .invoices-table .empty-row:hover { background: transparent; }

        .status-pill { display: inline-block; font-size: .72rem; font-weight: 700; text-transform: capitalize; padding: 3px 10px; border-radius: 20px; }

        .action-cell { cursor: default; }
        .action-cell .btn { margin: 0 3px 3px 0; }
        .disabled-btn { pointer-events: none; opacity: .5; }

        .invoices-actions { display: flex; justify-content: center; gap: 12px; flex-wrap: wrap; margin-top: 26px; }

        @media print { .no-print { display: none; } }
    </style>

    <div class="invoices-page">
        <div class="invoices-head">
            <div>
                <div class="eyebrow">Branch #<?php echo htmlspecialchars($branchId); ?></div>
                <h1>Invoices</h1>
                <div class="sub"><?php echo count($invoices); ?> invoice<?php echo count($invoices) === 1 ? '' : 's'; ?> on record</div>
            </div>
        </div>

        <?php if (isset($_GET['success'])) { ?>
            <div class="alert-manrope ok"><?php echo htmlspecialchars($_GET['success']); ?></div>
        <?php } elseif (isset($_GET['error'])) { ?>
            <div class="alert-manrope err"><?php echo htmlspecialchars($_GET['error']); ?></div>
        <?php } ?>

        <div class="table-wrap">
            <table class="invoices-table">
                <thead>
                    <tr>
                        <th>Invoice #</th>
                        <th>Date</th>
                        <th>Customer</th>
                        <th>Total (MWK)</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoices as $invoiceRow) {
                        $dateTime = new DateTime($invoiceRow['created_at']);
                        $formattedDate = $dateTime->format('Y-m-d');
                        $status = getStatus($invoiceRow['created_at'], $invoiceRow['valid_until'], $invoiceRow['status']);
                        $statusStyle = $statusStyles[$status] ?? $statusStyles['pending'];
                    ?>
                    <tr onclick="window.location.href='invoice_receipt.php?invoice_id=<?php echo $invoiceRow['invoice_id']; ?>'">
                        <td><?php echo htmlspecialchars($invoiceRow['invoice_number'] ?? $invoiceRow['invoice_id']); ?></td>
                        <td><?php echo $formattedDate; ?></td>
                        <td><?php echo htmlspecialchars($invoiceRow['customer_name']); ?></td>
                        <td><?php echo number_format($invoiceRow['total_amount'] ?? 0, 2); ?></td>
                        <td>
                            <span class="status-pill" style="background: <?php echo $statusStyle['bg']; ?>; color: <?php echo $statusStyle['fg']; ?>;">
                                <?php echo ucfirst($status); ?>
                            </span>
                        </td>
                        <td class="action-cell" onclick="event.stopPropagation();">
                            <a href="invoice_receipt.php?invoice_id=<?php echo $invoiceRow['invoice_id']; ?>&amp;document_type=proforma&amp;print=1"
                               class="btn btn-sm btn-secondary"
                               target="_blank"
                               rel="noopener">
                                <i class="fas fa-print"></i> Print Proforma
                            </a>
                            <?php if ($isUserAssignedBranch) { ?>
                                <a href="edit_invoice.php?invoice_id=<?php echo $invoiceRow['invoice_id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <form action="delete.invoice.php" method="POST" style="display: inline;">
                                    <input type="hidden" name="invoice_id" value="<?php echo $invoiceRow['invoice_id']; ?>">
                                    <input type="hidden" name="branch_id" value="<?php echo $branchId; ?>">
                                    <input type="hidden" name="search_term" value="<?php echo htmlspecialchars($_GET['search_term'] ?? ''); ?>">
                                    <input type="hidden" name="search_field" value="<?php echo htmlspecialchars($_GET['search_field'] ?? ''); ?>">
                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this invoice?');">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </form>
                            <?php } else { ?>
                                <span class="btn btn-sm btn-primary disabled-btn">
                                    <i class="fas fa-edit"></i> Edit
                                </span>
                                <span class="btn btn-sm btn-danger disabled-btn">
                                    <i class="fas fa-trash"></i> Delete
                                </span>
                            <?php } ?>
                            <?php if ($status === 'approved') { ?>
                                <a href="convert_to_inv.php?invoice_id=<?php echo $invoiceRow['invoice_id']; ?>" class="btn btn-sm btn-info">
                                    <i class="fas fa-file-invoice"></i> Generate Invoice
                                </a>
                                <a href="convert_to_dnote.php?invoice_id=<?php echo $invoiceRow['invoice_id']; ?>" class="btn btn-sm btn-warning">
                                    <i class="fas fa-truck"></i> Generate Delivery Note
                                </a>
                            <?php } ?>
                        </td>
                    </tr>
                    <?php } ?>
                    <?php if (empty($invoices)) { ?>
                    <tr class="empty-row">
                        <td colspan="6">No invoices found for this branch.</td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>

        <div class="invoices-actions no-print">
            <?php if ($isUserAssignedBranch) { ?>
                <a href="../sales/create_invoice.php?branch_id=<?php echo $branchId; ?>" class="btn btn-success">
                    <i class="fas fa-plus"></i> Create New Invoice
                </a>
            <?php } else { ?>
                <span class="btn btn-success disabled-btn">
                    <i class="fas fa-plus"></i> Create New Invoice
                </span>
            <?php } ?>
            <?php if ($isSuperAdmin) { ?>
                <a href="../sales/invoice_branch_selection.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Change Branch
                </a>
            <?php } else { ?>
                <a href="<?php echo getDashboardLink(); ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                </a>
            <?php } ?>
        </div>
    </div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
