<?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') {
    // Modified this section to properly handle id_achat parameter
    if (isset($_GET['id_achat'])) {
        $query = "SELECT * FROM paiements_fournisseurs_tranches WHERE id_achat = :id_achat";
        $params = array(':id_achat' => $_GET['id_achat']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    }
    else if (isset($_GET['id_paiement_tranche'])) {
        $query = "SELECT * FROM paiements_fournisseurs_tranches WHERE id_paiement_tranche = :id_paiement_tranche";
        $params = array(':id_paiement_tranche' => $_GET['id_paiement_tranche']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    }
    else {
        // Default case - require parameters
        http_response_code(400);
        echo json_encode(['error' => 'Please provide id_achat or id_paiement_tranche parameter']);
        exit();
    }
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $categorie_code = $_POST['categorie_code'];
        $numero_paiement = reference_generator($categorie_code);
        
        $query = "INSERT INTO paiements_fournisseurs_tranches(
                    id_achat, numero_paiement, categorie_code, nombre_tranches,
                    montant_total, montant_par_tranche, date_debut, periodicite_jours,
                    statut_tranches, user_cre
                ) VALUES (
                    :id_achat, :numero_paiement, :categorie_code, :nombre_tranches,
                    :montant_total, :montant_par_tranche, :date_debut, :periodicite_jours,
                    :statut_tranches, :user_cre
                )";
        
        $queryAutoIncrement = "SELECT MAX(id_paiement_tranche) as id FROM paiements_fournisseurs_tranches";
        
        $params = array(
            ':id_achat' => $_POST['id_achat'],
            ':categorie_code' => $categorie_code,
            ':numero_paiement' => $numero_paiement,
            ':nombre_tranches' => $_POST['nombre_tranches'],
            ':montant_total' => $_POST['montant_total'],
            ':montant_par_tranche' => $_POST['montant_par_tranche'],
            ':date_debut' => $_POST['date_debut'],
            ':periodicite_jours' => $_POST['periodicite_jours'],
            ':statut_tranches' => $_POST['statut_tranches'],
            ':user_cre' => $_POST['user_cre']
        );
        
        $result = metodPost($query, $queryAutoIncrement, $params, 'paiements_fournisseurs_tranches');
        $status_result = handlePurchasePaymentStatusChange('CREATE', $_POST['id_achat']);
        
        echo json_encode(['id' => $result['id']]);
        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_tranche = $_GET['id_paiement_tranche'];
    
    $query = "UPDATE paiements_fournisseurs_tranches SET 
                id_achat = :id_achat,
                nombre_tranches = :nombre_tranches,
                montant_total = :montant_total,
                montant_par_tranche = :montant_par_tranche,
                date_debut = :date_debut,
                periodicite_jours = :periodicite_jours,
                statut_tranches = :statut_tranches,
                user_upd = :user_upd
              WHERE id_paiement_tranche = :id_paiement_tranche";
    
    $params = array(
        ':id_paiement_tranche' => $id_paiement_tranche,
        ':id_achat' => $_POST['id_achat'],
        ':nombre_tranches' => $_POST['nombre_tranches'],
        ':montant_total' => $_POST['montant_total'],
        ':montant_par_tranche' => $_POST['montant_par_tranche'],
        ':date_debut' => $_POST['date_debut'],
        ':periodicite_jours' => $_POST['periodicite_jours'],
        ':statut_tranches' => $_POST['statut_tranches'],
        ':user_upd' => $_POST['user_upd']
    );
    
    $result = metodPut($query, $params, 'paiements_fournisseurs_tranches');
    $status_result = handlePurchasePaymentStatusChange('UPDATE', $_POST['id_achat']);
    
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $id = $_GET['id_paiement_tranche'];
    
    // Get id_achat before deleting
    $query = "SELECT id_achat FROM paiements_fournisseurs_tranches WHERE id_paiement_tranche = :id";
    $params = array(':id' => $id);
    $result = metodGet($query, $params)->fetch(PDO::FETCH_ASSOC);
    $id_achat = $result['id_achat'];
    
    // Delete the payment
    $query = "DELETE FROM paiements_fournisseurs_tranches WHERE id_paiement_tranche = :id";
    $params = array(':id' => $id);
    $result = metodDelete($query, $params, 'paiements_fournisseurs_tranches');
    
    // Update payment status
    $status_result = handlePurchasePaymentStatusChange('DELETE', $id_achat);
    
    echo json_encode($result);
    header("HTTP/1.1 200 OK");
    exit();
}

http_response_code(400);
?>
