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

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

requireAuth();

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


if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $categorie_code = $_POST['categorie_code'];
        $numero_paiement = reference_generator($categorie_code);
        
        $query = "INSERT INTO paiements_clients_cash(
                    id_vente, categorie_code, numero_paiement, date_paiement,
                    montant_a_payer, montant_paye, mode_paiement, reference_paiement,
                    commentaire, user_cre
                ) VALUES (
                    :id_vente, :categorie_code, :numero_paiement, :date_paiement,
                    :montant_a_payer, :montant_paye, :mode_paiement, :reference_paiement,
                    :commentaire, :user_cre
                )";
        
        $queryAutoIncrement = "SELECT MAX(id_paiement_cash) as id_paiement_cash FROM paiements_clients_cash";
        
        $params = array(
            ':id_vente' => $_POST['id_vente'],
            ':categorie_code' => $categorie_code,
            ':numero_paiement' => $numero_paiement,
            ':date_paiement' => $_POST['date_paiement'],
            ':montant_a_payer' => $_POST['montant_a_payer'],
            ':montant_paye' => $_POST['montant_paye'],
            ':mode_paiement' => $_POST['mode_paiement'],
            ':reference_paiement' => $_POST['reference_paiement'],
            ':commentaire' => $_POST['commentaire'],
            ':user_cre' => $_POST['user_cre']
        );
        
        $result = metodPost($query, $queryAutoIncrement, $params, 'paiements_clients_cash');
        $status_result = handlePaymentStatusChange('CREATE', $_POST['id_vente']);
        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_paiement_cash = $_GET['id_paiement_cash'];
    
    $query = "UPDATE paiements_clients_cash SET 
                id_vente = :id_vente,
                categorie_code = :categorie_code,
                date_paiement = :date_paiement,
                montant_a_payer = :montant_a_payer,
                montant_paye = :montant_paye,
                mode_paiement = :mode_paiement,
                reference_paiement = :reference_paiement,
                commentaire = :commentaire,
                user_upd = :user_upd
              WHERE id_paiement_cash = :id_paiement_cash";
    
    $params = array(
        ':id_paiement_cash' => $id_paiement_cash,
        ':id_vente' => $_POST['id_vente'],
        ':categorie_code' => $_POST['categorie_code'],
        ':date_paiement' => $_POST['date_paiement'],
        ':montant_a_payer' => $_POST['montant_a_payer'],
        ':montant_paye' => $_POST['montant_paye'],
        ':mode_paiement' => $_POST['mode_paiement'],
        ':reference_paiement' => $_POST['reference_paiement'],
        ':commentaire' => $_POST['commentaire'],
        ':user_upd' => $_POST['user_upd']
    );
    
    $result = metodPut($query, $params, 'paiements_clients_cash');
    $status_result = handlePaymentStatusChange('UPDATE', $_POST['id_vente']);

    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $id = $_GET['id_paiement_cash'];
    
    $query = "SELECT id_vente FROM paiements_clients_cash WHERE id_paiement_cash = :id";
    $params = array(':id' => $id);
    $result = metodGet($query, $params)->fetch(PDO::FETCH_ASSOC);
    $id_vente = $result['id_vente'];
    
    $query = "DELETE FROM paiements_clients_cash WHERE id_paiement_cash = :id";
    $params = array(':id' => $id);
    $delete_result = metodDelete($query, $params, 'paiements_clients_cash');

    $status_result = handlePaymentStatusChange('DELETE', $id_vente);
    
    echo json_encode($status_result);
    header("HTTP/1.1 200 OK");
    exit();
}

http_response_code(400);

?>
