<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

try {
    $db = Database::getInstance();
} catch (Exception $e) {
    die(json_encode(['success' => false, 'message' => 'DB Connection failed: ' . $e->getMessage()]));
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        try {
            $showAll = isset($_GET['show_all']) && $_GET['show_all'] == '1';
            $sql = "SELECT * FROM Sites";
            if (!$showAll) {
                $sql .= " WHERE SiteID != 'SG'";
            }
            $sql .= " ORDER BY Nom_Site";
            $result = $db->select($sql);
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'create':
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "INSERT INTO Sites (SiteID, Nom_Site, Nom_SiteAR, Localisation_Site, Cree_Par, Date_Creation) VALUES (?, ?, ?, ?, ?, ?)";
            $db->query($sql, [
                $data['SiteID'],
                $data['Nom_Site'],
                $data['Nom_SiteAR'] ?? '',
                $data['Localisation_Site'] ?? '',
                $data['Cree_Par'] ?? 'System',
                date('Y-m-d H:i:s')
            ]);
            echo json_encode(['success' => true, 'message' => 'Site créé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'update':
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "UPDATE Sites SET Nom_Site = ?, Nom_SiteAR = ?, Localisation_Site = ?, Cree_Par = ?, Date_Creation = ? WHERE SiteID = ?";
            $db->query($sql, [
                $data['Nom_Site'],
                $data['Nom_SiteAR'] ?? '',
                $data['Localisation_Site'] ?? '',
                $data['Cree_Par'] ?? 'System',
                date('Y-m-d H:i:s'),
                $data['SiteID']
            ]);
            echo json_encode(['success' => true, 'message' => 'Site modifié']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'delete':
        $id = $_GET['id'] ?? '';
        try {
            $db->query("DELETE FROM Sites WHERE SiteID = ?", [$id]);
            echo json_encode(['success' => true, 'message' => 'Site supprimé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'get':
        $id = $_GET['id'] ?? '';
        try {
            $result = $db->selectOne("SELECT * FROM Sites WHERE SiteID = ?", [$id]);
            if ($result) {
                echo json_encode(['success' => true, 'data' => $result]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Site non trouvé']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
