<?php
session_start();
include('../../includes/config.php');
include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../../includes/sidebar.php';
include __DIR__ . '/../../includes/footer.php';

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

// Inventory Breakdown
$inventoryData = ['in_stock' => 0, 'low_stock' => 0, 'out_of_stock' => 0];
$inventory_sql = "SELECT quantity FROM inventory WHERE store_id = ?";
$inv_stmt = $conn->prepare($inventory_sql);
$inv_stmt->bind_param("i", $_SESSION['store_id']);
$inv_stmt->execute();
$inv_result = $inv_stmt->get_result();
while ($row = $inv_result->fetch_assoc()) {
    $qty = (int)$row['quantity'];
    if ($qty === 0) {
        $inventoryData['out_of_stock']++;
    } elseif ($qty <= 10) {
        $inventoryData['low_stock']++;
    } else {
        $inventoryData['in_stock']++;
    }
}
$inv_stmt->close();

// Sales Trend (last 7 days)
$sales_labels = [];
$sales_values = [];
$sales_sql = "
    SELECT DATE(created_at) as date, COALESCE(SUM(total_amount),0) as total 
    FROM sales_transactions 
    WHERE store_id = ? AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(created_at) ORDER BY date ASC";
$sales_stmt = $conn->prepare($sales_sql);
$sales_stmt->bind_param("i", $_SESSION['store_id']);
$sales_stmt->execute();
$sales_result = $sales_stmt->get_result();
while ($row = $sales_result->fetch_assoc()) {
    $sales_labels[] = $row['date'];
    $sales_values[] = (float)$row['total'];
}
$sales_stmt->close();

// Expenses Trend (last 7 days) for current store
$expenses_labels = [];
$expenses_values = [];
$expenses_sql = "
    SELECT DATE(expense_date) as date, COALESCE(SUM(amount),0) as total
    FROM expenses
    WHERE store_id = ? AND expense_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(expense_date) ORDER BY date ASC";
$expenses_stmt = $conn->prepare($expenses_sql);
$expenses_stmt->bind_param("i", $_SESSION['store_id']);
$expenses_stmt->execute();
$expenses_result = $expenses_stmt->get_result();
while ($row = $expenses_result->fetch_assoc()) {
    $expenses_labels[] = $row['date'];
    $expenses_values[] = (float)$row['total'];
}
$expenses_stmt->close();

// Store Performance - Sales for all stores
$performance_sql = "
    SELECT s.store_name, COALESCE(SUM(sa.total_amount), 0) AS total_sales, COALESCE(SUM(ex.amount), 0) AS total_expenses
    FROM stores s
    LEFT JOIN sales_transactions sa ON s.id = sa.store_id
    LEFT JOIN expenses ex ON s.id = ex.store_id
    GROUP BY s.id, s.store_name
";
$performance_stmt = $conn->prepare($performance_sql);
$performance_stmt->execute();
$performance_result = $performance_stmt->get_result();

$perf_labels = [];
$perf_sales = [];
$perf_expenses = [];
while ($row = $performance_result->fetch_assoc()) {
    $perf_labels[] = $row['store_name'];
    $perf_sales[] = (float)$row['total_sales'];
    $perf_expenses[] = (float)$row['total_expenses'];
}
$performance_stmt->close();

$conn->close();

function e($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Manager Dashboard - Digital POS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.css" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* Unified styles from Admin Dashboard */
        body, html {
    margin: 0;
    padding: 0;
    height: 100%;
    font-family: 'Segoe UI', sans-serif;
    position: relative;
}

body::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.4); /* Dark semi-transparent overlay */
    z-index: -1;
}

body {
    background: url('../../images/bg.jpg') no-repeat center center fixed;
    background-size: cover;
}


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

        .glassy-header {
            position: fixed;
            top: 0; left: 0;
            width: 100%;
            height: 70px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(12px);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 25px;
            z-index: 1000;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }



        .content {
            margin-left: 200px;
            margin-top: 70px;
            padding: 30px;
            color: white;
        }

        h3 {
            margin-bottom: 20px;
            font-size: 24px;
            color: white;
        }

        .charts {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .chart-card {
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 20px;
            flex: 1;
            min-width: 300px;
            color: black;
            box-shadow: 0 8px 16px rgba(0,0,0,0.2);
            transition: transform 0.3s;
        }

        .chart-card:hover {
            transform: translateY(-5px);
        }

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

        @media (max-width: 768px) {
            .sidebar {
                position: relative;
                width: 100%;
                height: auto;
                top: 0;
            }

            .content {
                margin-left: 0;
                margin-top: 0;
            }

            .charts {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>

<div class="overlay"></div>

<!--<div class="sidebar">
    <ul>
        <li><a href="/digital_pos/pages/shared/profile.php">My Profile</a></li>
        <li><a href="#">Dashboard</a></li>
        <li><a href="#">Inventory</a></li>
        <li><a href="#">Staff</a></li>
        <li><a href="#">Sales Reports</a></li>
        <li><a href="#">Settings</a></li>
        <li><a href="../../logout.php">Logout</a></li>
    </ul>
</div>-->

<div class="content">
    <h3>Store Management Overview</h3>
    <div class="charts">
        <div class="chart-card" data-aos="fade-up" data-aos-delay="100"><canvas id="inventoryChart"></canvas></div>
        <div class="chart-card" data-aos="fade-up" data-aos-delay="200"><canvas id="salesTrendChart"></canvas></div>
        <div class="chart-card" data-aos="fade-up" data-aos-delay="300"><canvas id="expensesTrendChart"></canvas></div>
        <div class="chart-card" data-aos="fade-up" data-aos-delay="400" style="flex-basis: 100%;"><canvas id="storePerformanceChart"></canvas></div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.js"></script>
<script>AOS.init();</script>
<script>
    new Chart(document.getElementById('inventoryChart'), {
        type: 'pie',
        data: {
            labels: ['In Stock', 'Low Stock', 'Out of Stock'],
            datasets: [{
                data: [<?= e($inventoryData['in_stock']) ?>, <?= e($inventoryData['low_stock']) ?>, <?= e($inventoryData['out_of_stock']) ?>],
                backgroundColor: ['#28a745', '#ffc107', '#dc3545']
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });

    new Chart(document.getElementById('salesTrendChart'), {
        type: 'line',
        data: {
            labels: <?= json_encode($sales_labels) ?>,
            datasets: [{
                label: 'Sales (MWK)',
                data: <?= json_encode($sales_values) ?>,
                borderColor: 'orange',
                backgroundColor: 'rgba(255,165,0,0.2)',
                fill: true,
                tension: 0.3,
                pointRadius: 5,
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                x: { title: { display: true, text: 'Date' } },
                y: { title: { display: true, text: 'MWK' }, beginAtZero: true }
            }
        }
    });

    new Chart(document.getElementById('expensesTrendChart'), {
        type: 'line',
        data: {
            labels: <?= json_encode($expenses_labels) ?>,
            datasets: [{
                label: 'Expenses (MWK)',
                data: <?= json_encode($expenses_values) ?>,
                borderColor: 'red',
                backgroundColor: 'rgba(255,99,132,0.2)',
                fill: true,
                tension: 0.3,
                pointRadius: 5,
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                x: { title: { display: true, text: 'Date' } },
                y: { title: { display: true, text: 'MWK' }, beginAtZero: true }
            }
        }
    });

    new Chart(document.getElementById('storePerformanceChart'), {
        type: 'bar',
        data: {
            labels: <?= json_encode($perf_labels) ?>,
            datasets: [
                {
                    label: 'Sales (MWK)',
                    data: <?= json_encode($perf_sales) ?>,
                    backgroundColor: '#007bff',
                    borderRadius: 5
                },
                {
                    label: 'Expenses (MWK)',
                    data: <?= json_encode($perf_expenses) ?>,
                    backgroundColor: '#dc3545',
                    borderRadius: 5
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                x: { title: { display: true, text: 'Store' }, stacked: true },
                y: { title: { display: true, text: 'MWK' }, beginAtZero: true }
            }
        }
    });
</script>

</body>
</html>
