<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../config/database.php';

// Vérifier l'authentification
session_start();
if (!isset($_SESSION['user_code'])) {
    echo json_encode(['success' => false, 'message' => 'Non autorisé']);
    exit;
}

$db = Database::getInstance();
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        try {
            $sql = "SELECT * FROM parking_tarifs ORDER BY date_validite DESC";
            $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 parking_tarifs (SiteID, designation, designationAR, prix, date_validite, created_at) 
                    VALUES (?, ?, ?, ?, ?, NOW())";
            $db->query($sql, [
                $data['SiteID'],
                $data['designation'],
                $data['designationAR'],
                $data['prix'],
                $data['date_validite']
            ]);
            echo json_encode(['success' => true, 'message' => 'Tarification ajoutée']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'update':
        $id = $_GET['id'] ?? 0;
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "UPDATE parking_tarifs SET SiteID = ?, designation = ?, designationAR = ?, prix = ?, date_validite = ? WHERE id_tarif = ?";
            $db->query($sql, [
                $data['SiteID'],
                $data['designation'],
                $data['designationAR'],
                $data['prix'],
                $data['date_validite'],
                $id
            ]);
            echo json_encode(['success' => true, 'message' => 'Tarification modifiée']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'delete':
        $id = $_GET['id'] ?? 0;
        try {
            $sql = "DELETE FROM parking_tarifs WHERE id_tarif = ?";
            $db->query($sql, [$id]);
            echo json_encode(['success' => true, 'message' => 'Tarification supprimée']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
