<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');

$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$export = $_GET['export'] ?? '';

$where = ['DATE(st.created_at) >= ?', 'DATE(st.created_at) <= ?'];
$params = [$date_from, $date_to];
$types = 'ss';

$sql = "
    SELECT u.id, u.first_name, u.last_name, COUNT(*) AS txns, 
           SUM(st.total_amount) AS total, AVG(st.total_amount) AS avg
    FROM sales_transactions st
    JOIN users u ON st.sold_by = u.id
    WHERE " . implode(' AND ', $where) . "
    GROUP BY u.id
    ORDER BY total DESC
    LIMIT 5
";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if ($export === 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=cashier_performance.xls");
    echo "<table border=1><tr><th>Cashier</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr>";
    foreach ($data as $r) {
        $n = htmlspecialchars($r['first_name'] . ' ' . $r['last_name']);
        echo "<tr><td>$n</td><td>{$r['txns']}</td><td>{$r['total']}</td><td>{$r['avg']}</td></tr>";
    }
    echo "</table>";
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cashier Performance - Digital POS</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
        }

        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: -1;
        }

        .content {
            margin: 100px auto 40px auto;
            max-width: 1200px;
            padding: 40px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 20px;
            backdrop-filter: blur(15px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
            color: #ffa500;
        }

        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            padding: 10px 20px;
            background:rgba(255, 111, 0, 0);
            color: white;
            font-weight: 600;
            border-radius: 8px;
            text-decoration: none;
            transition: background-color 0.3s ease;
        }

        .back-link:hover {
            background: #e65c00;
        }

        .filters {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: center;
            margin-bottom: 20px;
        }

        .filters input,
        .filters button {
            padding: 10px 15px;
            border-radius: 8px;
            border: none;
            outline: none;
            font-size: 14px;
        }

        .filters input[type="date"] {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }

        .filters button {
            background: #ff6f00;
            color: white;
            cursor: pointer;
        }

        .filters button:hover {
            background: #ffa500;
        }

        canvas {
            background: white;
            border-radius: 10px;
            padding: 10px;
            margin-bottom: 30px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255, 255, 255, 0.05);
        }

        th, td {
            padding: 12px;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        th {
            background: rgba(0, 0, 0, 0.3);
            color: #ffa500;
        }

        tr:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        @media(max-width: 768px) {
            .filters {
                flex-direction: column;
                align-items: center;
            }

            canvas {
                width: 100% !important;
            }
        }
    </style>
</head>
<body>
<div class="overlay"></div>

<div class="content">
    <a href="reports.php" class="back-link">&larr; Back to Reports</a>

    <h2>👨‍💼 Top 5 Cashiers by Sales</h2>

    <form class="filters" method="GET">
        <input type="date" name="date_from" value="<?= $date_from ?>">
        <input type="date" name="date_to" value="<?= $date_to ?>">
        <button type="submit">Filter</button>
        <button type="button" onclick="window.location.href='?date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&export=excel'">Export Excel</button>
        <button type="button" onclick="window.print()">Export PDF</button>
    </form>

    <canvas id="cashierChart" height="100"></canvas>

    <table>
        <thead>
            <tr>
                <th>Cashier</th>
                <th>Transactions</th>
                <th>Total Sales (MWK)</th>
                <th>Average Sale (MWK)</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $r): 
                $name = htmlspecialchars($r['first_name'] . ' ' . $r['last_name']); ?>
                <tr>
                    <td><?= $name ?></td>
                    <td><?= $r['txns'] ?></td>
                    <td><?= number_format($r['total'], 2) ?></td>
                    <td><?= number_format($r['avg'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<script>
    const ctx2 = document.getElementById('cashierChart').getContext('2d');
    new Chart(ctx2, {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_map(fn($r) => $r['first_name'] . ' ' . $r['last_name'], $data)) ?>,
            datasets: [{
                label: 'Sales (MWK)',
                data: <?= json_encode(array_column($data, 'total')) ?>,
                backgroundColor: 'rgba(255,111,0,0.6)',
                borderColor: 'rgba(255,111,0,1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        color: '#fff'
                    }
                },
                x: {
                    ticks: {
                        color: '#fff'
                    }
                }
            },
            plugins: {
                legend: {
                    labels: {
                        color: '#fff'
                    }
                }
            }
        }
    });
</script>
</body>
</html>
