<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Sales.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: /unauthorized.php');
    exit;
}


$branch = new Branch($conn);
$sales = new Sales($conn);


$branchesResult = $branch->getAllBranches();
$branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);


$currentDate = new DateTime();
$currentWeekStart = new DateTime('Monday this week');
$currentWeekEnd = new DateTime('Sunday this week');
$currentMonthStart = new DateTime('first day of this month');
$currentMonthEnd = new DateTime('last day of this month');


$previousWeekStart = (clone $currentWeekStart)->modify('-1 week');
$previousWeekEnd = (clone $currentWeekEnd)->modify('-1 week');
$previousMonthStart = (clone $currentMonthStart)->modify('-1 month');
$previousMonthEnd = (clone $currentMonthEnd)->modify('-1 month');


function getWeeklySales($conn, $branches, $startDate, $endDate) {
    $weeklySales = [];
    $totalSales = 0;

    foreach ($branches as $branch) {
        $sql = "SELECT COALESCE(SUM(si.total_price), 0) as total_sales
               FROM sold_items si
               INNER JOIN weekly_reports wr ON
                   si.branch_id = wr.branch_id AND
                   DATE(si.sold_at) BETWEEN wr.week_start_date AND DATE_ADD(wr.week_start_date, INTERVAL 6 DAY)
               WHERE si.branch_id = :branch_id
               AND COALESCE(si.is_ims_income, 1) = 1
               AND DATE(si.sold_at) BETWEEN :start_date AND :end_date
               AND wr.verification_status = 'verified'";


        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':branch_id', $branch['branch_id'], PDO::PARAM_INT);
        $stmt->bindParam(':start_date', $startDate);
        $stmt->bindParam(':end_date', $endDate);
        $stmt->execute();

        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $branchSales = $result['total_sales'] ?: 0;

        $weeklySales[$branch['branch_id']] = [
            'branch_name' => $branch['branch_name'],
            'total_sales' => $branchSales
        ];

        $totalSales += $branchSales;
    }

    return [
        'branch_sales' => $weeklySales,
        'total_sales' => $totalSales
    ];
}


function getMonthlySales($conn, $branches, $startDate, $endDate) {
    $monthlySales = [];
    $totalSales = 0;

    foreach ($branches as $branch) {
        $sql = "SELECT COALESCE(SUM(si.total_price), 0) as total_sales
               FROM sold_items si
               INNER JOIN weekly_reports wr ON
                   si.branch_id = wr.branch_id AND
                   DATE(si.sold_at) BETWEEN wr.week_start_date AND DATE_ADD(wr.week_start_date, INTERVAL 6 DAY)
               WHERE si.branch_id = :branch_id
               AND COALESCE(si.is_ims_income, 1) = 1
               AND DATE(si.sold_at) BETWEEN :start_date AND :end_date
               AND wr.verification_status = 'verified'";


        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':branch_id', $branch['branch_id'], PDO::PARAM_INT);
        $stmt->bindParam(':start_date', $startDate);
        $stmt->bindParam(':end_date', $endDate);
        $stmt->execute();

        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $branchSales = $result['total_sales'] ?: 0;

        $monthlySales[$branch['branch_id']] = [
            'branch_name' => $branch['branch_name'],
            'total_sales' => $branchSales
        ];

        $totalSales += $branchSales;
    }

    return [
        'branch_sales' => $monthlySales,
        'total_sales' => $totalSales
    ];
}


$currentWeekSales = getWeeklySales(
    $conn,
    $branches,
    $currentWeekStart->format('Y-m-d'),
    $currentWeekEnd->format('Y-m-d')
);


$previousWeekSales = getWeeklySales(
    $conn,
    $branches,
    $previousWeekStart->format('Y-m-d'),
    $previousWeekEnd->format('Y-m-d')
);


$currentMonthSales = getMonthlySales(
    $conn,
    $branches,
    $currentMonthStart->format('Y-m-d'),
    $currentMonthEnd->format('Y-m-d')
);


$previousMonthSales = getMonthlySales(
    $conn,
    $branches,
    $previousMonthStart->format('Y-m-d'),
    $previousMonthEnd->format('Y-m-d')
);


$weeklyChange = 0;
if ($previousWeekSales['total_sales'] > 0) {
    $weeklyChange = (($currentWeekSales['total_sales'] - $previousWeekSales['total_sales']) / $previousWeekSales['total_sales']) * 100;
}


$monthlyChange = 0;
if ($previousMonthSales['total_sales'] > 0) {
    $monthlyChange = (($currentMonthSales['total_sales'] - $previousMonthSales['total_sales']) / $previousMonthSales['total_sales']) * 100;
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
        .summary-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
        }

        .summary-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
        }

        .period-header {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 10px 10px 0 0;
            border-bottom: 1px solid #dee2e6;
        }

        .change-indicator {
            font-weight: bold;
            padding: 3px 8px;
            border-radius: 4px;
        }

        .change-positive {
            background-color: #d4edda;
            color: #155724;
        }

        .change-negative {
            background-color: #f8d7da;
            color: #721c24;
        }

        .change-neutral {
            background-color: #e2e3e5;
            color: #383d41;
        }

        .branch-sales-table {
            margin-top: 15px;
        }


        .branch-sales-table th,
        .branch-sales-table td {
            vertical-align: middle;
        }

        .branch-sales-table table {
            table-layout: fixed;
            width: 100%;
        }


        .branch-sales-table td {
            word-wrap: break-word;
            min-width: 120px;
        }

        .chart-container {
            height: 300px;
            margin-bottom: 30px;
        }
    </style>
    <div class="container-fluid mt-4" style="padding-left: 30px; padding-right: 30px;">
        <div class="row mb-4">
            <div class="col-12 d-flex flex-column align-items-center justify-content-center">
                <h1 class="mt-5 mb-4">Sales Summary Dashboard</h1>
                <div class="mb-4">
                    <a href="../dashboard/admin.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>


        <div class="row mb-4">

            <div class="col-md-6 px-4">
                <div class="card summary-card">
                    <div class="card-header period-header">
                        <h4>
                            <i class="fas fa-calendar-week"></i>
                            Weekly Sales Overview
                            <span class="float-end">
                                <?php if ($weeklyChange > 0): ?>
                                    <span class="change-indicator change-positive">
                                        <i class="fas fa-arrow-up"></i> <?php echo number_format(abs($weeklyChange), 2); ?>%
                                    </span>
                                <?php elseif ($weeklyChange < 0): ?>
                                    <span class="change-indicator change-negative">
                                        <i class="fas fa-arrow-down"></i> <?php echo number_format(abs($weeklyChange), 2); ?>%
                                    </span>
                                <?php else: ?>
                                    <span class="change-indicator change-neutral">
                                        <i class="fas fa-equals"></i> 0%
                                    </span>
                                <?php endif; ?>
                            </span>
                        </h4>
                        <div>
                            <small class="text-muted">
                                Current Week: <?php echo $currentWeekStart->format('M d'); ?> - <?php echo $currentWeekEnd->format('M d, Y'); ?>
                            </small>
                        </div>
                    </div>
                    <div class="card-body">
                        <h3 class="text-center mb-4">MWK <?php echo number_format($currentWeekSales['total_sales'], 2); ?></h3>

                        <div class="chart-container">
                            <canvas id="weeklyChart"></canvas>
                        </div>

                        <h5>Branch Breakdown</h5>
                        <div class="table-responsive branch-sales-table">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th style="width: 35%">Branch</th>
                                        <th style="width: 35%" class="text-center">Sales Amount</th>
                                        <th style="width: 30%" class="text-center">% of Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($currentWeekSales['branch_sales'] as $branchId => $branchData): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($branchData['branch_name']); ?></td>
                                            <td class="text-center">MWK <?php echo number_format($branchData['total_sales'], 2); ?></td>
                                            <td class="text-center">
                                                <?php
                                                $percentage = $currentWeekSales['total_sales'] > 0
                                                    ? ($branchData['total_sales'] / $currentWeekSales['total_sales']) * 100
                                                    : 0;
                                                echo number_format($percentage, 2) . '%';
                                                ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-dark">
                                        <th>Total</th>
                                        <th class="text-center">MWK <?php echo number_format($currentWeekSales['total_sales'], 2); ?></th>
                                        <th class="text-center">100%</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>


            <div class="col-md-6 px-4">
                <div class="card summary-card">
                    <div class="card-header period-header">
                        <h4>
                            <i class="fas fa-calendar-alt"></i>
                            Monthly Sales Overview
                            <span class="float-end">
                                <?php if ($monthlyChange > 0): ?>
                                    <span class="change-indicator change-positive">
                                        <i class="fas fa-arrow-up"></i> <?php echo number_format(abs($monthlyChange), 2); ?>%
                                    </span>
                                <?php elseif ($monthlyChange < 0): ?>
                                    <span class="change-indicator change-negative">
                                        <i class="fas fa-arrow-down"></i> <?php echo number_format(abs($monthlyChange), 2); ?>%
                                    </span>
                                <?php else: ?>
                                    <span class="change-indicator change-neutral">
                                        <i class="fas fa-equals"></i> 0%
                                    </span>
                                <?php endif; ?>
                            </span>
                        </h4>
                        <div>
                            <small class="text-muted">
                                Current Month: <?php echo $currentMonthStart->format('M Y'); ?>
                            </small>
                        </div>
                    </div>
                    <div class="card-body">
                        <h3 class="text-center mb-4">MWK <?php echo number_format($currentMonthSales['total_sales'], 2); ?></h3>

                        <div class="chart-container">
                            <canvas id="monthlyChart"></canvas>
                        </div>

                        <h5>Branch Breakdown</h5>
                        <div class="table-responsive branch-sales-table">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th style="width: 35%">Branch</th>
                                        <th style="width: 35%" class="text-center">Sales Amount</th>
                                        <th style="width: 30%" class="text-center">% of Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($currentMonthSales['branch_sales'] as $branchId => $branchData): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($branchData['branch_name']); ?></td>
                                            <td class="text-center">MWK <?php echo number_format($branchData['total_sales'], 2); ?></td>
                                            <td class="text-center">
                                                <?php
                                                $percentage = $currentMonthSales['total_sales'] > 0
                                                    ? ($branchData['total_sales'] / $currentMonthSales['total_sales']) * 100
                                                    : 0;
                                                echo number_format($percentage, 2) . '%';
                                                ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-dark">
                                        <th>Total</th>
                                        <th class="text-center">MWK <?php echo number_format($currentMonthSales['total_sales'], 2); ?></th>
                                        <th class="text-center">100%</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="row mb-4">

            <div class="col-md-6 px-4">
                <div class="card summary-card">
                    <div class="card-header period-header">
                        <h4>
                            <i class="fas fa-calendar-week"></i>
                            Weekly Historical Comparison
                        </h4>
                        <div>
                            <small class="text-muted">
                                Comparing <?php echo $currentWeekStart->format('M d'); ?> - <?php echo $currentWeekEnd->format('M d, Y'); ?>
                            </small>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th style="width: 60%">Period</th>
                                        <th style="width: 40%" class="text-center">Total Sales</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            Current Week<br>
                                            <small class="text-muted">
                                                <?php echo $currentWeekStart->format('M d'); ?> - <?php echo $currentWeekEnd->format('M d, Y'); ?>
                                            </small>
                                        </td>
                                        <td class="text-center">MWK <?php echo number_format($currentWeekSales['total_sales'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>
                                            Previous Week<br>
                                            <small class="text-muted">
                                                <?php echo $previousWeekStart->format('M d'); ?> - <?php echo $previousWeekEnd->format('M d, Y'); ?>
                                            </small>
                                        </td>
                                        <td class="text-center">MWK <?php echo number_format($previousWeekSales['total_sales'], 2); ?></td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr class="table-info">
                                        <th>Week-over-Week Change</th>
                                        <th class="text-center">
                                            <?php if ($weeklyChange > 0): ?>
                                                <span class="change-indicator change-positive">
                                                    <i class="fas fa-arrow-up"></i> <?php echo number_format(abs($weeklyChange), 2); ?>%
                                                </span>
                                            <?php elseif ($weeklyChange < 0): ?>
                                                <span class="change-indicator change-negative">
                                                    <i class="fas fa-arrow-down"></i> <?php echo number_format(abs($weeklyChange), 2); ?>%
                                                </span>
                                            <?php else: ?>
                                                <span class="change-indicator change-neutral">
                                                    <i class="fas fa-equals"></i> 0%
                                                </span>
                                            <?php endif; ?>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>


            <div class="col-md-6 px-4">
                <div class="card summary-card">
                    <div class="card-header period-header">
                        <h4>
                            <i class="fas fa-calendar-alt"></i>
                            Monthly Historical Comparison
                        </h4>
                        <div>
                            <small class="text-muted">
                                Comparing <?php echo $currentMonthStart->format('M Y'); ?>
                            </small>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th style="width: 60%">Period</th>
                                        <th style="width: 40%" class="text-center">Total Sales</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            Current Month<br>
                                            <small class="text-muted"><?php echo $currentMonthStart->format('M Y'); ?></small>
                                        </td>
                                        <td class="text-center">MWK <?php echo number_format($currentMonthSales['total_sales'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>
                                            Previous Month<br>
                                            <small class="text-muted"><?php echo $previousMonthStart->format('M Y'); ?></small>
                                        </td>
                                        <td class="text-center">MWK <?php echo number_format($previousMonthSales['total_sales'], 2); ?></td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr class="table-info">
                                        <th>Month-over-Month Change</th>
                                        <th class="text-center">
                                            <?php if ($monthlyChange > 0): ?>
                                                <span class="change-indicator change-positive">
                                                    <i class="fas fa-arrow-up"></i> <?php echo number_format(abs($monthlyChange), 2); ?>%
                                                </span>
                                            <?php elseif ($monthlyChange < 0): ?>
                                                <span class="change-indicator change-negative">
                                                    <i class="fas fa-arrow-down"></i> <?php echo number_format(abs($monthlyChange), 2); ?>%
                                                </span>
                                            <?php else: ?>
                                                <span class="change-indicator change-neutral">
                                                    <i class="fas fa-equals"></i> 0%
                                                </span>
                                            <?php endif; ?>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>

        const weeklyChartData = {
            labels: [
                <?php
                foreach ($currentWeekSales['branch_sales'] as $branchData) {
                    echo "'" . addslashes($branchData['branch_name']) . "', ";
                }
                ?>
            ],
            datasets: [{
                label: 'Weekly Sales by Branch',
                data: [
                    <?php
                    foreach ($currentWeekSales['branch_sales'] as $branchData) {
                        echo $branchData['total_sales'] . ', ';
                    }
                    ?>
                ],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)',
                    'rgba(255, 159, 64, 0.7)',
                    'rgba(199, 199, 199, 0.7)',
                    'rgba(83, 102, 255, 0.7)',
                    'rgba(40, 159, 64, 0.7)',
                    'rgba(210, 199, 199, 0.7)'
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 99, 132, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)',
                    'rgba(199, 199, 199, 1)',
                    'rgba(83, 102, 255, 1)',
                    'rgba(40, 159, 64, 1)',
                    'rgba(210, 199, 199, 1)'
                ],
                borderWidth: 1
            }]
        };


        const monthlyChartData = {
            labels: [
                <?php
                foreach ($currentMonthSales['branch_sales'] as $branchData) {
                    echo "'" . addslashes($branchData['branch_name']) . "', ";
                }
                ?>
            ],
            datasets: [{
                label: 'Monthly Sales by Branch',
                data: [
                    <?php
                    foreach ($currentMonthSales['branch_sales'] as $branchData) {
                        echo $branchData['total_sales'] . ', ';
                    }
                    ?>
                ],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)',
                    'rgba(255, 159, 64, 0.7)',
                    'rgba(199, 199, 199, 0.7)',
                    'rgba(83, 102, 255, 0.7)',
                    'rgba(40, 159, 64, 0.7)',
                    'rgba(210, 199, 199, 0.7)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)',
                    'rgba(199, 199, 199, 1)',
                    'rgba(83, 102, 255, 1)',
                    'rgba(40, 159, 64, 1)',
                    'rgba(210, 199, 199, 1)'
                ],
                borderWidth: 1
            }]
        };


        const weeklyCtx = document.getElementById('weeklyChart').getContext('2d');
        const weeklyChart = new Chart(weeklyCtx, {
            type: 'pie',
            data: weeklyChartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += 'MWK ' + new Intl.NumberFormat().format(context.raw);
                                return label;
                            }
                        }
                    }
                }
            }
        });


        const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
        const monthlyChart = new Chart(monthlyCtx, {
            type: 'pie',
            data: monthlyChartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += 'MWK ' + new Intl.NumberFormat().format(context.raw);
                                return label;
                            }
                        }
                    }
                }
            }
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
