<?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');
include('../../includes/footer.php');

// Basic summary data
$product_count = $conn->query("SELECT COUNT(*) FROM products")->fetch_row()[0];
$total_stock_value = $conn->query("SELECT SUM(quantity * cost_price) FROM inventory WHERE deleted_at IS NULL")->fetch_row()[0] ?? 0;
$expense_total = $conn->query("SELECT SUM(amount) FROM expenses WHERE deleted_at IS NULL")->fetch_row()[0] ?? 0;
$store_count = $conn->query("SELECT COUNT(*) FROM stores")->fetch_row()[0];
$user_count = $conn->query("SELECT COUNT(*) FROM users")->fetch_row()[0];
$sales_today = $conn->query("SELECT SUM(total_amount) FROM sales_transactions WHERE DATE(created_at) = CURDATE()")->fetch_row()[0] ?? 0;
$sales_month = $conn->query("SELECT SUM(total_amount) FROM sales_transactions WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())")->fetch_row()[0] ?? 0;
$sales_total = $conn->query("SELECT SUM(total_amount) FROM sales_transactions")->fetch_row()[0] ?? 0;

// User breakdown by role_id (assuming roles: 1=Admin, 2=Manager, 3=Cashier)
$user_roles = ['Admin' => 1, 'Manager' => 2, 'Cashier' => 3];
$user_counts = [];
foreach ($user_roles as $role_name => $role_id) {
    $count = $conn->query("SELECT COUNT(*) FROM users WHERE role_id = $role_id")->fetch_row()[0];
    $user_counts[$role_name] = $count;
}

// Top 5 stores by total sales
$topStoresResult = $conn->query("
    SELECT s.store_name, SUM(st.total_amount) AS total_sales
    FROM stores s
    LEFT JOIN sales_transactions st ON s.id = st.store_id
    GROUP BY s.id
    ORDER BY total_sales DESC
    LIMIT 5
");
$top_stores = [];
$top_store_sales = [];
while ($row = $topStoresResult->fetch_assoc()) {
    $top_stores[] = $row['store_name'];
    $top_store_sales[] = floatval($row['total_sales'] ?? 0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>System Summary Report with Charts</title>
    <style>
        body {
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
            font-family: 'Segoe UI', sans-serif;
            margin: 0;
            padding: 0;
        }
        .overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.6);
            z-index: -1;
        }
        .content {
            margin: 100px auto 40px;
            max-width: 1200px;
            padding: 40px;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        h2 {
            text-align: center;
            margin-bottom: 30px;
        }
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
            margin-bottom: 50px;
        }
        .card {
            background: rgba(0, 0, 0, 0.4);
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .card h3 {
            font-size: 1.1rem;
            margin-bottom: 10px;
            color: #ffa500;
        }
        .card p {
            font-size: 1.4rem;
            font-weight: bold;
        }
        .export-buttons {
            text-align: right;
            margin-bottom: 20px;
        }
        .export-buttons button {
            background: #ff6f00;
            border: none;
            color: white;
            padding: 10px 14px;
            margin-left: 10px;
            border-radius: 8px;
            cursor: pointer;
        }
        .export-buttons button:hover {
            background: #e65c00;
        }
        /* Responsive charts container with flexbox and horizontal scroll if needed */
        .charts {
            display: flex;
            gap: 40px;
            overflow-x: auto; /* enable horizontal scroll only if needed */
            padding-bottom: 10px;
        }
        .charts > canvas {
            flex: 1 0 350px;  /* minimum width 350px, can grow */
            max-width: 100%;
            height: 300px !important;
            border-radius: 12px;
            background: rgba(0,0,0,0.4);
            padding: 20px;
        }
        @media (max-width: 768px) {
            .summary-grid {
                grid-template-columns: 1fr;
            }
            /* Allow charts to stack vertically on small screens */
            .charts {
                flex-direction: column;
                overflow-x: visible;
            }
            .charts > canvas {
                width: 100% !important;
                min-width: auto !important;
                height: 300px !important;
            }
        }
        .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>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="overlay"></div>
<div class="content">
              <a href="reports.php" class="back-link">&larr; Back to Reports</a>

    <h2>📊 System Summary Report with Charts</h2>

    <div class="export-buttons">
        <button onclick="window.print()">🖨️ Print</button>
        <button onclick="exportCSV()">⬇️ Export CSV</button>
    </div>

    <div class="summary-grid">
        <div class="card">
            <h3>Total Products</h3>
            <p><?= $product_count ?></p>
        </div>
        <div class="card">
            <h3>Total Stock Value</h3>
            <p>MWK <?= number_format($total_stock_value, 2) ?></p>
        </div>
        <div class="card">
            <h3>Total Expenses</h3>
            <p>MWK <?= number_format($expense_total, 2) ?></p>
        </div>
        <div class="card">
            <h3>Total Stores</h3>
            <p><?= $store_count ?></p>
        </div>
        <div class="card">
            <h3>Total Users</h3>
            <p><?= $user_count ?></p>
        </div>
        <div class="card">
            <h3>Sales Today</h3>
            <p>MWK <?= number_format($sales_today, 2) ?></p>
        </div>
        <div class="card">
            <h3>Sales This Month</h3>
            <p>MWK <?= number_format($sales_month, 2) ?></p>
        </div>
        <div class="card">
            <h3>All Time Sales</h3>
            <p>MWK <?= number_format($sales_total, 2) ?></p>
        </div>
    </div>

    <div class="charts">
        <canvas id="salesChart" aria-label="Sales Summary Chart" role="img"></canvas>
        <canvas id="userChart" aria-label="User Roles Chart" role="img"></canvas>
        <canvas id="storeChart" aria-label="Top Stores Chart" role="img"></canvas>
    </div>
</div>

<script>
function exportCSV() {
    const rows = [
        ["Metric", "Value"],
        ["Total Products", "<?= $product_count ?>"],
        ["Total Stock Value", "<?= number_format($total_stock_value, 2) ?>"],
        ["Total Expenses", "<?= number_format($expense_total, 2) ?>"],
        ["Total Stores", "<?= $store_count ?>"],
        ["Total Users", "<?= $user_count ?>"],
        ["Sales Today", "<?= number_format($sales_today, 2) ?>"],
        ["Sales This Month", "<?= number_format($sales_month, 2) ?>"],
        ["All Time Sales", "<?= number_format($sales_total, 2) ?>"]
    ];
    let csvContent = "data:text/csv;charset=utf-8," 
        + rows.map(e => e.join(",")).join("\n");
    const link = document.createElement("a");
    link.setAttribute("href", encodeURI(csvContent));
    link.setAttribute("download", "system_summary_report.csv");
    document.body.appendChild(link);
    link.click();
    link.remove();
}

// Chart.js charts

const salesCtx = document.getElementById('salesChart').getContext('2d');
const userCtx = document.getElementById('userChart').getContext('2d');
const storeCtx = document.getElementById('storeChart').getContext('2d');

const salesChart = new Chart(salesCtx, {
    type: 'bar',
    data: {
        labels: ['Sales Today', 'Sales This Month', 'All Time Sales'],
        datasets: [{
            label: 'MWK',
            data: [
                <?= $sales_today ?>, 
                <?= $sales_month ?>, 
                <?= $sales_total ?>
            ],
            backgroundColor: ['#ff6f00', '#ffa500', '#ffca28'],
            borderRadius: 5
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            title: { display: true, text: 'Sales Summary' }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: { color: 'white' }
            },
            x: { ticks: { color: 'white' } }
        }
    }
});

const userChart = new Chart(userCtx, {
    type: 'doughnut',
    data: {
        labels: <?= json_encode(array_keys($user_counts)) ?>,
        datasets: [{
            label: 'Users',
            data: <?= json_encode(array_values($user_counts)) ?>,
            backgroundColor: ['#ff6f00', '#ffa500', '#ffca28'],
            hoverOffset: 20
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { labels: { color: 'white' } },
            title: { display: true, text: 'User Roles Breakdown' }
        }
    }
});

const storeChart = new Chart(storeCtx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($top_stores) ?>,
        datasets: [{
            label: 'Total Sales (MWK)',
            data: <?= json_encode($top_store_sales) ?>,
            backgroundColor: '#ff6f00',
            borderRadius: 5
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: { display: false },
            title: { display: true, text: 'Top 5 Stores by Sales' }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: { color: 'white' }
            },
            x: { ticks: { color: 'white' } }
        }
    }
});
</script>
</body>
</html>
