<?php
session_start();
require_once '../config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$userId = (int)$_SESSION['user_id'];

/* =========================
   DASHBOARD COUNTS
========================= */
$totalOrders = 0;
$pendingOrders = 0;
$approvedOrders = 0;
$rejectedOrders = 0;

$res = $conn->query("SELECT COUNT(*) AS c FROM orders");
if ($res) $totalOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Pending'");
if ($res) $pendingOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Approved'");
if ($res) $approvedOrders = (int)($res->fetch_assoc()['c'] ?? 0);

$res = $conn->query("SELECT COUNT(*) AS c FROM orders WHERE status='Rejected'");
if ($res) $rejectedOrders = (int)($res->fetch_assoc()['c'] ?? 0);

/* =========================
   FETCH ORDERS
========================= */
$orders = [];

$query = "
SELECT
    o.id,
    o.qty,
    o.notes,
    o.status,
    o.created_at,
    p.product_name,
    mr.name AS mr_name,
    mgr.name AS manager_name,
    ag.name AS agency_name,
    COALESCE(mr.country, mgr.country, ag.country) AS country
FROM orders o
LEFT JOIN products p
    ON p.id = o.product_id
LEFT JOIN users mr
    ON mr.id = o.mr_id
LEFT JOIN users mgr
    ON mgr.id = mr.manager_id
LEFT JOIN users ag
    ON ag.id = mgr.agency_id
ORDER BY o.id DESC
";

$result = mysqli_query($conn, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $orders[] = $row;
    }
}

/* =========================
   HELPERS
========================= */
function e($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

function badge($status) {
    $status = strtolower(trim($status ?? ''));
    if ($status === 'approved') return 'approved';
    if ($status === 'rejected') return 'rejected';
    return 'pending';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Order History</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
:root{
    --sidebar-width:260px;
    --bg:#f1f5f9;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --primary:#334155;
    --primary-dark:#1e293b;
    --success:#16a34a;
    --danger:#dc2626;
    --warning:#f59e0b;
    --border:#e2e8f0;
    --shadow:0 2px 10px rgba(15,23,42,.04);
    --radius:16px;
}

*{ box-sizing:border-box; }

body{
    margin:0;
    font-family:'Inter',sans-serif;
    background:#f1f5f9;
    color:var(--text);
}

.page{
    margin-left:var(--sidebar-width);
    padding:78px 14px 14px;
    min-height:100vh;
}

.hero{
    background:#fff;
    border:1px solid var(--border);
    border-radius:18px;
    padding:15px 18px;
    margin-bottom:12px;
    box-shadow:var(--shadow);
}

.hero h1{
    margin:0;
    font-size:18px;
    font-weight:800;
    display:flex;
    align-items:center;
    gap:8px;
    color:#0f172a;
}

.hero h1 i{
    color:#334155;
}

.hero p{
    margin:5px 0 0;
    font-size:12px;
    color:#64748b;
}

.stats{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin-bottom:12px;
}

.stat-card{
    background:#fff;
    border:1px solid var(--border);
    border-radius:16px;
    padding:12px;
    box-shadow:var(--shadow);
}

.stat-card .label{
    font-size:10px;
    font-weight:700;
    color:#64748b;
    text-transform:uppercase;
    letter-spacing:.3px;
}

.stat-card .value{
    margin-top:4px;
    font-size:18px;
    font-weight:800;
    color:#0f172a;
}

.stat-card.total .value{ color:#334155; }
.stat-card.pending .value{ color:#92400e; }
.stat-card.approved .value{ color:#166534; }
.stat-card.rejected .value{ color:#991b1b; }

.card{
    background:#fff;
    border:1px solid var(--border);
    border-radius:18px;
    overflow:hidden;
    box-shadow:var(--shadow);
}

.table-top{
    padding:12px 16px;
    border-bottom:1px solid #eef2f7;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    flex-wrap:wrap;
}

.table-top h2{
    margin:0;
    font-size:15px;
    font-weight:700;
}

.table-top .sub{
    font-size:11px;
    color:#64748b;
}

.table-wrap{
    overflow:auto;
    cursor:grab;
    user-select:none;
    scroll-behavior:smooth;
}

.table-wrap.active{
    cursor:grabbing;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:1120px;
}

thead{
    background:#334155;
}

th{
    padding:11px 12px;
    text-align:left;
    color:#fff;
    font-size:11px;
    font-weight:700;
    white-space:nowrap;
}

td{
    padding:11px 12px;
    border-bottom:1px solid #eef2f7;
    font-size:12px;
    color:#1e293b;
    white-space:nowrap;
    background:#fff;
    transition:.15s ease;
}

tbody tr:hover td{
    background:#f8fbff;
}

.note{
    max-width:170px;
    overflow:hidden;
    text-overflow:ellipsis;
    color:#64748b;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:68px;
    padding:5px 8px;
    border-radius:999px;
    font-size:10px;
    font-weight:700;
}

.badge.pending{
    background:#fef3c7;
    color:#92400e;
}

.badge.approved{
    background:#dcfce7;
    color:#166534;
}

.badge.rejected{
    background:#fee2e2;
    color:#991b1b;
}

.empty{
    text-align:center;
    padding:24px;
    color:#64748b;
    font-size:13px;
}

.table-wrap::-webkit-scrollbar{
    height:6px;
}

.table-wrap::-webkit-scrollbar-track{
    background:#e2e8f0;
}

.table-wrap::-webkit-scrollbar-thumb{
    background:#94a3b8;
    border-radius:20px;
}

@media(max-width:992px){
    .page{
        margin-left:0;
        padding:80px 10px 10px;
    }

    .stats{
        grid-template-columns:1fr 1fr;
    }
}

@media(max-width:768px){
    .hero{
        padding:14px;
    }

    .hero h1{
        font-size:16px;
    }

    .hero p{
        font-size:11px;
    }

    .stats{
        grid-template-columns:1fr;
    }

    th, td{
        padding:10px;
        font-size:11px;
    }
}
</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="page">

    <div class="hero">
        <h1><i class="fa-solid fa-clock-rotate-left"></i> Order History</h1>
        <p>View all medical representative order requests in one place.</p>
    </div>

    <div class="stats">
        <div class="stat-card total">
            <div class="label">Total Orders</div>
            <div class="value"><?php echo (int)$totalOrders; ?></div>
        </div>
        <div class="stat-card pending">
            <div class="label">Pending</div>
            <div class="value"><?php echo (int)$pendingOrders; ?></div>
        </div>
        <div class="stat-card approved">
            <div class="label">Approved</div>
            <div class="value"><?php echo (int)$approvedOrders; ?></div>
        </div>
        <div class="stat-card rejected">
            <div class="label">Rejected</div>
            <div class="value"><?php echo (int)$rejectedOrders; ?></div>
        </div>
    </div>

    <div class="card">
        <div class="table-top">
            <h2>Order History</h2>
            <div class="sub">Drag table left or right to view more columns.</div>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>MR Name</th>
                        <th>Manager</th>
                        <th>Agency</th>
                        <th>Country</th>
                        <th>Product</th>
                        <th>Qty</th>
                        <th>Notes</th>
                        <th>Status</th>
                        <th>Date</th>
                    </tr>
                </thead>

                <tbody>
                <?php if (!empty($orders)): ?>
                    <?php foreach ($orders as $row): ?>
                        <tr>
                            <td>#<?php echo (int)$row['id']; ?></td>
                            <td><?php echo e($row['mr_name']); ?></td>
                            <td><?php echo e($row['manager_name']); ?></td>
                            <td><?php echo e($row['agency_name']); ?></td>
                            <td><?php echo e($row['country']); ?></td>
                            <td><?php echo e($row['product_name']); ?></td>
                            <td><?php echo (int)$row['qty']; ?></td>
                            <td class="note" title="<?php echo e($row['notes']); ?>">
                                <?php echo e($row['notes']); ?>
                            </td>
                            <td>
                                <span class="badge <?php echo badge($row['status']); ?>">
                                    <?php echo e($row['status']); ?>
                                </span>
                            </td>
                            <td>
                                <?php echo date("d M Y", strtotime($row['created_at'])); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="10" class="empty">No order requests found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
const slider = document.querySelector('.table-wrap');

let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {
    isDown = true;
    slider.classList.add('active');
    startX = e.pageX - slider.offsetLeft;
    scrollLeft = slider.scrollLeft;
});

slider.addEventListener('mouseleave', () => {
    isDown = false;
    slider.classList.remove('active');
});

slider.addEventListener('mouseup', () => {
    isDown = false;
    slider.classList.remove('active');
});

slider.addEventListener('mousemove', (e) => {
    if(!isDown) return;
    e.preventDefault();
    const x = e.pageX - slider.offsetLeft;
    const walk = (x - startX) * 2;
    slider.scrollLeft = scrollLeft - walk;
});
</script>

</body>
</html>