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

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

// Validate & sanitize dates
function validateDate($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

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

if (!validateDate($date_from)) $date_from = date('Y-m-01');
if (!validateDate($date_to)) $date_to = date('Y-m-d');

$export = $_GET['export'] ?? '';

$manager_id = $_SESSION['user_id'];

// Get store_id from users table (assuming users.store_id exists)
$store_stmt = $conn->prepare("SELECT store_id FROM users WHERE id = ?");
$store_stmt->bind_param("i", $manager_id);
$store_stmt->execute();
$store_result = $store_stmt->get_result();
$store = $store_result->fetch_assoc();
$store_id = $store['store_id'] ?? 0;
$store_stmt->close();

if ($store_id === 0) {
    die("You are not assigned to any store or unauthorized.");
}

// Log filters/export activity
$action = $export ? "Exported sales report" : "Viewed sales report";
$details = $date_from . " to " . $date_to; // Assign concatenated string to variable
$log = $conn->prepare("INSERT INTO audit_log (user_id, action, module, details, role_id, created_at, device_info) VALUES (?, ?, 'Sales Report', ?, ?, NOW(), ?)");
$log->bind_param("issis", $_SESSION['user_id'], $action, $details, $_SESSION['role_id'], $_SERVER['HTTP_USER_AGENT']);
$log->execute();
$log->close();

// Fetch sales data for the store and date range
$sql = "SELECT st.id, st.created_at, u.first_name, u.last_name,
               SUM(si.quantity * si.unit_price) AS total,
               st.vat_total
        FROM sales_transactions st
        JOIN users u ON st.sold_by = u.id
        JOIN sales_items si ON st.id = si.transaction_id
        WHERE DATE(st.created_at) BETWEEN ? AND ? AND st.store_id = ?
        GROUP BY st.id
        ORDER BY st.created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ssi", $date_from, $date_to, $store_id);
$stmt->execute();
$sales = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Calculate summary totals safely
$total_sales = array_sum(array_column($sales, 'total'));
$total_vat = array_sum(array_column($sales, 'vat_total'));
$total_txns = count($sales);

// Handle Excel export
if ($export === 'excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=manager_sales_report_" . date('Ymd') . ".xls");
    echo "<table border='1'>
            <tr><th>Date</th><th>Transaction ID</th><th>Cashier</th><th>Total</th><th>VAT</th></tr>";
    foreach ($sales as $row) {
        echo "<tr>
                <td>" . htmlspecialchars($row['created_at']) . "</td>
                <td>" . htmlspecialchars($row['id']) . "</td>
                <td>" . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . "</td>
                <td>" . number_format($row['total'], 2) . "</td>
                <td>" . number_format($row['vat_total'], 2) . "</td>
              </tr>";
    }
    echo "</table>";
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Manager Sales Report</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            margin: 0;
        }
        .overlay {
            position: fixed; inset: 0;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            max-width: 1200px;
            margin: 80px auto;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(15px);
            padding: 30px;
            border-radius: 20px;
        }
        h2 {
            text-align: center;
            color: #ffa500;
        }
        .filters {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        .filters input, .filters button {
            padding: 10px 15px;
            border-radius: 8px;
            border: none;
            font-size: 1rem;
        }
        .filters input {
            background: rgba(255,255,255,0.2);
            color: white;
            min-width: 150px;
        }
        .filters button {
            background: #ff6f00;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .filters button:hover {
            background: #e65c00;
        }
        .summary {
            display: flex;
            gap: 20px;
            justify-content: space-around;
            margin-bottom: 30px;
            text-align: center;
        }
        .summary div {
            flex: 1;
            background: rgba(255,255,255,0.1);
            padding: 20px;
            border-radius: 10px;
            min-width: 150px;
        }
        .summary h3 {
            margin: 0 0 10px;
            color: #ffa500;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255,255,255,0.05);
            color: white;
        }
        th, td {
            padding: 12px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: center;
        }
        th {
            background: rgba(0,0,0,0.3);
            color: #ffa500;
        }
        canvas {
            background: white;
            padding: 10px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            background: rgba(255,111,0,0.1);
            border-radius: 8px;
            transition: background-color 0.3s ease;
        }
        .back-link:hover {
            background: rgba(255,111,0,0.3);
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <a href="reports.php" class="back-link">&larr; Back to Reports</a>
    <h2>📊 Manager Sales Report</h2>

    <form method="GET" class="filters" aria-label="Filter sales report">
        <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" onclick="window.location.href='?date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>&export=excel'">Export Excel</button>
        <button type="button" onclick="window.print()">Print / Export PDF</button>
    </form>

    <div class="summary" role="region" aria-label="Summary totals">
        <div>
            <h3>Total Sales</h3>
            <strong><?= number_format($total_sales, 2) ?> MWK</strong>
        </div>
        <div>
            <h3>Total VAT</h3>
            <strong><?= number_format($total_vat, 2) ?> MWK</strong>
        </div>
        <div>
            <h3>Transactions</h3>
            <strong><?= $total_txns ?></strong>
        </div>
    </div>

    <?php if ($total_txns > 0): ?>
    <canvas id="salesChart" height="100" aria-label="Sales and VAT bar chart"></canvas>
    <?php else: ?>
    <p style="text-align:center; color:#ffa500; font-weight:bold;">No sales data found for the selected date range.</p>
    <?php endif; ?>

    <table aria-describedby="sales-table-description">
        <caption id="sales-table-description" style="caption-side: top; text-align: center; margin-bottom: 10px; font-weight: bold;">
            Sales transactions from <?= htmlspecialchars($date_from) ?> to <?= htmlspecialchars($date_to) ?>
        </caption>
        <thead>
            <tr>
                <th>Date</th>
                <th>Transaction ID</th>
                <th>Cashier</th>
                <th>Total</th>
                <th>VAT</th>
            </tr>
        </thead>
        <tbody>
        <?php if ($total_txns > 0): ?>
            <?php foreach ($sales as $s): ?>
                <tr>
                    <td><?= date('Y-m-d', strtotime($s['created_at'])) ?></td>
                    <td><?= htmlspecialchars($s['id']) ?></td>
                    <td><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></td>
                    <td><?= number_format($s['total'], 2) ?></td>
                    <td><?= number_format($s['vat_total'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr><td colspan="5" style="color:#ffa500;">No sales found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<?php if ($total_txns > 0): ?>
<script>
const ctx = document.getElementById('salesChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_map(fn($s) => date('Y-m-d', strtotime($s['created_at'])), $sales)) ?>,
        datasets: [{
            label: 'Sales Total (MWK)',
            data: <?= json_encode(array_column($sales, 'total')) ?>,
            backgroundColor: 'rgba(255,111,0,0.6)'
        }, {
            label: 'VAT (MWK)',
            data: <?= json_encode(array_column($sales, 'vat_total')) ?>,
            backgroundColor: 'rgba(0,150,136,0.6)'
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: '#fff' } }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: { color: '#fff' }
            },
            x: {
                ticks: { color: '#fff' }
            }
        }
    }
});
</script>
<?php endif; ?>

</body>
</html>
