<?php
include 'bd/myData.php';
require_once 'auth.php';

include 'cors.php';
setupCORS();

requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    requirePermission('article', 'view');

    if (isset($_GET['id_marque'])) {
        $query = "SELECT * FROM marque WHERE id_marque = :id_marque";
        $params = array(':id_marque' => $_GET['id_marque']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else if (isset($_GET['id_categorie'])) {
        $query = "SELECT * FROM marque WHERE id_categorie = :id_categorie";
        $params = array(':id_categorie' => $_GET['id_categorie']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else {
        $query = "SELECT * FROM marque ORDER BY description";
        $result = metodGet($query);
        echo json_encode($result->fetchAll());
    }
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $query = "INSERT INTO marque(
                    id_categorie,
                    description
                  ) VALUES (
                    :id_categorie,
                    :description
                  )";
        
        $queryAutoIncrement = "SELECT MAX(id_marque) as id_marque FROM marque";
        
        $params = array(
            ':id_categorie' => $_POST['id_categorie'],
            ':description' => $_POST['description']
        );
        
        $result = metodPost($query, $queryAutoIncrement, $params, 'marque');
        echo json_encode($result);
        header("HTTP/1.1 200 OK");
        
    } catch (Exception $e) {
        header("HTTP/1.1 500 Internal Server Error");
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    $id_marque = $_GET['id_marque'];
    
    $query = "UPDATE marque SET 
                id_categorie = :id_categorie,
                description = :description
              WHERE id_marque = :id_marque";
    
    $params = array(
        ':id_marque' => $id_marque,
        ':id_categorie' => $_POST['id_categorie'],
        ':description' => $_POST['description']
    );
    
    $result = metodPut($query, $params, 'marque');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $id = $_GET['id_marque'];
    $query = "DELETE FROM marque WHERE id_marque = :id";
    $params = array(':id' => $id);
    $result = metodDelete($query, $params, 'marque');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");
?>
