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

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

// Audit log
$device = $_SERVER['HTTP_USER_AGENT'];
$action = 'View';
$module = 'Daily Sales Report';
$details = json_encode(['page'=>'daily_sales_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
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to   = $_GET['date_to'] ?? date('Y-m-d');
$store_id  = $role_id == 1 ? ($_GET['store_id'] ?? '') : $assigned_store;
$export    = $_GET['export'] ?? '';

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

if (!empty($store_id)) {
    $where[] = 's.store_id = ?';
    $params[] = $store_id;
    $types .= 'i';
}

// Get summary data
$summary_sql = "
    SELECT 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
    WHERE " . implode(' AND ', $where) . "
    GROUP BY sale_date
    ORDER BY sale_date
";
$stmt = $conn->prepare($summary_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=daily_sales_report.xls");
    echo "<table border=1><tr><th>Date</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr>";
    foreach ($data as $r) {
        echo "<tr><td>{$r['sale_date']}</td><td>{$r['txns']}</td><td>{$r['total']}</td><td>{$r['avg']}</td></tr>";
    }
    echo "</table>";
    exit();
}

// Store list
$storeList = $conn->query("SELECT id, store_name FROM stores");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Daily Sales 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: 1000px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(15px);
            border-radius: 15px;
        }
        .filters {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .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;
        }
        th {
            background: #ff6f00;
        }
        .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>Daily Sales Report</h2>

    <form class="filters" method="GET">
        <?php if ($role_id == 1): ?>
            <select name="store_id">
                <option value="">All Stores</option>
                <?php while ($s = $storeList->fetch_assoc()): ?>
                    <option value="<?= $s['id'] ?>" <?= ($store_id == $s['id'] ? 'selected' : '') ?>>
                        <?= htmlspecialchars($s['store_name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        <?php endif; ?>
        <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" 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><?= count($data) ?></strong> Days</div>
        <div><strong>MK <?= number_format(array_sum(array_column($data,'total')),2) ?></strong> Total Sales</div>
        <div><strong><?= number_format(end($data)['avg'] ?? 0,2) ?></strong> Last Day Avg</div>
    </div>

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

    <table>
        <thead>
            <tr><th>Date</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr>
        </thead>
        <tbody>
        <?php foreach ($data as $r): ?>
            <tr>
                <td><?= htmlspecialchars($r['sale_date']) ?></td>
                <td><?= $r['txns'] ?></td>
                <td>MK <?= number_format($r['total'],2) ?></td>
                <td>MK <?= number_format($r['avg'],2) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

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

const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: <?= json_encode(array_column($data, 'sale_date')) ?>,
        datasets: [
            {
                label: 'Total Sales',
                data: <?= json_encode(array_column($data, 'total')) ?>,
                backgroundColor: 'rgba(255,111,0,0.6)'
            },
            {
                label: 'Transactions',
                data: <?= json_encode(array_column($data, 'txns')) ?>,
                backgroundColor: 'rgba(0,150,136,0.6)'
            }
        ]
    },
    options: {
        responsive: true,
        scales: {
            y: { beginAtZero: true }
        }
    }
});
</script>
</body>
</html>
