<?php

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

global $Session, $Conf, $Route;
// appel de geolib en admin
require_once __DIR__ . '/../pub/res/php/geolib.php';

function nettoie_input($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

function getinfos($sql) {
    // This is a placeholder function. Replace with actual database query logic.
    // For example, you might use PDO to execute the query and return the results.
    // $db = Database::getInstance();
    // $stmt = $db->prepare($sql);
    // $stmt->execute();
    // return $stmt->fetchAll(PDO::FETCH_ASSOC);
    return [];
}

function eLog($message) {
    error_log($message);
}

switch ($Route->_action) {
    case "export_operation":
        $data = json_decode(file_get_contents("php://input"));
        if (isset($data->cid)) {
            $cid = nettoie_input($data->cid);
            $idMembre = "0";
            $libMembre = "";
            if (isset($data->idMembre) && isset($data->libMembre)) {
                $idMembre = nettoie_input($data->idMembre);
                $libMembre = nettoie_input($data->libMembre);
            }

            // On crée le dossier de l'amicale s'il n'est pas déjà créé
            $dir = 'pub/files/upload/' . $Conf->_entite["rowid"];
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }

            $sql = 'SELECT p.date_eve, u.prenom, u.libelle AS nom, u.nom_tournee, p.fk_type, p.numero, p.rue_bis, p.rue, p.ville, p.fk_habitat, p.appt, p.niveau, p.libelle, p.email, p.phone, p.montant, xtr.libelle AS reglement, p.remarque FROM ope_pass p LEFT JOIN users u ON u.rowid=p.fk_user LEFT JOIN x_types_reglements xtr ON xtr.rowid=p.fk_type_reglement WHERE p.fk_operation=' . $cid;
            if ($idMembre != "0") {
                $sql .= ' AND p.fk_user=' . $idMembre . ';';
            }
            $pass = getinfos($sql);

            $aData = array();
            $aData[] = array(
                'Date',
                'Heure',
                'Prenom',
                'Nom',
                'Tournee',
                'Type',
                'N°',
                'Rue',
                'Ville',
                'Habitat',
                'Donateur',
                'Email',
                'Tel',
                'Montant',
                'Reglement',
                'Remarque'
            );
            foreach ($pass as $p) {
                switch ($p["fk_type"]) {
                    case 1:
                        $ptype = "Effectué";
                        $preglement = $p["reglement"];
                        break;
                    case 2:
                        $ptype = "A finaliser";
                        $preglement = "";
                        break;
                    case 3:
                        $ptype = "Refusé";
                        $preglement = "";
                        break;
                    case 4:
                        $ptype = "Don";
                        $preglement = "";
                        break;
                    case 9:
                        $ptype = "Habitat vide";
                        $preglement = "";
                        break;
                    default:
                        $ptype = $p["fk_type"];
                        $preglement = "";
                        break;
                }
                if ($p["fk_habitat"] == 1) {
                    $phabitat = "Individuel";
                } else {
                    $phabitat = "Etage " . $p["niveau"] . " - Appt " . $p["appt"];
                }
                $dateEve = date("d/m/Y", strtotime($p["date_eve"]));
                $heureEve = date("H:i", strtotime($p["date_eve"]));
                $nom = str_replace("/", "-", $p["nom"]);
                $tournee = str_replace("/", "-", $p["nom_tournee"]);
                $aData[] = array(
                    $dateEve,
                    $heureEve,
                    $p["prenom"],
                    $nom,
                    $tournee,
                    $ptype,
                    $p["numero"] . $p["rue_bis"],
                    $p["rue"],
                    $p["ville"],
                    $phabitat,
                    $p["libelle"],
                    $p["email"],
                    $p["phone"],
                    $p["montant"],
                    $preglement,
                    $p["remarque"]
                );
            }
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $activeWorksheet = $spreadsheet->getActiveSheet()
                ->fromArray($aData, null, 'A1');

            $writer = new Xlsx($spreadsheet);
            if ($idMembre == "0") {
                $xlsxName = $dir . '/geosector-ope-' . $cid . '-' . date("Ymd-His") . '.xlsx';
            } else {
                $libMembre = str_replace("/", "-", $libMembre);
                $libMembre = str_replace("*", "-", $libMembre);
                $xlsxName = $dir . '/geosector-ope-' . $cid . '-' . $libMembre . '-' . date("Ymd-His") . '.xlsx';
            }
            eLog("Export Operation : " . $xlsxName);
            $writer->save($xlsxName);

            $ret = array('url' => $xlsxName);
            echo json_encode($ret);
        }
        break;
}
