<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// En-têtes CORS et JSON globaux
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// Gestion de la méthode OPTIONS (Pre-flight request)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

// Inclusion de la connexion base de données
require_once __DIR__ . '/../config/database.php';

class EventController {
    private $db;

    public function __construct() {
        $this->db = (new Database())->getConnection();
    }

    // -------------------------------------------------------------
    // GET ALL EVENTS — AVEC MISE À JOUR AUTO ET FILTRE PAR PLAGE DE DATES
    // -------------------------------------------------------------
    public function getAll() {
        // ÉTAPE 1: Mettre à jour automatiquement le statut des événements expirés
        try {
            $updateStmt = $this->db->prepare("UPDATE evenements SET statut = 'fait', updated_at = NOW() WHERE statut = 'planifie' AND date_evenement < CURDATE()");
            $updateStmt->execute();
        } catch (Exception $e) {
            // Log silencieux pour ne pas bloquer l'API
            error_log("Erreur mise à jour statut auto: " . $e->getMessage());
        }

        // ÉTAPE 2: Récupérer les paramètres de filtrage
        $q        = $_GET['q'] ?? null;
        $type     = $_GET['type'] ?? null;
        $dateFrom = $_GET['date_from'] ?? null;
        $dateTo   = $_GET['date_to'] ?? null;

        // Construction dynamique de la clause WHERE
        $where = ["1"];
        $params = [];

        if ($q) {
            $where[] = "(titre LIKE ? OR description LIKE ?)";
            $like = "%$q%";
            $params[] = $like;
            $params[] = $like;
        }

        if ($type) {
            $where[] = "type = ?";
            $params[] = $type;
        }

        if ($dateFrom) {
            $where[] = "date_evenement >= ?";
            $params[] = $dateFrom;
        }

        if ($dateTo) {
            $where[] = "date_evenement <= ?";
            $params[] = $dateTo;
        }

        $whereSql = "WHERE " . implode(" AND ", $where);

        try {
            // Tri par date décroissante (plus récent en haut)
            $sql = "SELECT * FROM evenements $whereSql ORDER BY date_evenement DESC";
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode(["success" => true, "data" => $data]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Erreur serveur: " . $e->getMessage()]);
        }
    }

    // -------------------------------------------------------------
    // GET ONE EVENT
    // -------------------------------------------------------------
    public function getOne() {
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;

        if (!$id) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("SELECT * FROM evenements WHERE id = ?");
            $stmt->execute([$id]);
            $event = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($event) {
                echo json_encode(["success" => true, "data" => $event]);
            } else {
                http_response_code(404);
                echo json_encode(["success" => false, "message" => "Événement introuvable"]);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }

    // -------------------------------------------------------------
    // ADD EVENT
    // -------------------------------------------------------------
    public function add() {
        $input = json_decode(file_get_contents("php://input"), true);

        if (!$input || !isset($input['titre']) || !isset($input['date_evenement'])) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "Paramètres requis manquants (titre, date_evenement)"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("
                INSERT INTO evenements (titre, description, date_evenement, lieu, type, statut, couleur, created_by, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $stmt->execute([
                $input['titre'],
                $input['description'] ?? null,
                $input['date_evenement'],
                $input['lieu'] ?? null,
                $input['type'] ?? 'Autre',
                $input['statut'] ?? "planifie",
                $input['couleur'] ?? "#2196F3",
                $input['created_by'] ?? null
            ]);

            http_response_code(201); // Created
            echo json_encode(["success" => true, "message" => "Événement créé"]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => "Erreur: " . $e->getMessage()]);
        }
    }

    // -------------------------------------------------------------
    // UPDATE EVENT
    // -------------------------------------------------------------
    public function update() {
        $id = isset($_GET['id']) ? intval($_GET['id']) : null;
        $input = json_decode(file_get_contents("php://input"), true);

        if (!$id || !$input) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "ID ou données manquantes"]);
            return;
        }

        $fields = [];
        $params = [];
        $allowedFields = ["titre", "description", "date_evenement", "lieu", "type", "statut", "couleur"];

        foreach ($allowedFields as $f) {
            if (isset($input[$f])) {
                $fields[] = "$f = ?";
                $params[] = $input[$f];
            }
        }

        if (empty($fields)) {
            echo json_encode(["success" => false, "message" => "Aucun champ à mettre à jour"]);
            return;
        }

        $params[] = $id; // Pour la clause WHERE

        try {
            $sql = "UPDATE evenements SET " . implode(", ", $fields) . ", updated_at = NOW() WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            echo json_encode(["success" => true, "message" => "Événement mis à jour"]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }

    // -------------------------------------------------------------
    // MARK EVENT AS DONE
    // -------------------------------------------------------------
    public function markDone() {
        // Accepter ID via GET ou POST
        $id = isset($_GET['id']) ? intval($_GET['id']) : (isset($_POST['id']) ? intval($_POST['id']) : null);
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("UPDATE evenements SET statut='fait', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(["success" => true, "message" => "Événement marqué comme fait"]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }

    // -------------------------------------------------------------
    // DELETE EVENT
    // -------------------------------------------------------------
    public function delete() {
        // Accepter ID via GET ou POST
        $id = isset($_GET['id']) ? intval($_GET['id']) : (isset($_POST['id']) ? intval($_POST['id']) : null);
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "ID manquant"]);
            return;
        }

        try {
            $stmt = $this->db->prepare("DELETE FROM evenements WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(["success" => true, "message" => "Événement supprimé"]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
        }
    }
}

// ---------------- ROUTER ------------------
$controller = new EventController();
$action = $_GET['action'] ?? null;

switch ($action) {
    case 'all':       $controller->getAll(); break;
    case 'get':       $controller->getOne(); break;
    case 'add':       $controller->add(); break;
    case 'update':    $controller->update(); break;
    case 'delete':    $controller->delete(); break;
    case 'mark_done': $controller->markDone(); break;
    default:
        http_response_code(404);
        echo json_encode(["success" => false, "message" => "Action inconnue ou manquante"]);
        break;
}
?>