<?php
// ── PHP logic BEFORE header (header starts output) ──────────────────────────
require_once __DIR__ . '/../../classes/Branding.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';

if (session_status() === PHP_SESSION_NONE) session_start();

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

require_once __DIR__ . '/../../includes/auth.php';
$auth     = new Auth($conn);
$auth->requireLogin();

$orderObj = new Order($conn);
$branch   = new Branch($conn);

$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/orders/order_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/orders/order_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 = ((int)$branchId === (int)$userBranchId) || $isSuperAdmin;
$orders = $orderObj->getOrdersByBranch($branchId);

$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branchId]);
$branchName = $stmt->fetchColumn();

// Status helpers
function getOrderStatus($delivery_date, $status) {
    $now = new DateTime();
    $d   = new DateTime($delivery_date);
    if ($now > $d && $status === 'pending') return 'overdue';
    return $status;
}

$statusPill = [
    'pending'   => 'warning',
    'approved'  => 'info',
    'rejected'  => 'danger',
    'delivered' => 'primary',
    'completed' => 'success',
    'overdue'   => 'danger',
];

// Stats
$totalOrders    = count($orders);
$completedCount = count(array_filter($orders, fn($o) => $o['status'] === 'completed'));
$pendingCount   = count(array_filter($orders, fn($o) => in_array($o['status'], ['pending', 'approved', 'delivered'])));

// ── Header include (outputs <!DOCTYPE html> … <main> ) ───────────────────────
include __DIR__ . '/../../includes/header.php';
?>

<style>
    /* ── Google Font (matches order_details.php / create_order.php / edit_sale.php) ── */
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

    *, *::before, *::after { box-sizing: border-box; }
    :root {
        --brand:          #4F46E5;
        --brand-dark:     #3730A3;
        --brand-light:    #EEF2FF;
        --brand-ring:     rgba(79,70,229,.18);

        --success:        #059669;
        --success-bg:     #ECFDF5;
        --success-border: #A7F3D0;
        --danger:         #DC2626;
        --danger-bg:      #FEF2F2;
        --danger-border:  #FECACA;
        --warning:        #D97706;
        --warning-bg:     #FFFBEB;
        --warning-border: #FDE68A;
        --info:           #0284C7;
        --info-bg:        #E0F2FE;

        --n900: #0F172A; --n800: #1E293B; --n700: #334155; --n600: #475569;
        --n500: #64748B; --n400: #94A3B8; --n300: #CBD5E1; --n200: #E2E8F0;
        --n100: #F1F5F9; --n50:  #F8FAFC; --white: #FFFFFF;

        --topbar-h: 58px;
        --r-sm: 6px; --r: 10px; --r-lg: 14px;
        --s2: 0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.04);
    }

    body { font-family: 'Inter', system-ui, -apple-system, sans-serif; }

    /* ── Top Bar ─────────────────────────────────────── */
    .pos-topbar {
        display: flex; align-items: center; justify-content: space-between;
        background: var(--n900); color: var(--white);
        min-height: var(--topbar-h);
        border-radius: var(--r);
        border-bottom: 3px solid var(--brand);
        padding: 12px 22px; margin-bottom: 20px; gap: 12px; flex-wrap: wrap;
    }
    .pos-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
    .pos-topbar .brand-icon {
        width: 34px; height: 34px; border-radius: var(--r-sm);
        background: var(--brand); display: flex; align-items: center;
        justify-content: center; font-size: 15px; color: #fff; flex-shrink: 0;
    }
    .pos-topbar-title-wrap { line-height: 1.25; min-width: 0; }
    .pos-topbar-title { font-size: 1rem; font-weight: 700; color: var(--white); display: block; }
    .pos-topbar-sub { font-size: .76rem; color: var(--n400); }
    .pos-topbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; flex-wrap: wrap; }

    .btn-topbar {
        display: inline-flex; align-items: center; gap: 6px;
        padding: 8px 16px; border-radius: var(--r-sm); font-size: .82rem; font-weight: 600;
        text-decoration: none; border: none; cursor: pointer; transition: all .15s;
    }
    .btn-topbar-primary { background: var(--success); color: #fff; }
    .btn-topbar-primary:hover { background: #047857; color: #fff; transform: translateY(-1px); }
    .btn-topbar-primary.disabled { background: var(--n700); color: var(--n400); cursor: not-allowed; pointer-events: none; }
    .btn-topbar-ghost {
        background: rgba(255,255,255,.08); color: var(--n300); border: 1px solid rgba(255,255,255,.14);
    }
    .btn-topbar-ghost:hover { background: rgba(255,255,255,.14); color: #fff; }

    /* ── Alerts ──────────────────────────────────────── */
    .alert { border-radius: var(--r-sm); font-size: .88rem; }
    .alert-success { background: var(--success-bg); color: #065F46; border: 1px solid var(--success-border); }
    .alert-danger  { background: var(--danger-bg); color: #991B1B; border: 1px solid var(--danger-border); }

    /* ── Stat tiles ──────────────────────────────────── */
    .stat-tile {
        background: var(--white); border-radius: var(--r); border: 1px solid var(--n200);
        box-shadow: var(--s2); padding: 16px 18px;
        display: flex; align-items: center; gap: 14px;
        border-top: 3px solid var(--n300); transition: transform .15s;
    }
    .stat-tile:hover { transform: translateY(-2px); }
    .stat-tile.total { border-top-color: var(--brand); }
    .stat-tile.active { border-top-color: var(--warning); }
    .stat-tile.done { border-top-color: var(--success); }
    .stat-icon {
        width: 42px; height: 42px; border-radius: 50%; flex-shrink: 0;
        display: flex; align-items: center; justify-content: center; font-size: 1.1rem;
    }
    .stat-tile.total .stat-icon { background: var(--brand-light); color: var(--brand); }
    .stat-tile.active .stat-icon { background: var(--warning-bg); color: var(--warning); }
    .stat-tile.done .stat-icon { background: var(--success-bg); color: var(--success); }
    .stat-value { font-size: 1.6rem; font-weight: 800; color: var(--n900); line-height: 1; }
    .stat-label { font-size: .68rem; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: var(--n500); margin-top: 3px; }

    /* ── Orders table card ───────────────────────────── */
    .pos-card {
        background: var(--white); border-radius: var(--r); border: 1px solid var(--n200);
        box-shadow: var(--s2); overflow: hidden;
    }
    .pos-card-header {
        display: flex; justify-content: space-between; align-items: center;
        padding: 14px 20px; border-bottom: 1px solid var(--n200); background: var(--n50);
    }
    .pos-card-header .title { font-size: .92rem; font-weight: 700; color: var(--n800); }
    .pos-card-header .count { font-size: .78rem; color: var(--n500); }

    .orders-tbl { width: 100%; border-collapse: collapse; }
    .orders-tbl thead th {
        font-size: .68rem; font-weight: 700; text-transform: uppercase; letter-spacing: .05em;
        color: var(--n500); background: var(--n50); border-bottom: 2px solid var(--n200);
        padding: 10px 14px; text-align: left; white-space: nowrap;
    }
    .orders-tbl td { padding: 11px 14px; font-size: .84rem; color: var(--n700); vertical-align: middle; border-bottom: 1px solid var(--n100); }
    .orders-tbl tbody tr { cursor: pointer; transition: background .12s; }
    .orders-tbl tbody tr:hover { background: var(--brand-light); }
    .orders-tbl tbody tr:hover td { color: var(--n900); }

    /* Status pill (reused style from order_details.php) */
    .status-pill {
        font-size: .7rem; font-weight: 700; padding: 4px 11px; border-radius: 20px;
        text-transform: uppercase; letter-spacing: .04em; white-space: nowrap;
    }
    .status-pill.warning { background: var(--warning-bg); color: var(--warning); }
    .status-pill.info    { background: var(--info-bg); color: var(--info); }
    .status-pill.danger  { background: var(--danger-bg); color: var(--danger); }
    .status-pill.primary { background: var(--brand-light); color: var(--brand); }
    .status-pill.success { background: var(--success-bg); color: var(--success); }
    .status-pill.secondary { background: var(--n200); color: var(--n600); }

    /* Balance pill */
    .bal-pill { display: inline-block; padding: 4px 11px; border-radius: 20px; font-size: .76rem; font-weight: 600; }
    .bal-paid    { background: var(--success-bg); color: var(--success); }
    .bal-partial { background: var(--warning-bg); color: var(--warning); }
    .bal-unpaid  { background: var(--danger-bg); color: var(--danger); }

    /* Action buttons */
    .btn-tbl {
        width: 30px; height: 30px; border-radius: var(--r-sm); border: none;
        display: inline-flex; align-items: center; justify-content: center;
        font-size: .78rem; margin-right: 4px; text-decoration: none; transition: all .12s;
    }
    .btn-tbl-primary { background: var(--brand-light); color: var(--brand); }
    .btn-tbl-primary:hover { background: var(--brand); color: #fff; }
    .btn-tbl-success { background: var(--success-bg); color: var(--success); }
    .btn-tbl-success:hover { background: var(--success); color: #fff; }
    .btn-tbl-danger  { background: var(--danger-bg); color: var(--danger); }
    .btn-tbl-danger:hover { background: var(--danger); color: #fff; }
    .btn-tbl-purple  { background: #F3E8FF; color: #9333EA; }
    .btn-tbl-purple:hover { background: #9333EA; color: #fff; }
    .btn-tbl.disabled { background: var(--n100); color: var(--n300); cursor: not-allowed; pointer-events: none; }

    .empty-state { padding: 3.5rem 1rem; text-align: center; color: var(--n400); }
    .empty-state i { font-size: 2.5rem; display: block; margin-bottom: .75rem; }

    /* DataTables controls restyle */
    .dataTables_wrapper .dataTables_filter input,
    .dataTables_wrapper .dataTables_length select {
        border: 1.5px solid var(--n300); border-radius: var(--r-sm); padding: 5px 10px; font-size: .82rem;
    }
    .dataTables_wrapper .dataTables_filter input:focus { outline: none; border-color: var(--brand); }
    .page-link { color: var(--brand); }
    .page-item.active .page-link { background: var(--brand); border-color: var(--brand); }

    @media print { .no-print { display: none !important; } }
    @media (max-width: 768px) {
        .pos-topbar { border-radius: 0; margin: 0 0 16px; }
    }
</style>

<div class="pos-topbar no-print">
    <div class="pos-topbar-left">
        <div class="brand-icon"><i class="fas fa-clipboard-list"></i></div>
        <div class="pos-topbar-title-wrap">
            <span class="pos-topbar-title">Orders</span>
            <span class="pos-topbar-sub"><?php echo htmlspecialchars($branchName ?: ('Branch ' . $branchId)); ?></span>
        </div>
    </div>
    <div class="pos-topbar-right">
        <?php if ($isUserAssignedBranch): ?>
            <a href="create_order.php?branch_id=<?php echo $branchId; ?>" class="btn-topbar btn-topbar-primary">
                <i class="fas fa-plus"></i> New Order
            </a>
        <?php else: ?>
            <button class="btn-topbar btn-topbar-primary disabled" disabled>
                <i class="fas fa-plus"></i> New Order
            </button>
        <?php endif; ?>

        <?php if ($isSuperAdmin): ?>
            <a href="../orders/order_branch_selection.php" class="btn-topbar btn-topbar-ghost">
                <i class="fas fa-exchange-alt"></i> Change Branch
            </a>
        <?php else: ?>
            <a href="<?php echo getDashboardLink(); ?>" class="btn-topbar btn-topbar-ghost">
                <i class="fas fa-home"></i> Dashboard
            </a>
        <?php endif; ?>
    </div>
</div>

<?php if (isset($_GET['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars(urldecode($_GET['success'])); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php elseif (isset($_GET['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars(urldecode($_GET['error'])); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- ── Stats ─────────────────────────────────────────────────── -->
<div class="row g-3 mb-3 no-print">
    <div class="col-sm-4">
        <div class="stat-tile total">
            <div class="stat-icon"><i class="fas fa-clipboard-list"></i></div>
            <div>
                <div class="stat-value"><?php echo $totalOrders; ?></div>
                <div class="stat-label">Total Orders</div>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="stat-tile active">
            <div class="stat-icon"><i class="fas fa-clock"></i></div>
            <div>
                <div class="stat-value"><?php echo $pendingCount; ?></div>
                <div class="stat-label">Active</div>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="stat-tile done">
            <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
            <div>
                <div class="stat-value"><?php echo $completedCount; ?></div>
                <div class="stat-label">Completed</div>
            </div>
        </div>
    </div>
</div>

<!-- ── Orders Table ───────────────────────────────────────────── -->
<div class="pos-card">
    <div class="pos-card-header">
        <span class="title">Order List</span>
        <span class="count"><?php echo $totalOrders; ?> record<?php echo $totalOrders !== 1 ? 's' : ''; ?></span>
    </div>
    <div class="table-responsive">
        <table class="orders-tbl" id="ordersTable" style="width:100%">
            <thead>
                <tr>
                    <th>Order #</th>
                    <th>Item</th>
                    <th>Customer</th>
                    <th>Price (MWK)</th>
                    <th>Paid (MWK)</th>
                    <th>Balance</th>
                    <th>Delivery Date</th>
                    <th>Status</th>
                    <th class="no-print">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($orders)): ?>
                <tr>
                    <td colspan="9">
                        <div class="empty-state">
                            <i class="fas fa-clipboard-list"></i>
                            No orders found for this branch.
                        </div>
                    </td>
                </tr>
                <?php else: ?>
                <?php foreach ($orders as $o):
                    $st    = getOrderStatus($o['delivery_date'], $o['status']);
                    $pill  = $statusPill[$st] ?? 'secondary';
                    $price = (float)$o['price'];
                    $paid  = isset($o['total_paid']) ? (float)$o['total_paid'] : (float)$o['amount_paid'];
                    $bal   = round($price - $paid, 2);
                    $isFull = ($bal <= 0.009);

                    if ($o['status'] === 'completed') {
                        $balClass = 'bal-paid'; $balLabel = 'Paid';
                    } elseif ($isFull) {
                        $balClass = 'bal-paid'; $balLabel = 'Full – Pending Code';
                    } elseif ($paid > 0) {
                        $balClass = 'bal-partial'; $balLabel = number_format(max(0,$bal), 2);
                    } else {
                        $balClass = 'bal-unpaid'; $balLabel = number_format($price, 2);
                    }
                ?>
                <tr onclick="window.location.href='order_details.php?order_id=<?php echo $o['order_id']; ?>'">
                    <td><strong><?php echo htmlspecialchars($o['order_number'] ?? '—'); ?></strong></td>
                    <td><?php echo htmlspecialchars($o['item_name']); ?></td>
                    <td><?php echo htmlspecialchars($o['customer_name']); ?></td>
                    <td><?php echo number_format($price, 2); ?></td>
                    <td><?php echo number_format($paid, 2); ?></td>
                    <td><span class="bal-pill <?php echo $balClass; ?>"><?php echo $balLabel; ?></span></td>
                    <td><?php echo date('d M Y', strtotime($o['delivery_date'])); ?></td>
                    <td><span class="status-pill <?php echo $pill; ?>"><?php echo ucfirst($st); ?></span></td>
                    <td class="no-print" onclick="event.stopPropagation();">
                        <?php if ($isUserAssignedBranch): ?>
                            <?php if ($o['status'] !== 'completed'): ?>
                                <a href="edit_order.php?order_id=<?php echo $o['order_id']; ?>"
                                   class="btn-tbl btn-tbl-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php if (!$isFull): ?>
                                <a href="add_order_payment.php?order_id=<?php echo $o['order_id']; ?>"
                                   class="btn-tbl btn-tbl-success" title="Add Payment">
                                    <i class="fas fa-plus-circle"></i>
                                </a>
                                <?php endif; ?>
                                <form action="delete_order.php" method="POST" class="d-inline">
                                    <input type="hidden" name="order_id" value="<?php echo $o['order_id']; ?>">
                                    <button type="submit" class="btn-tbl btn-tbl-danger"
                                            onclick="event.stopPropagation();return confirm('Delete this order?');"
                                            title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            <?php else: ?>
                                <a href="order_receipt.php?order_id=<?php echo $o['order_id']; ?>"
                                   class="btn-tbl btn-tbl-purple" title="View Receipt">
                                    <i class="fas fa-receipt"></i>
                                </a>
                                <a href="order_receipt.php?order_id=<?php echo $o['order_id']; ?>"
                                   class="btn-tbl btn-tbl-primary" title="Print Receipt" target="_blank" rel="noopener">
                                    <i class="fas fa-print"></i>
                                </a>
                            <?php endif; ?>
                        <?php else: ?>
                            <button class="btn-tbl btn-tbl-primary disabled" disabled>
                                <i class="fas fa-edit"></i>
                            </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
    // Initialise DataTable for search + pagination
    $(document).ready(function() {
        if ($('#ordersTable tbody tr').length > 1) {
            $('#ordersTable').DataTable({
                pageLength: 25,
                order: [[0, 'desc']],
                columnDefs: [
                    { orderable: false, targets: 8 }  // Actions column
                ],
                language: {
                    search: 'Search orders:',
                    emptyTable: 'No orders found for this branch.'
                }
            });
        }
    });
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
