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

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

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$assigned_store = $_SESSION['store_id'] ?? null;

// Audit log page access
$device = $_SERVER['HTTP_USER_AGENT'];
$action = 'View';
$module = 'Cashier Performance Report';
$details = json_encode(['page' => 'cashier_performance_report']);
$stmt = $conn->prepare("INSERT INTO audit_log (user_id, module, action, details, role_id, device_info) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("isssis", $user_id, $module, $action, $details, $role_id, $device);
$stmt->execute();
$stmt->close();

// Filters from GET
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$cashier_id = $_GET['cashier_id'] ?? '';
$export = $_GET['export'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 15;
$offset = ($page - 1) * $limit;

// Prepare SQL conditions
$where = ['DATE(s.created_at) >= ?', 'DATE(s.created_at) <= ?'];
$params = [$date_from, $date_to];
$types = 'ss';

// Restrict cashiers based on role/store
if ($role_id == 2 && $assigned_store) { // Manager role
    $where[] = 'u.store_id = ?';
    $params[] = $assigned_store;
    $types .= 'i';
}

// Filter by cashier if selected
if (!empty($cashier_id)) {
    $where[] = 's.sold_by = ?';
    $params[] = $cashier_id;
    $types .= 'i';
}

// Count total rows for pagination
$count_sql = "
    SELECT COUNT(DISTINCT s.sold_by, DATE(s.created_at)) 
    FROM sales_transactions s 
    JOIN users u ON s.sold_by = u.id
    WHERE " . implode(' AND ', $where);

$stmt = $conn->prepare($count_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
$stmt->close();

$totalPages = max(1, ceil($totalRows / $limit));

// Main query: daily cashier performance with pagination
$sql = "
    SELECT s.sold_by, u.first_name, u.last_name, 
           DATE(s.created_at) as sale_date,
           COUNT(*) AS txns,
           SUM(s.total_amount) AS total,
           AVG(s.total_amount) AS avg
    FROM sales_transactions s
    JOIN users u ON s.sold_by = u.id
    WHERE " . implode(' AND ', $where) . "
    GROUP BY s.sold_by, sale_date
    ORDER BY sale_date DESC, u.first_name ASC
    LIMIT ? OFFSET ?
";

$stmt = $conn->prepare($sql);
// Bind params + limit, offset
$bind_params = array_merge($params, [$limit, $offset]);
$bind_types = $types . 'ii';

$stmt->bind_param($bind_types, ...$bind_params);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Fetch cashier list for filter dropdown (only allowed cashiers)
if ($role_id == 1) {
    $cashierListSql = "SELECT id, first_name, last_name FROM users WHERE role_id = 3 ORDER BY first_name, last_name";
    $cashierList = $conn->query($cashierListSql);
} else if ($role_id == 2 && $assigned_store) {
    $cashierListSql = "SELECT id, first_name, last_name FROM users WHERE role_id = 3 AND store_id = ? ORDER BY first_name, last_name";
    $stmt = $conn->prepare($cashierListSql);
    $stmt->bind_param("i", $assigned_store);
    $stmt->execute();
    $cashierList = $stmt->get_result();
    $stmt->close();
} else {
    $cashierList = [];
}

// Aggregate summary (all filtered data without pagination)
$summary_sql = "
    SELECT COUNT(*) as total_txns, 
           SUM(s.total_amount) as total_sales,
           AVG(s.total_amount) as avg_sale
    FROM sales_transactions s
    JOIN users u ON s.sold_by = u.id
    WHERE " . implode(' AND ', $where);

$stmt = $conn->prepare($summary_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$stmt->bind_result($total_txns, $total_sales, $avg_sale);
$stmt->fetch();
$stmt->close();

if ($export === 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=cashier_performance_report.xls");
    echo "<table border=1><tr><th>Cashier</th><th>Date</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr>";
    foreach ($data as $r) {
        $cashier_name = htmlspecialchars($r['first_name'] . ' ' . $r['last_name']);
        echo "<tr><td>$cashier_name</td><td>{$r['sale_date']}</td><td>{$r['txns']}</td><td>{$r['total']}</td><td>{$r['avg']}</td></tr>";
    }
    echo "</table>";
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Cashier Performance Report</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background: fixed url('../../images/profile.jpg') no-repeat center;
            background-size: cover;
            font-family: 'Segoe UI', sans-serif;
            color: white;
        }
        .overlay {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            margin: 80px auto;
            max-width: 1100px;
            padding: 25px;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(15px);
            border-radius: 15px;
        }
        .filters {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .filters select, input, button {
            padding: 8px 10px;
            border: none;
            border-radius: 6px;
            background: rgba(255,255,255,0.2);
            color: white;
            cursor: pointer;
        }
        .export-btn { background: #ff6f00; }
        .summary {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .summary div {
            flex: 1;
            background: rgba(255,255,255,0.08);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        .summary strong {
            color: #ffa500;
            font-size: 1.2em;
        }
        table, th, td {
            border-collapse: collapse;
            width: 100%;
            background: rgba(0,0,0,0.3);
            border: 1px solid rgba(255,255,255,0.1);
            padding: 10px;
            font-size: 0.95rem;
        }
        th {
            background: #ff6f00;
        }
        .pagination {
            margin-top: 15px;
            text-align: center;
        }
        .pagination a {
            margin: 0 5px;
            padding: 6px 12px;
            color: #ff6f00;
            font-weight: bold;
            text-decoration: none;
            border-radius: 6px;
            background: rgba(0,0,0,0.2);
            transition: background 0.3s ease;
        }
        .pagination a.active, .pagination a:hover {
            background: #e65c00;
            color: white;
        }
        .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;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <a href="reports.php" class="back-link">&larr; Back to Reports</a>
    <h2>Cashier Performance Report</h2>
    <form class="filters" method="GET" autocomplete="off">
        <?php if ($role_id == 1): ?>
            <select name="cashier_id">
                <option value="">All Cashiers</option>
                <?php foreach ($cashierList as $c): ?>
                    <?php $id = $c['id']; $name = htmlspecialchars($c['first_name'].' '.$c['last_name']); ?>
                    <option value="<?= $id ?>" <?= ($cashier_id == $id ? 'selected' : '') ?>><?= $name ?></option>
                <?php endforeach; ?>
            </select>
        <?php elseif ($role_id == 2): ?>
            <select name="cashier_id">
                <option value="">All Cashiers</option>
                <?php while ($c = $cashierList->fetch_assoc()): ?>
                    <?php $id = $c['id']; $name = htmlspecialchars($c['first_name'].' '.$c['last_name']); ?>
                    <option value="<?= $id ?>" <?= ($cashier_id == $id ? 'selected' : '') ?>><?= $name ?></option>
                <?php endwhile; ?>
            </select>
        <?php endif; ?>

        <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" required>
        <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" required>
        <button type="submit">Filter</button>
        <button type="button" class="export-btn" onclick="exportExcel()">Export Excel</button>
        <button type="button" class="export-btn" onclick="window.print()">Export PDF</button>
    </form>

    <div class="summary">
        <div><strong><?= number_format($total_sales, 2) ?></strong> Total Sales (MK)</div>
        <div><strong><?= $total_txns ?></strong> Total Transactions</div>
        <div><strong><?= number_format($avg_sale ?? 0, 2) ?></strong> Avg Sale Per Transaction (MK)</div>
    </div>

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

    <table>
        <thead>
            <tr>
                <th>Cashier</th>
                <th>Date</th>
                <th>Transactions</th>
                <th>Total Sales (MK)</th>
                <th>Avg Sale (MK)</th>
            </tr>
        </thead>
        <tbody>
        <?php if (!$data): ?>
            <tr><td colspan="5" style="text-align:center;">No data found.</td></tr>
        <?php else: ?>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></td>
                    <td><?= htmlspecialchars($row['sale_date']) ?></td>
                    <td><?= $row['txns'] ?></td>
                    <td><?= number_format($row['total'], 2) ?></td>
                    <td><?= number_format($row['avg'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>

    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"
                   class="<?= ($p == $page ? 'active' : '') ?>"><?= $p ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<script>
function exportExcel() {
    const url = new URL(location);
    url.searchParams.set('export', 'excel');
    location.href = url.toString();
}

const ctx = document.getElementById('chart').getContext('2d');

// Prepare chart data grouped by cashier
const rawData = <?= json_encode($data) ?>;

const cashierLabels = [...new Set(rawData.map(d => d.first_name + ' ' + d.last_name))];

const salesByCashier = {};
const txnsByCashier = {};
cashierLabels.forEach(name => {
    salesByCashier[name] = 0;
    txnsByCashier[name] = 0;
});
rawData.forEach(d => {
    const name = d.first_name + ' ' + d.last_name;
    salesByCashier[name] += parseFloat(d.total);
    txnsByCashier[name] += parseInt(d.txns);
});

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: cashierLabels,
        datasets: [
            {
                label: 'Total Sales (MK)',
                data: cashierLabels.map(name => salesByCashier[name].toFixed(2)),
                backgroundColor: 'rgba(255,111,0,0.6)'
            },
            {
                label: 'Transactions',
                data: cashierLabels.map(name => txnsByCashier[name]),
                backgroundColor: 'rgba(0,150,136,0.6)'
            }
        ]
    },
    options: {
        responsive: true,
        scales: {
            y: { beginAtZero: true }
        }
    }
});
</script>
</body>
</html>
