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

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

requirePermission('counter', 'view');


if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    if (isset($_GET['check_codnum'])) {
        try {
            $query = "SELECT COUNT(*) as count FROM acodnum WHERE CODNUM = :codnum";
            $stmt = $pdo->prepare($query);
            $stmt->execute([':codnum' => $_GET['check_codnum']]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'available' => ($result['count'] == 0),
                'message' => ($result['count'] > 0) ? 'Code already exists' : 'Code is available'
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode([
                'error' => true,
                'message' => $e->getMessage()
            ]);
        }
        exit();
    }
    

    if (isset($_GET['Code'])) {
        $query = "SELECT * FROM acodnum WHERE Code = :Code";
        $params = array(':Code' => $_GET['Code']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else {
        $query = "SELECT * FROM acodnum";
        $result = metodGet($query);
        echo json_encode($result->fetchAll());
    }
    exit();
}






ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        // Log the received data
        error_log("Received POST data: " . print_r($_POST, true));
        
        $query = "INSERT INTO acodnum (
            CODNUM, DES, NIVRAZ, POSCTE, POSCTE1, POSCTE2, Formule,
            POSTYP1, POSTYP2, POSTYP3, POSTYP4, POSTYP5, VAL, TYP, user_cre
        ) VALUES (
            :CODNUM, :DES, :NIVRAZ, :POSCTE, :POSCTE1, :POSCTE2, :Formule,
            :POSTYP1, :POSTYP2, :POSTYP3, :POSTYP4, :POSTYP5, :VAL, :TYP, :user_cre
        )";

        // Prepare parameters with null handling
        $params = array(
            ':CODNUM' => $_POST['CODNUM'] ?? null,
            ':DES' => $_POST['DES'] ?? null,
            ':NIVRAZ' => $_POST['NIVRAZ'] ?? null,
            ':POSCTE' => $_POST['POSCTE'] ?? null,
            ':POSCTE1' => $_POST['POSCTE1'] ?? null,
            ':POSCTE2' => $_POST['POSCTE2'] ?? null,
            ':Formule' => $_POST['Formule'] ?? null,
            ':POSTYP1' => !empty($_POST['POSTYP1']) ? $_POST['POSTYP1'] : null,
            ':POSTYP2' => !empty($_POST['POSTYP2']) ? $_POST['POSTYP2'] : null,
            ':POSTYP3' => !empty($_POST['POSTYP3']) ? $_POST['POSTYP3'] : null,
            ':POSTYP4' => !empty($_POST['POSTYP4']) ? $_POST['POSTYP4'] : null,
            ':POSTYP5' => !empty($_POST['POSTYP5']) ? $_POST['POSTYP5'] : null,
            ':VAL' => !empty($_POST['VAL']) ? $_POST['VAL'] : 0,
            ':TYP' => $_POST['TYP'] ?? 'Alphanumerique',
            ':user_cre' => $_POST['user_cre'] ?? null
        );

        // Log the prepared parameters
        error_log("Prepared parameters: " . print_r($params, true));

        try {
            $result = metodPost($query, null, $params, 'acodnum');
            error_log("Query result: " . print_r($result, true));
            
            echo json_encode([
                'success' => true,
                'message' => 'Record inserted successfully',
                'data' => $result
            ]);
            
        } catch (PDOException $e) {
            error_log("Database error: " . $e->getMessage());
            throw new Exception("Database error: " . $e->getMessage());
        }
        
    } catch (Exception $e) {
        error_log("Error in POST processing: " . $e->getMessage());
        http_response_code(500);
        echo json_encode([
            'error' => true,
            'message' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    $Code = $_GET['Code'];

    $query = "UPDATE acodnum SET
        CODNUM = :CODNUM,
        DES = :DES,
        LNG = :LNG,
        NIVRAZ = :NIVRAZ,
        POSCTE = :POSCTE,
        POSCTE1 = :POSCTE1,
        POSCTE2 = :POSCTE2,
        Formule = :Formule,
        POSTYP1 = :POSTYP1,
        POSTYP2 = :POSTYP2,
        POSTYP3 = :POSTYP3,
        POSTYP4 = :POSTYP4,
        POSTYP5 = :POSTYP5,
        VAL = :VAL,
        TYP = :TYP,
        UPDDAT = :UPDDAT,
        UPDTIM = :UPDTIM,
        user_upd = :user_upd
    WHERE Code = :Code";

    $params = array(
        ':Code' => $Code,
        ':CODNUM' => $_POST['CODNUM'],
        ':DES' => $_POST['DES'],
        ':LNG' => $_POST['LNG'],
        ':NIVRAZ' => $_POST['NIVRAZ'],
        ':POSCTE' => $_POST['POSCTE'],
        ':POSCTE1' => $_POST['POSCTE1'],
        ':POSCTE2' => $_POST['POSCTE2'],
        ':Formule' => $_POST['Formule'],
        ':POSTYP1' => $_POST['POSTYP1'],
        ':POSTYP2' => $_POST['POSTYP2'],
        ':POSTYP3' => $_POST['POSTYP3'],
        ':POSTYP4' => $_POST['POSTYP4'],
        ':POSTYP5' => $_POST['POSTYP5'],
        ':VAL' => $_POST['VAL'],
        ':TYP' => $_POST['TYP'],
        ':UPDDAT' => date('Y-m-d'),
        ':UPDTIM' => date('H:i:s'),
        ':user_upd' => $_POST['user_upd']
    );

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

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

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