<?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 avalnum WHERE Code = :Code";
        $params = array(':Code' => $_GET['Code']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else {
        $query = "SELECT * FROM avalnum";
        $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 avalnum (
            CODNUM, PERIODE, SITE, Value, user_cre
        ) VALUES (
            :CODNUM, :PERIODE, :SITE, :Value, :user_cre
        )";

        $queryAutoIncrement = "SELECT MAX(Code) as Code FROM avalnum";

        $params = array(
            ':CODNUM' => $_POST['CODNUM'],
            ':PERIODE' => $_POST['PERIODE'],
            ':SITE' => $_POST['SITE'],
            ':Value' => $_POST['Value'],
            ':user_cre' => $_POST['user_cre']
        );

        $result = metodPost($query, $queryAutoIncrement, $params, 'avalnum');
        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 avalnum SET
        CODNUM = :CODNUM,
        PERIODE = :PERIODE,
        SITE = :SITE,
        Value = :Value,
        user_upd = :user_upd,
        date_upd = :date_upd
    WHERE Code = :Code";

    $params = array(
        ':Code' => $Code,
        ':CODNUM' => $_POST['CODNUM'],
        ':PERIODE' => $_POST['PERIODE'],
        ':SITE' => $_POST['SITE'],
        ':Value' => $_POST['Value'],
        ':user_upd' => $_POST['user_upd'],
        ':date_upd' => date('Y-m-d H:i:s')
    );

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

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

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