<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once __DIR__ . '/../config/database.php';

$db = Database::getInstance();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            $sites = $db->select("SELECT SiteID, Nom_Site, Nom_SiteAR, Localisation_Site FROM Sites ORDER BY SiteID");
            echo json_encode(['success' => true, 'data' => $sites]);
            exit;
        } elseif ($action === 'get' && isset($_GET['id'])) {
            $site = $db->selectOne("SELECT SiteID, Nom_Site, Nom_SiteAR, Localisation_Site FROM Sites WHERE SiteID = ?", [$_GET['id']]);
            echo json_encode(['success' => (bool)$site, 'data' => $site]);
            exit;
        }
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action GET invalide']);
        exit;
    }

    $inputJson = file_get_contents('php://input');
    $input = json_decode($inputJson, true);

    if ($method === 'POST') {
        $siteId = $input['SiteID'] ?? null;
        $nom = $input['Nom_Site'] ?? null;
        $nomAr = $input['Nom_SiteAR'] ?? null;
        $loc = $input['Localisation_Site'] ?? null;
        $creePar = $input['Cree_Par'] ?? null;
        $dateCreation = $input['Date_Creation'] ?? date('Y-m-d H:i:s');

        if (!$siteId || !$nom || !$nomAr || !$loc) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Champs requis manquants']);
            exit;
        }

        // Vérifier duplication
        $check = $db->selectOne("SELECT COUNT(*) as count FROM Sites WHERE SiteID = ?", [$siteId]);
        if ($check['count'] > 0) {
            http_response_code(409);
            echo json_encode(['success' => false, 'message' => "Le site $siteId existe déjà"]);
            exit;
        }

        $db->query("INSERT INTO Sites (SiteID, Nom_Site, Nom_SiteAR, Localisation_Site, Cree_Par, Date_Creation) VALUES (?, ?, ?, ?, ?, ?)",
                   [$siteId, $nom, $nomAr, $loc, $creePar, $dateCreation]);
        echo json_encode(['success' => true]);
        exit;
    }

    if ($method === 'PUT') {
        $siteId = $input['SiteID'] ?? null;
        if (!$siteId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'SiteID requis']);
            exit;
        }
        $nom = $input['Nom_Site'] ?? '';
        $nomAr = $input['Nom_SiteAR'] ?? '';
        $loc = $input['Localisation_Site'] ?? '';
        $creePar = $input['Cree_Par'] ?? '';
        $dateCreation = $input['Date_Creation'] ?? date('Y-m-d H:i:s');

        $db->query("UPDATE Sites SET Nom_Site = ?, Nom_SiteAR = ?, Localisation_Site = ?, Cree_Par = ?, Date_Creation = ? WHERE SiteID = ?",
                   [$nom, $nomAr, $loc, $creePar, $dateCreation, $siteId]);
        echo json_encode(['success' => true]);
        exit;
    }

    if ($method === 'DELETE') {
        $siteId = $input['SiteID'] ?? ($_GET['id'] ?? null);
        if (!$siteId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'SiteID requis']);
            exit;
        }
        $db->query("DELETE FROM Sites WHERE SiteID = ?", [$siteId]);
        echo json_encode(['success' => true]);
        exit;
    }

    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur API Sites: ' . $e->getMessage()]);
}
?>
