<?php
// doc-project | stats/stats.php | Génère l’interface de statistiques de ventes, compare les périodes par année et permet la saisie/récupération des données par date et localisation. | Expose: getWeekDates, getAllSalesData, getPeriodsByYear, getTotalsForPeriod, generateCombinedTable | Dépend de: config.php, update_event.php, fill_table.php, session PHP, base de données pos_events | Impacte: affichage HTML/JS, interactions AJAX, mises à jour de données | Tables: pos_events(date, montant_total_pelissanne, montant_total_lancon, nombre_pelissanne, nombre_lancon, nd_pelissanne, nd_lancon, ed_pelissanne, ed_lancon, weather, events) */
// stats.php
// Activer l'affichage des erreurs (à désactiver en production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Inclure le fichier de configuration pour accéder à la base de données
include 'config.php';

// Vérifier que la connexion PDO est établie
if (!isset($pdo)) {
    die('Erreur de connexion à la base de données.');
}

// Obtenir le paramètre 'location' depuis l'URL pour le tableau principal
$location = $_GET['location'] ?? 'pelissanne';

// Déterminer le suffixe en fonction de la localisation pour le tableau principal
if ($location == 'pelissanne') {
    $suffix = '_pel';
} elseif ($location == 'lancon') {
    $suffix = '';
} elseif ($location == 'both') {
    $suffix = 'both';
} else {
    $suffix = '_pel'; // par défaut, Pélissanne
}

// Déterminer le texte de la sélection en fonction de la localisation
$selection = '';

if ($location == 'pelissanne') {
    $selection = 'Pélissanne';
} elseif ($location == 'lancon') {
    $selection = 'Lançon';
} elseif ($location == 'both') {
    $selection = 'Les deux';
} else {
    $selection = 'Pélissanne';
}

// Obtenir la date sélectionnée ou utiliser la date actuelle
$selectedDate = $_GET['date'] ?? date('Y-m-d');
$currentDate = new DateTime($selectedDate);
$currentYear = (int)$currentDate->format('Y');

// Récupérer le dernier jour saisi dans pos_events
$stmtLastDate = $pdo->prepare("SELECT MAX(date) as last_date FROM pos_events");
$stmtLastDate->execute();
$lastDateRow = $stmtLastDate->fetch(PDO::FETCH_ASSOC);
$lastDataDate = new DateTime($lastDateRow['last_date']);

// Fonction pour obtenir les dates du mardi au dimanche pour une semaine et une année données
function getWeekDates($weekNumber, $year) {
    $dates = [];
    $dto = new DateTime();
    $dto->setISODate($year, $weekNumber);

    // Commencer le mardi
    $dto->modify('tuesday this week');

    for ($i = 0; $i < 6; $i++) {
        $dates[] = clone $dto;
        $dto->modify('+1 day');
    }

    return $dates;
}

// Obtenir le numéro de semaine et les dates pour la date sélectionnée
$currentWeekNumber = (int)$currentDate->format('W');
$weekDates = getWeekDates($currentWeekNumber, $currentYear);

// Définir les années à afficher
$years = [$currentYear, $currentYear - 1, $currentYear - 2, $currentYear - 3, $currentYear - 4];

// Obtenir les dates correspondantes pour chaque année
$datesByYear = [];
$allDates = [];

foreach ($weekDates as $date) {
    $currentDateString = $date->format('Y-m-d');
    $datesByYear[$currentDateString] = [];
    $weekNumber = (int)$date->format('W');
    $dayOfWeek = (int)$date->format('N'); // 1 (Lundi) à 7 (Dimanche)
    foreach ($years as $year) {
        $dateInYear = new DateTime();
        $dateInYear->setISODate($year, $weekNumber, $dayOfWeek);
        $dateInYearString = $dateInYear->format('Y-m-d');
        $datesByYear[$currentDateString][$year] = $dateInYear;
        $allDates[$dateInYearString] = $dateInYear;
    }
}

// Fonction pour récupérer les données de vente pour toutes les dates
// Fonction pour récupérer les données de vente pour toutes les dates
function getAllSalesData($pdo, $dates, $suffix) {
    $dateStrings = [];
    foreach ($dates as $dateObj) {
        $dateStrings[] = $dateObj->format('Y-m-d');
    }

    if (empty($dateStrings)) {
        return [];
    }

    $placeholders = implode(',', array_fill(0, count($dateStrings), '?'));

    // Vérifiez que la requête SQL récupère correctement les données
    $stmtEvent = $pdo->prepare("
        SELECT *
        FROM pos_events
        WHERE date IN ($placeholders)
    ");
    $stmtEvent->execute($dateStrings);

    $eventData = $stmtEvent->fetchAll(PDO::FETCH_ASSOC);

    $data = [];
    foreach ($eventData as $row) {
        $dateString = $row['date'];
        $totalAmount = 0;
        $totalPizzas = 0;
        $nd = 0;
        $ed = 0; // Nouvelle variable pour Montant ED

        // Debug: afficher les données récupérées pour les dates des années précédentes
        // Utilisez var_dump() ou error_log() pour suivre les données
        error_log("Data for date: $dateString, Montant total Pélissanne: {$row['montant_total_pelissanne']}, Montant total Lançon: {$row['montant_total_lancon']}");

        if ($suffix == '_pel') {
            $totalAmount = (float)($row['montant_total_pelissanne'] ?? 0);
            $totalPizzas = (int)($row['nombre_pelissanne'] ?? 0);
            $nd = (float)($row['nd_pelissanne'] ?? 0);
            $ed = (float)($row['ed_pelissanne'] ?? 0); // Montant ED pour Pélissanne
        } elseif ($suffix == '') {
            $totalAmount = (float)($row['montant_total_lancon'] ?? 0);
            $totalPizzas = (int)($row['nombre_lancon'] ?? 0);
            $nd = (float)($row['nd_lancon'] ?? 0);
            $ed = (float)($row['ed_lancon'] ?? 0); // Montant ED pour Lançon
        } elseif ($suffix == 'both') {
            $totalAmount = (float)($row['montant_total_pelissanne'] ?? 0) + (float)($row['montant_total_lancon'] ?? 0);
            $totalPizzas = (int)($row['nombre_pelissanne'] ?? 0) + (int)($row['nombre_lancon'] ?? 0);
            $nd = (float)($row['nd_pelissanne'] ?? 0) + (float)($row['nd_lancon'] ?? 0);
            $ed = (float)($row['ed_pelissanne'] ?? 0) + (float)($row['ed_lancon'] ?? 0); // Montant ED pour les deux
        }

        $weather = $row['weather'] ?? '-';
        $events = $row['events'] ?? '-';

        $data[$dateString] = [
            'total_amount' => $totalAmount,
            'total_pizzas' => $totalPizzas,
            'nd' => $nd,
            'ed' => $ed, // Inclure Montant ED dans les données
            'weather' => $weather,
            'events' => $events,
        ];
    }

    return $data;
}



// Récupérer les données pour toutes les dates
$dataFromDB = getAllSalesData($pdo, $allDates, $suffix);

// Organiser les données
$data = []; // $data[metric][currentDateString][year] = value;

foreach ($datesByYear as $currentDateString => $yearsDates) {
    foreach ($years as $year) {
        $dateObj = $yearsDates[$year];
        $dateString = $dateObj->format('Y-m-d');
        $eventData = $dataFromDB[$dateString] ?? null;

        // Assurez-vous que les montants des années précédentes sont bien récupérés
        $totalAmount = $eventData['total_amount'] ?? 0;
        $totalPizzas = $eventData['total_pizzas'] ?? 0;
        $nd = $eventData['nd'] ?? 0;
        $ed = $eventData['ed'] ?? 0;
        $weather = $eventData['weather'] ?? '-';
        $events = $eventData['events'] ?? '-';

        // Debug: Afficher les données récupérées pour vérifier
        error_log("Total for $dateString, year $year: $totalAmount");

        $data['total_pizzas'][$currentDateString][$year] = $totalPizzas;
        $data['total_amount'][$currentDateString][$year] = $totalAmount;
        $data['nd'][$currentDateString][$year] = $nd;
        $data['ed'][$currentDateString][$year] = $ed;
        $data['weather'][$currentDateString][$year] = $weather;
        $data['events'][$currentDateString][$year] = $events;
    }
}



// En bas de page permettre de choisir *semaine *plage personnalisée

// Récupérer la période sélectionnée
$periode = $_GET['periode'] ?? 'semaine'; // par défaut, 'semaine'

// Récupérer la localisation pour les statistiques supplémentaires
$stats_location = $_GET['stats_location'] ?? $location; // Par défaut, même localisation que le tableau principal

// Déterminer le suffixe en fonction de la localisation pour les statistiques supplémentaires
if ($stats_location == 'pelissanne') {
    $stats_suffix = '_pel';
} elseif ($stats_location == 'lancon') {
    $stats_suffix = '';
} elseif ($stats_location == 'both') {
    $stats_suffix = 'both';
} else {
    $stats_suffix = '_pel'; // par défaut, Pélissanne
}

// Fonction pour obtenir les périodes par année
function getPeriodsByYear($periode, $currentDate, $years, $lastDataDate) {
    $periodsByYear = [];

    if ($periode == 'semaine') {
        $weekNumber = (int)$currentDate->format('W');
        $dayOfWeek = (int)$currentDate->format('N');

        foreach ($years as $year) {
            $startDate = new DateTime();
            $startDate->setISODate($year, $weekNumber);
            $startDate->modify('tuesday this week');

            $endDate = clone $startDate;
            $endDate->modify('+5 days'); // Jusqu'au dimanche

            // Ajuster si nécessaire
            $stmtLastDateYear = $GLOBALS['pdo']->prepare("SELECT MAX(date) as last_date FROM pos_events WHERE YEAR(date) = ?");
            $stmtLastDateYear->execute([$year]);
            $lastDateRowYear = $stmtLastDateYear->fetch(PDO::FETCH_ASSOC);
            $lastDataDateYear = new DateTime($lastDateRowYear['last_date']);

            if ($endDate > $lastDataDateYear && $startDate <= $lastDataDateYear) {
                $endDate = $lastDataDateYear;
            } elseif ($startDate > $lastDataDateYear) {
                $startDate = null;
                $endDate = null;
            }

            $periodsByYear[$year] = ['start' => $startDate, 'end' => $endDate];
        }
    } elseif ($periode == 'personnalisee') {
        $customStart = $_GET['custom_start'] ?? null;
        $customEnd = $_GET['custom_end'] ?? null;
        if ($customStart && $customEnd) {
            $startDateInput = new DateTime($customStart);
            $endDateInput = new DateTime($customEnd);
            if ($startDateInput > $endDateInput) {
                $temp = $startDateInput;
                $startDateInput = $endDateInput;
                $endDateInput = $temp;
            }

            foreach ($years as $year) {
                $startDate = clone $startDateInput;
                $startDate->setDate($year, (int)$startDateInput->format('m'), (int)$startDateInput->format('d'));
                $endDate = clone $endDateInput;
                $endDate->setDate($year, (int)$endDateInput->format('m'), (int)$endDateInput->format('d'));

                // Ajuster si nécessaire
                $stmtLastDateYear = $GLOBALS['pdo']->prepare("SELECT MAX(date) as last_date FROM pos_events WHERE YEAR(date) = ?");
                $stmtLastDateYear->execute([$year]);
                $lastDateRowYear = $stmtLastDateYear->fetch(PDO::FETCH_ASSOC);
                $lastDataDateYear = new DateTime($lastDateRowYear['last_date']);

                if ($endDate > $lastDataDateYear && $startDate <= $lastDataDateYear) {
                    $endDate = $lastDataDateYear;
                } elseif ($startDate > $lastDataDateYear) {
                    $startDate = null;
                    $endDate = null;
                }

                $periodsByYear[$year] = ['start' => $startDate, 'end' => $endDate];
            }
        }
    }

    return $periodsByYear;
}

// Récupérer les périodes par année
$periodsByYear = getPeriodsByYear($periode, $currentDate, $years, $lastDataDate);

// Fonction pour obtenir les totaux pour une période donnée
function getTotalsForPeriod($pdo, $startDate, $endDate, $suffix) {
    if (!$startDate || !$endDate) {
        return ['total_pizzas' => 0, 'total_amount' => 0, 'nd' => 0];
    }
    $startDateString = $startDate->format('Y-m-d');
    $endDateString = $endDate->format('Y-m-d');

    $stmt = $pdo->prepare("
        SELECT SUM(montant_total_pelissanne) as total_amount_pelissanne,
               SUM(nombre_pelissanne) as total_pizzas_pelissanne,
               SUM(nd_pelissanne) as nd_pelissanne,
               SUM(montant_total_lancon) as total_amount_lancon,
               SUM(nombre_lancon) as total_pizzas_lancon,
               SUM(nd_lancon) as nd_lancon
        FROM pos_events
        WHERE date BETWEEN ? AND ?
    ");
    $stmt->execute([$startDateString, $endDateString]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $totalAmount = 0;
    $totalPizzas = 0;
    $nd = 0;

    if ($suffix == '_pel') {
        $totalAmount = (float)($row['total_amount_pelissanne'] ?? 0);
        $totalPizzas = (int)($row['total_pizzas_pelissanne'] ?? 0);
        $nd = (float)($row['nd_pelissanne'] ?? 0);
    } elseif ($suffix == '') {
        $totalAmount = (float)($row['total_amount_lancon'] ?? 0);
        $totalPizzas = (int)($row['total_pizzas_lancon'] ?? 0);
        $nd = (float)($row['nd_lancon'] ?? 0);
    } elseif ($suffix == 'both') {
        $totalAmount = (float)($row['total_amount_pelissanne'] ?? 0) + (float)($row['total_amount_lancon'] ?? 0);
        $totalPizzas = (int)($row['total_pizzas_pelissanne'] ?? 0) + (int)($row['total_pizzas_lancon'] ?? 0);
        $nd = (float)($row['nd_pelissanne'] ?? 0) + (float)($row['nd_lancon'] ?? 0);
    }

    return ['total_pizzas' => $totalPizzas, 'total_amount' => $totalAmount, 'nd' => $nd];
}

// Calculer les totaux pour chaque année
$totals = [];

foreach ($periodsByYear as $year => $period) {
    $start = $period['start'];
    $end = $period['end'];
    $totals[$year] = getTotalsForPeriod($pdo, $start, $end, $stats_suffix);
}

// Fonction pour générer le tableau combiné
function generateCombinedTable($data, $datesByYear, $years, $selectedDate, $currentYear, $location) {
    // $data[metric][currentDateString][year] = value

    echo "<div class='table-wrapper'>";
    echo "<table class='table custom-table'>";
    echo "<thead><tr>";

    // Première cellule fixe
    echo "<th class='sticky-col'>Dates</th>";

    // Générer les en-têtes de dates
    $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::NONE, IntlDateFormatter::NONE, null, null, 'EEEE');

    foreach ($datesByYear as $currentDateString => $yearsDates) {
        $dateObj = $yearsDates[$currentYear]; // get current year's date
        $dayName = $dateObj ? ucfirst($formatter->format($dateObj)) : ''; // Protéger contre null
        $dateFormatted = $dateObj->format('d/m/Y');
        $isCurrentWeek = 'current-week';
        echo "<th class='$isCurrentWeek' data-date='" . $currentDateString . "'>" . $dayName . "<br>" . $dateFormatted . "</th>";
    }
    echo "</tr></thead><tbody>";

    // For each metric, generate a row
    $metrics = ['total_pizzas' => 'Nombre Total de Pizzas', 'total_amount' => 'Montant Total (€)', 'nd' => 'Montant D', 'ed' => 'Montant ED', 'weather' => 'Météo', 'events' => 'Événements'];


    foreach ($metrics as $metricKey => $metricLabel) {
        echo "<tr><th class='sticky-col'>$metricLabel</th>";
        foreach ($datesByYear as $currentDateString => $yearsDates) {
            $cellContent = '';
            $cellContent .= "<div class='cell-content'>";
            foreach ($years as $year) {
                $value = $data[$metricKey][$currentDateString][$year] ?? '-';
                if ($metricKey == 'total_amount' || $metricKey == 'nd') {
                    $value = number_format($value, 2, ',', ' ');
                }
                $dateObjForYear = $yearsDates[$year];
                $dateStringForYear = $dateObjForYear->format('Y-m-d');
                $currentYearClass = ($year == $currentYear) ? 'current-year-value' : '';

                if ($year == $currentYear) {
                    // This is the current year value
                    $isEmptyValue = ($value === null || $value === 0 || $value === '0' || $value === '0,00' || $value === '0.00' || $value === '-' || (is_numeric($value) && (float)$value == 0));

                    if ($isEmptyValue) {
                        // Output button instead of value
                        if ($metricKey == 'total_pizzas' || $metricKey == 'total_amount') {
                            $buttonLabel = 'Récupérer';
                        } else {
                            $buttonLabel = 'Renseigner';
                        }
                        // Create button with appropriate data attributes
                        $button = "<button class='btn btn-primary action-button' data-date='$dateStringForYear' data-field='$metricKey' data-location='$location'>$buttonLabel</button>";
                        $cellContent .= "<div class='year-value $currentYearClass' data-year='$year' data-date='$dateStringForYear'>$button</div>";
                    } else {
                        // Output the value as before
                        $cellContent .= "<div class='year-value $currentYearClass' data-year='$year' data-date='$dateStringForYear'><span class='value'>" . htmlspecialchars($value) . "</span></div>";
                    }
                } else {
                    // Output the value as before
                    $cellContent .= "<div class='year-value $currentYearClass' data-year='$year' data-date='$dateStringForYear'><span class='value'>" . htmlspecialchars($value) . "</span></div>";
                }
            }
            $cellContent .= "</div>";
            echo "<td data-field='$metricKey'>$cellContent</td>";
        }
        echo "</tr>";
    }

    echo "</tbody></table></div>";
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Statistiques des Ventes</title>
    <!-- Lien vers Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
    >
    <!-- Styles personnalisés -->
    <style>
        body {
            background-color: #1a1a1a;
            color: #ffffff;
        }
        .custom-table {
            background-color: #2c2c2c;
            color: #ffffff;
            border: 1px solid #444;
            min-width: 800px;
        }
        .custom-table th, .custom-table td {
            border: 1px solid #444;
            text-align: center;
            vertical-align: middle;
            padding: 12px;
            min-width: 100px;
            white-space: nowrap;
        }
        .custom-table th {
            background-color: #333333;
            position: sticky;
            top: 0;
            z-index: 2;
            font-weight: bold;
        }
        .custom-table th.sticky-col, .custom-table td.sticky-col {
            position: sticky;
            left: 0;
            z-index: 3;
            background-color: #333333;
        }
        h2 {
            margin-top: 30px;
            margin-bottom: 20px;
        }
        .table-wrapper {
            overflow-x: auto;
            max-width: 100%;
            margin-bottom: 20px;
        }
        .container {
            max-width: 100%;
        }
        @media (max-width: 576px) {
            .custom-table {
                font-size: 14px;
            }
            .custom-table th, .custom-table td {
                padding: 8px;
                min-width: 80px;
            }
        }
        .btn-group .btn.active {
            background-color: #007bff;
            color: #fff;
        }
        /* Style pour le datepicker */
        .datepicker-container {
            margin-top: 20px;
        }
        /* Style pour rendre les year-value cliquables */
        .year-value {
            cursor: pointer;
        }
        /* Style pour les valeurs des années */
        .year-value {
            margin-bottom: 5px;
            color: #d3d3d3; /* Gris très clair */
            font-weight: normal; /* Pas en gras */
        }
        .year-value.current-year-value {
            color: #ffffff; /* Blanc */
            font-weight: bold; /* En gras */
        }
        .cell-content {
            max-height: 60px;
            overflow-y: auto;
            text-align: left;
        }
        /* Style pour les statistiques supplémentaires */
        .stats-section {
            margin-top: 40px;
            text-align: left;
        }
        .stats-section h3 {
            margin-bottom: 20px;
        }
        .stats-table {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            border-collapse: collapse;
        }
        .stats-table th, .stats-table td {
            border: 1px solid #444;
            padding: 10px;
            text-align: center;
        }
        .stats-table th {
            background-color: #333333;
            font-weight: bold;
        }
        .stats-table td.current-year {
            color: #ffffff; /* Blanc */
            font-weight: bold; /* En gras */
        }
        .stats-table td.other-year {
            color: #d3d3d3; /* Gris très clair */
            font-weight: normal; /* Pas en gras */
        }
        /* Masquer les champs de plage personnalisée par défaut */
        #customPeriodInputs {
            display: none;
        }

        .form-section {
        border: 1px solid #ddd;
        padding: 15px;
        margin-bottom: 20px;
        border-radius: 5px;
    }
    
    .form-section h4 {
        font-size: 1.2em;
        margin-bottom: 10px;
        text-decoration: underline;
    }

    label {
        font-weight: bold;
    }

    .radio-group {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-bottom: 15px;
    }

    .radio-group div {
        display: inline-block;
        text-align: center;
    }
    </style>
</head>
<body>

<div class="container text-center">
    <h1 class="text-center my-4">Statistiques des Ventes</h1>
    <div class="btn-group mb-3" role="group" aria-label="Choix de la localisation">
        <a href="?location=pelissanne&date=<?php echo $selectedDate; ?>" class="btn btn-primary <?php echo ($location == 'pelissanne') ? 'active' : ''; ?>">Pélissanne</a>
        <a href="?location=lancon&date=<?php echo $selectedDate; ?>" class="btn btn-secondary <?php echo ($location == 'lancon') ? 'active' : ''; ?>">Lançon</a>
        <a href="?location=both&date=<?php echo $selectedDate; ?>" class="btn btn-success <?php echo ($location == 'both') ? 'active' : ''; ?>">Les deux</a>
    </div>
<br>


    <!-- Sélecteur de date -->
    <div class="datepicker-container">
        <form method="GET" action="">
            <input type="hidden" name="location" value="<?php echo $location; ?>">
            <label for="datePicker">Choisir une date :</label>
            <input type="date" id="datePicker" name="date" value="<?php echo $selectedDate; ?>">
            <button type="submit" class="btn btn-primary">Afficher la semaine</button>
        </form>
    </div>
    <br>

        <!-- Boutons de navigation des semaines -->
        <div class="btn-group mb-3" role="group" aria-label="Navigation des semaines">
        <?php
        $prevWeekDate = clone $currentDate;
        $prevWeekDate->modify('-1 week');
        $nextWeekDate = clone $currentDate;
        $nextWeekDate->modify('+1 week');
        ?>
        <a href="?location=<?php echo $location; ?>&date=<?php echo $prevWeekDate->format('Y-m-d'); ?>" class="btn btn-light">Semaine précédente</a>
        <a href="?location=<?php echo $location; ?>&date=<?php echo $nextWeekDate->format('Y-m-d'); ?>" class="btn btn-light">Semaine suivante</a>
    </div>
    <br>
    <h1 class="text-center my-4"><?php echo $selection; ?></h1>
    <?php
    // Générer le tableau combiné
    generateCombinedTable($data, $datesByYear, $years, $selectedDate, $currentYear, $location);
    ?>


<!-- Bouton "Mettre à jour" -->
<button type="button" class="btn btn-warning mt-4" id="updateButton">Mettre à jour</button>



    <!-- Statistiques supplémentaires -->
    <div id="stats-section" class="stats-section container text-center">
    <h3>Statistiques supplémentaires</h3>

    <!-- Formulaire de sélection de la période et de la localisation -->
    <form method="GET" action="#stats-section">

        <!-- Section pour la localisation -->
        <div class="form-section">
            <h4>Sélectionner la localisation</h4>
            <div class="radio-group">
                <div>
                    <input type="radio" id="stats_location_pelissanne" name="stats_location" value="pelissanne" <?php if ($stats_location == 'pelissanne') echo 'checked'; ?>>
                    <label for="stats_location_pelissanne">Pélissanne</label>
                </div>
                <div>
                    <input type="radio" id="stats_location_lancon" name="stats_location" value="lancon" <?php if ($stats_location == 'lancon') echo 'checked'; ?>>
                    <label for="stats_location_lancon">Lançon</label>
                </div>
                <div>
                    <input type="radio" id="stats_location_both" name="stats_location" value="both" <?php if ($stats_location == 'both') echo 'checked'; ?>>
                    <label for="stats_location_both">Les deux</label>
                </div>
            </div>
        </div>

        <!-- Section pour la période -->
        <div class="form-section">
            <h4>Sélectionner la période</h4>
            <div class="radio-group">
                <div>
                    <input type="radio" id="periode_semaine" name="periode" value="semaine" <?php if ($periode == 'semaine') echo 'checked'; ?>>
                    <label for="periode_semaine">Semaine</label>
                </div>
                <div>
                    <input type="radio" id="periode_personnalisee" name="periode" value="personnalisee" <?php if ($periode == 'personnalisee') echo 'checked'; ?>>
                    <label for="periode_personnalisee">Plage personnalisée</label>
                </div>
            </div>

            <!-- Pour la plage personnalisée, afficher les champs de date -->
            <div id="customPeriodInputs" style="<?php if ($periode != 'personnalisee') echo 'display: none;'; ?>">
                <label for="customStart">Date de début :</label>
                <input type="date" id="customStart" name="custom_start" value="<?php echo $_GET['custom_start'] ?? ''; ?>"><br>
                <label for="customEnd">Date de fin :</label>
                <input type="date" id="customEnd" name="custom_end" value="<?php echo $_GET['custom_end'] ?? ''; ?>">
            </div>
        </div>

        <!-- Bouton de soumission -->
        <button type="submit" class="btn btn-primary">Afficher les statistiques</button>
    </form>

    <!-- Affichage des statistiques -->
    <h4>
        Statistiques pour la période sélectionnée : <br>
        <?php if ($periode === 'semaine'): ?>
            Semaine N°<?php echo $currentWeekNumber; ?> <br>
        <?php elseif ($periode === 'personnalisee'): ?>
            Du <?php echo date('d/m/Y', strtotime($_GET['custom_start'])); ?> 
            au <?php echo date('d/m/Y', strtotime($_GET['custom_end'])); ?> <br>
        <?php endif; ?>
        <?php echo ucfirst($stats_location); ?>
    </h4>


    <table class="stats-table">
        <tr>
            <th>Année</th>
            <th>Nombre Total de Pizzas</th>
            <th>Montant Total (€)</th>
            <th>Montant D</th>
        </tr>
        <?php foreach ($years as $year): ?>
            <tr>
                <td class="<?php echo ($year == $currentYear) ? 'current-year' : 'other-year'; ?>"><?php echo $year; ?></td>
                <td class="<?php echo ($year == $currentYear) ? 'current-year' : 'other-year'; ?>">
                    <?php echo $totals[$year]['total_pizzas'] ?? 0; ?>
                </td>
                <td class="<?php echo ($year == $currentYear) ? 'current-year' : 'other-year'; ?>">
                    <?php echo number_format($totals[$year]['total_amount'] ?? 0, 2, ',', ' '); ?>
                </td>
                <td class="<?php echo ($year == $currentYear) ? 'current-year' : 'other-year'; ?>">
                    <?php echo number_format($totals[$year]['nd'] ?? 0, 2, ',', ' '); ?>
                </td>
            </tr>
        <?php endforeach; ?>
    </table>
</div>


</div>

<!-- Lien vers Bootstrap JS et dépendances -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script
  src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
></script>
<script
  src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
></script>

<!-- JavaScript pour synchroniser le défilement horizontal des tableaux -->
<script>
    // Obtenir tous les éléments des conteneurs des tableaux
    const tableWrappers = document.querySelectorAll('.table-wrapper');

    // Fonction pour synchroniser le défilement
    function syncScroll(source) {
        tableWrappers.forEach(wrapper => {
            if (wrapper !== source) {
                wrapper.scrollLeft = source.scrollLeft;
            }
        });
    }

    tableWrappers.forEach(wrapper => {
        wrapper.addEventListener('scroll', () => {
            syncScroll(wrapper);
        });
    });

    // Définir la position de défilement initiale pour afficher la semaine sélectionnée
    function scrollToSelectedWeek() {
        const selectedDate = '<?php echo $selectedDate; ?>';
        tableWrappers.forEach(wrapper => {
            const table = wrapper.querySelector('table');
            const ths = table.querySelectorAll('th[data-date]');
            let scrollPosition = 0;
            let found = false;
            ths.forEach((th, index) => {
                if (th.getAttribute('data-date') === selectedDate) {
                    scrollPosition = th.offsetLeft - wrapper.offsetWidth / 2 + th.offsetWidth / 2;
                    found = true;
                }
            });
            if (found) {
                wrapper.scrollLeft = scrollPosition;
            }
        });
    }

    // Appeler la fonction après le chargement de la page
    window.onload = scrollToSelectedWeek;

// Gestion des clics sur les valeurs des années
$(document).on('click', '.year-value', function(event) {
    event.stopPropagation(); // Empêcher la propagation du clic au parent

    // Vérifier si c'est un bouton "Récupérer"
    var button = $(this).find('.action-button');
    if (button.length > 0 && button.text().trim() === 'Récupérer') {
        // Si c'est un bouton "Récupérer", on ne fait rien
        return; // Sortir de la fonction pour ne pas exécuter le reste du code
    }

    var date = $(this).data('date');
    var field = $(this).closest('td').data('field');
    var currentValue = $(this).find('.value').text().trim();
    var location = '<?php echo $location; ?>';

    if (currentValue === '-') {
        currentValue = '';
    }

    var newValue = prompt("Veuillez entrer la valeur pour " + field + " le " + date + " :", currentValue);
    if (newValue !== null) {
        // Envoyer la nouvelle valeur au serveur via AJAX
        $.ajax({
            url: 'update_event.php',
            type: 'POST',
            data: {
                date: date,
                field: field,
                value: newValue,
                location: location
            },
            success: function(response) {
                if (response == 'success') {
                    // Recharger la page pour mettre à jour les données
                    window.location.reload();
                } else {
                    alert('Erreur lors de la mise à jour.');
                }
            },
            error: function() {
                alert('Erreur de communication avec le serveur.');
            }
        });
    }
});



    // Afficher/Masquer les champs de date pour la période personnalisée
    $(document).ready(function(){
        $('input[name="periode"]').change(function(){
            if ($(this).val() == 'personnalisee') {
                $('#customPeriodInputs').show();
            } else {
                $('#customPeriodInputs').hide();
            }
        });
    });

    // Scroll automatique vers la section des statistiques si l'ancre est présente
    document.addEventListener('DOMContentLoaded', function () {
        if (window.location.hash === '#stats-section') {
            document.querySelector('#stats-section').scrollIntoView({ behavior: 'smooth' });
        }
    });

    $(document).ready(function() {
    // Gestion des clics sur les boutons "Récupérer"
    $(document).on('click', '.action-button', function(event) {
        event.preventDefault(); // Empêche le comportement par défaut du bouton

        // Récupérer les valeurs de data-attributes
        var date = $(this).data('date');
        var field = $(this).data('field');
        var location = $(this).data('location');

        // Vérifier que le bouton est bien un "Récupérer"
        if ($(this).text().trim() === 'Récupérer') {
            // Faire une requête AJAX vers fill_table.php avec la valeur de date
            $.ajax({
                url: 'fill_table.php',
                type: 'POST',
                data: { date: date, location: location },
                success: function(response) {
                    alert('Les données pour la date ' + date + ' ont été Récupéreres.');
                    // Vous pouvez également recharger ou mettre à jour la page ici si nécessaire
                    window.location.reload(); // Si vous voulez recharger la page après l'appel
                },
                error: function(xhr, status, error) {
                    alert('Erreur lors de la récupération des données : ' + error);
                }
            });
        }
    });
});


    // Fonction pour obtenir la date du jour au format YYYY-MM-DD
    function getCurrentDate() {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0'); // Les mois commencent à 0
        const day = String(today.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // Envoyer la date du jour via AJAX
    document.getElementById('updateButton').addEventListener('click', function() {
        const currentDate = getCurrentDate(); // Obtenir la date du jour

        // Envoyer la requête AJAX à fill_table.php
        $.ajax({
            url: 'fill_table.php',
            type: 'POST',
            data: { date: currentDate },
            success: function(response) {
                alert('Les données pour la date ' + currentDate + ' ont été récupérées.');
                // Vous pouvez recharger ou mettre à jour la page si nécessaire
                window.location.reload(); // Si vous voulez recharger la page après l'appel
            },
            error: function(xhr, status, error) {
                alert('Erreur lors de la récupération des données : ' + error);
            }
        });
    });



</script>
</body>
</html>
