<?php
include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

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

requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (isset($_GET['Code'])) {
        $query = "SELECT * FROM societes WHERE Code = :Code";
        $params = array(':Code' => $_GET['Code']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else {
        $query = "SELECT *FROM societes";
        $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 societes (description, user_cre) VALUES (:description, :user_cre)";
        $queryAutoIncrement = "SELECT MAX(Code) as Code FROM societes";

        $params = array(
            ':description' => $_POST['description'],
            ':user_cre' => $_POST['user_cre']
        );

        $result = metodPost($query, $queryAutoIncrement, $params, 'societes');
        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']);
    $Code = $_GET['Code'];

    $query = "UPDATE societes SET 
                description = :description,
                user_upd = :user_upd
              WHERE Code = :Code";

    $params = array(
        ':Code' => $Code,
        ':description' => $_POST['description'],
        ':user_upd' => $_POST['user_upd']
    );

    $result = metodPut($query, $params, 'societes');
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

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

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