<?php
include '../../includes/header.php';

$currentRole = strtolower(trim((string)($_SESSION['role'] ?? '')));
if (!in_array($currentRole, ['controller', 'admin', 'super_admin'], true)
    && !$auth->isController($_SESSION['user_id'])
    && !$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: /IMS/unauthorized.php');
    exit();
}

require_once __DIR__ . '/../../classes/DiscountPolicy.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../classes/Request.php';
require_once __DIR__ . '/../../classes/Quotation.php';
require_once __DIR__ . '/../../classes/CustomerService.php';
require_once __DIR__ . '/../../classes/LoanLaybuy.php';
require_once __DIR__ . '/../../classes/CreditSales.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Notifications.php';

$controllerNotifications = new Notifications($conn);
$controllerUnread = $controllerNotifications->getUnreadnotificationAdmin();

$sectionErrors = [];
function ctrlLoad(string $label, callable $cb): array {
    global $sectionErrors;
    try { $r = $cb(); return is_array($r) ? $r : []; }
    catch (Throwable $e) { $sectionErrors[$label] = $e->getMessage(); return []; }
}

$discountRequests   = ctrlLoad('discount_approvals', fn() => (new DiscountPolicy($conn))->getRequests('pending'));
$orders             = ctrlLoad('orders', function () use ($conn) {
    $s = $conn->prepare("SELECT o.*, b.branch_name, u.username AS created_by_name,
                                COALESCE((SELECT SUM(p.amount) FROM order_payments p WHERE p.order_id = o.order_id), o.amount_paid) as total_paid
                         FROM orders o
                         LEFT JOIN branches b ON b.branch_id = o.branch_id
                         LEFT JOIN users u ON o.created_by = u.user_id
                         ORDER BY o.created_at DESC LIMIT 60");
    $s->execute();
    return $s->fetchAll(PDO::FETCH_ASSOC);
});
$itemRequests       = ctrlLoad('branch_requests',  fn() => (new Request($conn))->getAllRequests());
$quotations         = ctrlLoad('quotations',        fn() => (new Quotation($conn))->getAllQuotations());
$laybuys            = ctrlLoad('laybuys', function () use ($conn) {
    $s = $conn->prepare("SELECT ll.*, b.branch_name FROM loans_laybuys ll
                         LEFT JOIN branches b ON b.branch_id = ll.branch_id
                         ORDER BY ll.created_at DESC LIMIT 60");
    $s->execute();
    return $s->fetchAll(PDO::FETCH_ASSOC);
});
$claims             = ctrlLoad('claims', function () use ($conn) {
    $logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'] ?? '', $_SESSION['role'] ?? '');
    return (new CustomerService($conn, $logger))->getRequests(null);
});
$pendingCreditSales = ctrlLoad('credit_sales', fn() => (new CreditSales($conn))->getCredits(null, 'pending_controller_approval', 50));

// ── helpers ────────────────────────────────────────────────────────────────
function ctrlStatusBadge(string $status): string {
    $map = [
        'pending'                     => 'bg-warning text-dark',
        'pending_controller_approval' => 'bg-warning text-dark',
        'approved'  => 'bg-success',
        'rejected'  => 'bg-danger',
        'completed' => 'bg-success',
        'delivered' => 'bg-success',
        'open'      => 'bg-primary',
        'in_progress'      => 'bg-info text-dark',
        'waiting_customer' => 'bg-warning text-dark',
        'resolved'  => 'bg-success',
        'closed'    => 'bg-secondary',
        'cancelled' => 'bg-danger',
        'active'    => 'bg-success',
    ];
    $cls = $map[strtolower(trim($status))] ?? 'bg-secondary';
    return '<span class="badge ' . $cls . '">' . htmlspecialchars(ucwords(str_replace('_', ' ', $status))) . '</span>';
}
function ctrlOpts(string $current, array $opts): void {
    foreach ($opts as $v => $l) {
        $sel = ((string)$current === (string)$v) ? ' selected' : '';
        echo '<option value="' . htmlspecialchars($v) . '"' . $sel . '>' . htmlspecialchars($l) . '</option>';
    }
}
function ctrlMoney(float $v): string { return 'MWK ' . number_format($v, 2); }
function ctrlDate(?string $d): string { return $d ? date('d M Y', strtotime($d)) : '—'; }

$pendingDiscounts = count($discountRequests);
$pendingOrders    = count(array_filter($orders,       fn($r) => ($r['status'] ?? '') === 'pending'));
$pendingRequests  = count(array_filter($itemRequests, fn($r) => in_array($r['status'] ?? '', ['pending','new'], true)));
$pendingQuotes    = count(array_filter($quotations,   fn($r) => ($r['status'] ?? '') === 'pending'));
$openClaims       = count(array_filter($claims,       fn($r) => !in_array($r['status'] ?? '', ['resolved','closed'], true)));
$pendingCredits   = count($pendingCreditSales);
?>

<style>
* { box-sizing: border-box; }

body { font-family: 'Roboto', sans-serif; font-size: 14px; line-height: 1.6; color: #333; background-color: #f8f9fa; }

.dashboard-container { display: flex; width: 100%; margin-top: 20px; }

/* ── Sidebar ── */
.sidebar {
    width: 250px;
    background-color: #343a40;
    color: white;
    padding: 20px;
    position: fixed;
    top: 0; left: 0;
    height: 100vh;
    overflow-y: auto;
    z-index: 100;
}
.sidebar-heading {
    padding: 10px 0;
    font-size: 15px;
    font-weight: 600;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    margin-bottom: 12px;
    color: #fff;
}
.sidebar-menu { list-style: none; padding: 0; margin: 0 0 20px 0; }
.sidebar-menu li { margin-bottom: 3px; }
.sidebar-menu a {
    display: flex; align-items: center; gap: 8px;
    padding: 9px 12px;
    color: rgba(255,255,255,0.8);
    text-decoration: none;
    border-radius: 4px;
    transition: background .2s, color .2s;
    font-size: 13px;
}
.sidebar-menu a:hover { background: rgba(255,255,255,0.12); color: #fff; }
.sidebar-menu a .badge { margin-left: auto; font-size: 10px; }
.sidebar-menu i { width: 18px; text-align: center; flex-shrink: 0; }
.sidebar-section { margin-bottom: 20px; }

/* ── Main ── */
.main-content { flex: 1; margin-left: 250px; padding: 20px; width: calc(100% - 250px); }

/* ── Summary cards ── */
.summary-card {
    border-radius: 6px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    transition: transform .25s, box-shadow .25s;
    margin-bottom: 20px;
}
.summary-card:hover { transform: translateY(-4px); box-shadow: 0 8px 16px rgba(0,0,0,0.15); }

/* ── Section cards ── */
.card { background: #fff; border-radius: 6px; box-shadow: 0 2px 5px rgba(0,0,0,0.08); margin-bottom: 20px; }
.card-header {
    padding: 12px 18px;
    border-bottom: 1px solid #eee;
    display: flex; align-items: center; gap: 8px;
    font-weight: 600; font-size: .9rem;
    background: #fff; border-radius: 6px 6px 0 0;
}
.card-header .ms-auto { margin-left: auto !important; }
.card-body { padding: 18px; }
.card-footer { padding: 12px 18px; background: #f9fafb; border-top: 1px solid #eee; border-radius: 0 0 6px 6px; }

/* ── Tables ── */
.ctrl-table { font-size: .82rem; margin-bottom: 0; }
.ctrl-table thead th {
    font-size: .7rem; text-transform: uppercase; letter-spacing: .05em;
    color: #6c757d; font-weight: 600;
    background: #f8f9fa; border-bottom: 2px solid #dee2e6;
    padding: .5rem .75rem;
}
.ctrl-table tbody td { padding: .5rem .75rem; vertical-align: middle; }
.ctrl-table tbody tr:hover { background: #f8f9fa; }
.ctrl-table .form-select, .ctrl-table .form-control { font-size: .8rem; padding: .25rem .5rem; height: auto; }

/* ── Follow-up rows ── */
.followup-row { border-bottom: 1px solid #f0f0f0; padding: .85rem 0; }
.followup-row:last-child { border-bottom: none; }

/* ── Empty state ── */
.ctrl-empty { padding: 1.75rem; text-align: center; color: #adb5bd; }
.ctrl-empty i { display: block; font-size: 1.8rem; margin-bottom: .4rem; }

@media (max-width: 768px) {
    .sidebar { width: 200px; }
    .main-content { margin-left: 200px; width: calc(100% - 200px); }
}
</style>

<div class="dashboard-container">

    <!-- ══ Sidebar ══════════════════════════════════════════════════════════ -->
    <div class="sidebar">
        <div class="sidebar-heading">Controller Dashboard</div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Approvals</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="#sect-discounts">
                        <i class="fas fa-percent"></i> Discount Approvals
                        <?php if ($pendingDiscounts): ?><span class="badge bg-danger"><?php echo $pendingDiscounts; ?></span><?php endif; ?>
                    </a>
                </li>
                <li>
                    <a href="/IMS/views/sales/credit_sales.php?status=pending_controller_approval">
                        <i class="fas fa-credit-card"></i> Credit Sales
                        <?php if ($pendingCredits): ?><span class="badge bg-warning text-dark"><?php echo $pendingCredits; ?></span><?php endif; ?>
                    </a>
                </li>
                <li>
                    <a href="#sect-requests">
                        <i class="fas fa-code-branch"></i> Branch Requests
                        <?php if ($pendingRequests): ?><span class="badge bg-warning text-dark"><?php echo $pendingRequests; ?></span><?php endif; ?>
                    </a>
                </li>
                <li>
                    <a href="#sect-quotations">
                        <i class="fas fa-file-invoice"></i> Quotations
                        <?php if ($pendingQuotes): ?><span class="badge bg-warning text-dark"><?php echo $pendingQuotes; ?></span><?php endif; ?>
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Operations</div>
            <ul class="sidebar-menu">
                <li><a href="#sect-orders"><i class="fas fa-shopping-bag"></i> Orders</a></li>
                <li><a href="#sect-laybuys"><i class="fas fa-calendar-alt"></i> Lay-Buys</a></li>
                <li><a href="/IMS/views/services/index.php"><i class="fas fa-tools"></i> Services</a></li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Customer Service</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="#sect-claims">
                        <i class="fas fa-clipboard-list"></i> Claims
                        <?php if ($openClaims): ?><span class="badge bg-primary"><?php echo $openClaims; ?></span><?php endif; ?>
                    </a>
                </li>
                <li><a href="#sect-followup"><i class="fas fa-headset"></i> Follow-Up Actions</a></li>
                <li><a href="/IMS/views/customer_service/index.php"><i class="fas fa-external-link-alt"></i> Full Claims Portal</a></li>
            </ul>
        </div>
    </div>

    <!-- ══ Main content ═════════════════════════════════════════════════════ -->
    <div class="main-content">

        <h1 class="mb-1">Controller Dashboard</h1>
        <p class="text-muted mb-4">Approvals, follow-ups and operations overview</p>

        <!-- Alerts -->
        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show"><i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($_GET['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if (isset($_GET['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show"><i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($_GET['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if ($sectionErrors): ?>
            <div class="alert alert-warning alert-dismissible fade show">
                <strong>Some sections could not load.</strong>
                <?php foreach ($sectionErrors as $lbl => $msg): ?><div class="small mt-1"><?php echo htmlspecialchars(ucwords(str_replace('_',' ',$lbl)) . ': ' . $msg); ?></div><?php endforeach; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        <?php if ($controllerUnread): ?>
            <?php foreach ($controllerUnread as $notification): ?>
                <div class="alert alert-info" role="alert">
                    <?php echo htmlspecialchars($notification['created_at']) . ' ' . htmlspecialchars($notification['message']); ?>
                    <form action="mark_message.php" method="POST" style="display:inline;">
                        <input type="hidden" name="notification_id" value="<?php echo htmlspecialchars($notification['notification_id']); ?>">
                        <input type="hidden" name="return_to" value="controller.php">
                        <button type="submit" name="delete_message" value="1" class="btn btn-sm btn-primary"><i class="fas fa-check"></i> Mark as read</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <!-- ── KPI summary cards ── -->
        <div class="row mb-4">
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card <?php echo $pendingDiscounts ? 'bg-danger text-white' : 'bg-light'; ?>">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-percent me-2"></i>Discount Approvals</h5>
                        <h2 class="mb-1"><?php echo $pendingDiscounts; ?></h2>
                        <p class="mb-0 small"><?php echo $pendingDiscounts ? 'Pending review' : 'All clear'; ?></p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card <?php echo $pendingCredits ? 'bg-warning text-dark' : 'bg-light'; ?>">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-credit-card me-2"></i>Credit Sales</h5>
                        <h2 class="mb-1"><?php echo $pendingCredits; ?></h2>
                        <p class="mb-0 small"><a href="/IMS/views/sales/credit_sales.php?status=pending_controller_approval" class="<?php echo $pendingCredits ? 'text-dark' : 'text-muted'; ?>">View pending approvals</a></p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-shopping-bag me-2"></i>Orders</h5>
                        <h2 class="mb-1"><?php echo count($orders); ?></h2>
                        <p class="mb-0 small"><?php echo $pendingOrders; ?> pending</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card bg-info text-dark">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-code-branch me-2"></i>Branch Requests</h5>
                        <h2 class="mb-1"><?php echo count($itemRequests); ?></h2>
                        <p class="mb-0 small"><?php echo $pendingRequests; ?> pending</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card bg-secondary text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-calendar-alt me-2"></i>Lay-Buys</h5>
                        <h2 class="mb-1"><?php echo count($laybuys); ?></h2>
                        <p class="mb-0 small">Total records</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 col-sm-6">
                <div class="card summary-card <?php echo $openClaims ? 'bg-dark text-white' : 'bg-light'; ?>">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-clipboard-list me-2"></i>Claims</h5>
                        <h2 class="mb-1"><?php echo count($claims); ?></h2>
                        <p class="mb-0 small"><?php echo $openClaims; ?> open</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── Discount Approvals ── -->
        <div class="card" id="sect-discounts">
            <div class="card-header">
                <i class="fas fa-percent text-danger"></i> Pending Discount Approvals
                <?php if ($pendingDiscounts): ?><span class="badge bg-danger"><?php echo $pendingDiscounts; ?></span><?php endif; ?>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table ctrl-table">
                        <thead><tr><th>Branch</th><th>Type</th><th>Value</th><th>Sale Total</th><th class="text-end">Actions</th></tr></thead>
                        <tbody>
                        <?php foreach ($discountRequests as $row): ?>
                            <tr>
                                <td class="fw-semibold"><?php echo htmlspecialchars($row['branch_name'] ?? $row['branch_id']); ?></td>
                                <td><?php echo htmlspecialchars(ucwords(str_replace('_',' ',$row['discount_type']))); ?></td>
                                <td><?php echo number_format((float)$row['discount_value'], 2); ?></td>
                                <td><?php echo ctrlMoney((float)$row['sale_total']); ?></td>
                                <td class="text-end">
                                    <form method="post" action="controller_action.php" class="d-inline">
                                        <input type="hidden" name="action" value="review_discount">
                                        <input type="hidden" name="request_id" value="<?php echo (int)$row['request_id']; ?>">
                                        <input type="hidden" name="status" value="approved">
                                        <input type="hidden" name="create_rule" value="1">
                                        <button class="btn btn-sm btn-success"><i class="fas fa-check me-1"></i>Approve</button>
                                    </form>
                                    <form method="post" action="controller_action.php" class="d-inline ms-1">
                                        <input type="hidden" name="action" value="review_discount">
                                        <input type="hidden" name="request_id" value="<?php echo (int)$row['request_id']; ?>">
                                        <input type="hidden" name="status" value="rejected">
                                        <button class="btn btn-sm btn-outline-danger"><i class="fas fa-times me-1"></i>Reject</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (!$discountRequests): ?>
                            <tr><td colspan="5"><div class="ctrl-empty"><i class="fas fa-check-circle text-success"></i>No pending discount approvals</div></td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer">
                <div class="text-muted small fw-semibold mb-2">Create Discount Preset Rule</div>
                <form method="post" action="controller_action.php" class="row g-2">
                    <input type="hidden" name="action" value="create_discount_rule">
                    <div class="col-md-4"><input class="form-control form-control-sm" name="rule_name" placeholder="Rule name" required></div>
                    <div class="col-md-3">
                        <select class="form-select form-select-sm" name="discount_type">
                            <option value="percentage">Percentage</option>
                            <option value="fixed">Fixed Amount</option>
                        </select>
                    </div>
                    <div class="col-md-3"><input class="form-control form-control-sm" type="number" step="0.01" min="0" name="discount_value" placeholder="Value" required></div>
                    <div class="col-md-2"><button class="btn btn-primary btn-sm w-100"><i class="fas fa-plus me-1"></i>Create</button></div>
                </form>
            </div>
        </div>

        <!-- ── Orders + Credit Sales ── -->
        <div class="row">
            <div class="col-lg-7">
                <div class="card" id="sect-orders">
                    <div class="card-header">
                        <i class="fas fa-shopping-bag text-primary"></i> Orders
                        <span class="badge bg-primary"><?php echo count($orders); ?></span>
                        <a href="../orders/" class="btn btn-sm btn-outline-primary ms-auto">All Orders</a>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" style="max-height:340px;overflow-y:auto">
                            <table class="table ctrl-table">
                                <thead><tr><th>Order</th><th>Customer</th><th>Branch</th><th>Paid</th><th>Status</th><th>Action</th></tr></thead>
                                <tbody>
                                <?php foreach (array_slice($orders, 0, 25) as $row): ?>
                                    <tr>
                                        <td><a href="../orders/order_details.php?order_id=<?php echo (int)$row['order_id']; ?>" class="fw-semibold text-decoration-none"><?php echo htmlspecialchars($row['order_number'] ?? ('ORD-'.$row['order_id'])); ?></a></td>
                                        <td><?php echo htmlspecialchars($row['customer_name'] ?? ''); ?></td>
                                        <td><?php echo htmlspecialchars($row['branch_name'] ?? '—'); ?></td>
                                        <td><?php echo ctrlMoney((float)($row['total_paid'] ?? 0)); ?></td>
                                        <td><?php echo ctrlStatusBadge($row['status'] ?? 'pending'); ?></td>
                                        <td>
                                            <form method="post" action="controller_action.php" class="d-flex gap-1">
                                                <input type="hidden" name="action" value="order_status">
                                                <input type="hidden" name="order_id" value="<?php echo (int)$row['order_id']; ?>">
                                                <select name="status" class="form-select form-select-sm" style="min-width:100px">
                                                    <?php ctrlOpts($row['status'] ?? 'pending', ['pending'=>'Pending','approved'=>'Approved','rejected'=>'Rejected','delivered'=>'Delivered','completed'=>'Completed']); ?>
                                                </select>
                                                <button class="btn btn-sm btn-outline-primary px-2"><i class="fas fa-save"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$orders): ?>
                                    <tr><td colspan="6"><div class="ctrl-empty"><i class="fas fa-inbox"></i>No orders found</div></td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-5">
                <div class="card h-100">
                    <div class="card-header">
                        <i class="fas fa-credit-card text-warning"></i> Pending Credit Approvals
                        <?php if ($pendingCredits): ?><span class="badge bg-warning text-dark"><?php echo $pendingCredits; ?></span><?php endif; ?>
                        <a href="/IMS/views/sales/credit_sales.php?status=pending_controller_approval" class="btn btn-sm btn-outline-warning ms-auto">Full View</a>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" style="max-height:340px;overflow-y:auto">
                            <table class="table ctrl-table">
                                <thead><tr><th>Ref</th><th>Customer</th><th>Total</th><th>Status</th></tr></thead>
                                <tbody>
                                <?php foreach (array_slice($pendingCreditSales, 0, 20) as $row): ?>
                                    <tr>
                                        <td><a href="/IMS/views/sales/credit_receipt.php?credit_id=<?php echo (int)$row['credit_id']; ?>" class="fw-semibold text-decoration-none"><?php echo htmlspecialchars($row['credit_number'] ?? ('CR-'.$row['credit_id'])); ?></a></td>
                                        <td><?php echo htmlspecialchars($row['customer_name'] ?? ''); ?></td>
                                        <td><?php echo ctrlMoney((float)($row['total_amount'] ?? 0)); ?></td>
                                        <td><?php echo ctrlStatusBadge($row['status'] ?? 'pending'); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$pendingCreditSales): ?>
                                    <tr><td colspan="4"><div class="ctrl-empty"><i class="fas fa-check-circle text-success"></i>No pending credit approvals</div></td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── Branch Requests + Quotations ── -->
        <div class="row">
            <div class="col-lg-6">
                <div class="card" id="sect-requests">
                    <div class="card-header">
                        <i class="fas fa-code-branch text-info"></i> Branch Requests
                        <?php if ($pendingRequests): ?><span class="badge bg-warning text-dark"><?php echo $pendingRequests; ?></span><?php endif; ?>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" style="max-height:300px;overflow-y:auto">
                            <table class="table ctrl-table">
                                <thead><tr><th>Request</th><th>Status</th><th class="text-end">Actions</th></tr></thead>
                                <tbody>
                                <?php foreach (array_slice($itemRequests, 0, 20) as $row): ?>
                                    <tr>
                                        <td class="fw-semibold"><?php echo htmlspecialchars($row['request_number'] ?? ('REQ-'.$row['request_id'])); ?></td>
                                        <td><?php echo ctrlStatusBadge($row['status'] ?? 'pending'); ?></td>
                                        <td class="text-end">
                                            <form method="post" action="controller_action.php" class="d-inline-flex gap-1 justify-content-end">
                                                <input type="hidden" name="action" value="request_status">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['request_id']; ?>">
                                                <a href="../sales/request_receipt.php?request_id=<?php echo (int)$row['request_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-eye"></i></a>
                                                <button name="status" value="approved" class="btn btn-sm btn-success"><i class="fas fa-check"></i></button>
                                                <button name="status" value="rejected" class="btn btn-sm btn-outline-danger"><i class="fas fa-times"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$itemRequests): ?>
                                    <tr><td colspan="3"><div class="ctrl-empty"><i class="fas fa-inbox"></i>No branch requests</div></td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-6">
                <div class="card" id="sect-quotations">
                    <div class="card-header">
                        <i class="fas fa-file-invoice text-secondary"></i> Quotations
                        <?php if ($pendingQuotes): ?><span class="badge bg-warning text-dark"><?php echo $pendingQuotes; ?></span><?php endif; ?>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" style="max-height:300px;overflow-y:auto">
                            <table class="table ctrl-table">
                                <thead><tr><th>Quotation</th><th>Status</th><th class="text-end">Actions</th></tr></thead>
                                <tbody>
                                <?php foreach (array_slice($quotations, 0, 20) as $row): ?>
                                    <tr>
                                        <td class="fw-semibold"><?php echo htmlspecialchars($row['quotation_number'] ?? ('QT-'.$row['quotation_id'])); ?></td>
                                        <td><?php echo ctrlStatusBadge($row['status'] ?? 'pending'); ?></td>
                                        <td class="text-end">
                                            <form method="post" action="controller_action.php" class="d-inline-flex gap-1 justify-content-end">
                                                <input type="hidden" name="action" value="quotation_status">
                                                <input type="hidden" name="id" value="<?php echo (int)$row['quotation_id']; ?>">
                                                <a href="../sales/quotation_receipt.php?quotation_id=<?php echo (int)$row['quotation_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-eye"></i></a>
                                                <button name="status" value="approved" class="btn btn-sm btn-success"><i class="fas fa-check"></i></button>
                                                <button name="status" value="rejected" class="btn btn-sm btn-outline-danger"><i class="fas fa-times"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (!$quotations): ?>
                                    <tr><td colspan="3"><div class="ctrl-empty"><i class="fas fa-inbox"></i>No quotations</div></td></tr>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── Claims ── -->
        <div class="card" id="sect-claims">
            <div class="card-header">
                <i class="fas fa-clipboard-list text-success"></i> Customer Claims
                <span class="badge bg-secondary"><?php echo count($claims); ?> total</span>
                <?php if ($openClaims): ?><span class="badge bg-primary"><?php echo $openClaims; ?> open</span><?php endif; ?>
                <a href="/IMS/views/customer_service/index.php" class="btn btn-sm btn-outline-success ms-auto">Full Portal</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height:320px;overflow-y:auto">
                    <table class="table ctrl-table">
                        <thead><tr><th>Request</th><th>Customer</th><th>Subject</th><th>Status</th><th>Delivery Date</th><th>Receipt</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach (array_slice($claims, 0, 30) as $row): ?>
                            <tr>
                                <td>
                                    <div class="fw-semibold"><?php echo htmlspecialchars($row['request_no'] ?? ('CLM-'.$row['request_id'])); ?></div>
                                    <small class="text-muted"><?php echo htmlspecialchars($row['branch_name'] ?? '—'); ?></small>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($row['customer_name']); ?>
                                    <?php if (!empty($row['customer_phone'])): ?><br><small class="text-muted"><?php echo htmlspecialchars($row['customer_phone']); ?></small><?php endif; ?>
                                </td>
                                <td style="max-width:160px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($row['subject']); ?></td>
                                <td><?php echo ctrlStatusBadge($row['status'] ?? 'open'); ?></td>
                                <td>
                                    <?php if (!empty($row['delivery_date'])): ?>
                                        <span class="text-primary fw-semibold"><?php echo ctrlDate($row['delivery_date']); ?></span>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($row['receipt_number'])): ?>
                                        <a href="../tracking/txn_tracking.php?transaction_id=<?php echo urlencode($row['receipt_number']); ?>" target="_blank" class="small text-decoration-none"><i class="fas fa-receipt me-1"></i><?php echo htmlspecialchars($row['receipt_number']); ?></a>
                                    <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                                </td>
                                <td><a href="/IMS/views/customer_service/index.php?request_id=<?php echo (int)$row['request_id']; ?>" class="btn btn-sm btn-outline-primary">Open</a></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (!$claims): ?>
                            <tr><td colspan="7"><div class="ctrl-empty"><i class="fas fa-check-circle text-success"></i>No claims on record</div></td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ── Claim Follow-Up ── -->
        <div class="card" id="sect-followup">
            <div class="card-header">
                <i class="fas fa-headset text-primary"></i> Claim Follow-Up Actions
                <small class="text-muted fw-normal ms-2">Update status, resolution &amp; delivery date</small>
            </div>
            <div class="card-body px-3 py-2">
            <?php
                $followupClaims = array_values(array_filter($claims, fn($r) => !in_array($r['status'] ?? '', ['closed'], true)));
                $followupClaims = array_slice($followupClaims, 0, 15);
            ?>
            <?php if (!$followupClaims): ?>
                <div class="ctrl-empty"><i class="fas fa-check-double text-success"></i>All claims are closed — no follow-up required.</div>
            <?php else: ?>
                <?php foreach ($followupClaims as $row):
                    $dlvInput = !empty($row['delivery_date']) ? date('Y-m-d', strtotime($row['delivery_date'])) : '';
                ?>
                <form method="post" action="controller_action.php" class="followup-row">
                    <input type="hidden" name="action" value="claim_followup">
                    <input type="hidden" name="request_id" value="<?php echo (int)$row['request_id']; ?>">
                    <input type="hidden" name="visibility" value="internal">
                    <div class="row align-items-end g-2">
                        <div class="col-xl-3 col-md-6">
                            <div class="fw-semibold"><?php echo htmlspecialchars($row['request_no'] ?? ('CLM-'.$row['request_id'])); ?></div>
                            <div class="text-muted small">
                                <?php echo htmlspecialchars($row['branch_name'] ?? '—'); ?>
                                <?php if (!empty($row['receipt_number'])): ?>
                                    · <a href="../tracking/txn_tracking.php?transaction_id=<?php echo urlencode($row['receipt_number']); ?>" target="_blank" class="text-decoration-none"><?php echo htmlspecialchars($row['receipt_number']); ?></a>
                                <?php endif; ?>
                            </div>
                            <div class="mt-1" style="font-size:.82rem"><?php echo htmlspecialchars($row['subject'] ?? ''); ?></div>
                            <div class="mt-1"><?php echo ctrlStatusBadge($row['status'] ?? 'open'); ?></div>
                        </div>
                        <div class="col-xl-2 col-md-6 col-sm-6">
                            <label class="form-label text-muted small mb-1">Status</label>
                            <select name="status" class="form-select form-select-sm">
                                <?php ctrlOpts($row['status'] ?? 'open', ['open'=>'Open','in_progress'=>'In Progress','waiting_customer'=>'Waiting Customer','approved'=>'Approved','rejected'=>'Rejected','resolved'=>'Resolved','closed'=>'Closed']); ?>
                            </select>
                        </div>
                        <div class="col-xl-2 col-md-4 col-sm-6">
                            <label class="form-label text-muted small mb-1">Delivery Date</label>
                            <input type="date" name="delivery_date" class="form-control form-control-sm" value="<?php echo htmlspecialchars($dlvInput); ?>">
                        </div>
                        <div class="col-xl-3 col-md-8">
                            <label class="form-label text-muted small mb-1">Resolution / Action</label>
                            <input type="text" name="resolution" class="form-control form-control-sm" value="<?php echo htmlspecialchars($row['resolution'] ?? ''); ?>" placeholder="Replacement approved, repair booked…">
                        </div>
                        <div class="col-xl-1 col-md-6">
                            <label class="form-label text-muted small mb-1">Note</label>
                            <input type="text" name="note" class="form-control form-control-sm" placeholder="Note…">
                        </div>
                        <div class="col-xl-1 col-md-6">
                            <label class="form-label d-block small mb-1">&nbsp;</label>
                            <button class="btn btn-primary btn-sm w-100"><i class="fas fa-save"></i></button>
                        </div>
                    </div>
                </form>
                <?php endforeach; ?>
            <?php endif; ?>
            </div>
        </div>

        <!-- ── Lay-Buys ── -->
        <div class="card" id="sect-laybuys">
            <div class="card-header">
                <i class="fas fa-calendar-alt text-primary"></i> Lay-Buys
                <span class="badge bg-secondary"><?php echo count($laybuys); ?></span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive" style="max-height:320px;overflow-y:auto">
                    <table class="table ctrl-table">
                        <thead><tr><th>Record</th><th>Branch</th><th>Customer</th><th>Total</th><th>Paid</th><th>Balance</th><th>Status</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach (array_slice($laybuys, 0, 30) as $row):
                            $total   = (float)($row['amount'] ?? 0);
                            $paid    = (float)($row['total_paid'] ?? 0);
                            $balance = $total - $paid;
                        ?>
                            <tr>
                                <td class="fw-semibold"><?php echo htmlspecialchars($row['record_number'] ?? ('REC-'.$row['record_id'])); ?></td>
                                <td><?php echo htmlspecialchars($row['branch_name'] ?? '—'); ?></td>
                                <td><?php echo htmlspecialchars($row['customer_name'] ?? ''); ?></td>
                                <td><?php echo ctrlMoney($total); ?></td>
                                <td class="text-success"><?php echo ctrlMoney($paid); ?></td>
                                <td class="<?php echo $balance > 0 ? 'text-danger fw-semibold' : 'text-muted'; ?>"><?php echo ctrlMoney($balance); ?></td>
                                <td><?php echo ctrlStatusBadge($row['status'] ?? 'active'); ?></td>
                                <td><a href="../laybuy_&_loans/laybuy_and_loans_receipt.php?record_id=<?php echo (int)$row['record_id']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-eye"></i></a></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (!$laybuys): ?>
                            <tr><td colspan="8"><div class="ctrl-empty"><i class="fas fa-inbox"></i>No lay-buy records</div></td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div><!-- /main-content -->
</div><!-- /dashboard-container -->

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