<?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_vente parameter
    if (isset($_GET['id_vente'])) {
        $query = "SELECT * FROM paiements_clients_tranches WHERE id_vente = :id_vente";
        $params = array(':id_vente' => $_GET['id_vente']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    }
    else if (isset($_GET['id_paiement_tranche'])) {
        $query = "SELECT * FROM paiements_clients_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 - you might want to limit this or require parameters
        http_response_code(400);
        echo json_encode(['error' => 'Please provide id_vente or id_paiement_tranche parameter']);
        exit();
    }
    exit();
}

// Rest of your existing code remains the same
if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    
    try {
        $categorie_code = $_POST['categorie_code'];
        $numero_paiement = reference_generator($categorie_code);
        $query = "INSERT INTO paiements_clients_tranches(id_vente,numero_paiement,categorie_code,nombre_tranches,montant_total,
        montant_par_tranche,date_debut,periodicite_jours,statut_tranches,user_cre
                ) VALUES (:id_vente,: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_clients_tranches";
        $params = array(
            ':id_vente' => $_POST['id_vente'],
            ':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_clients_tranches');
        $status_result = handlePaymentStatusChange('create', $_POST['id_vente']);

        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']);
    try {
        $id_paiement_tranche = $_GET['id_paiement_tranche'];    
        
        // First, count the actual number of tranches
        $countQuery = "SELECT COUNT(*) as nombre_tranches 
                      FROM reglements_tranches_clients 
                      WHERE id_paiement_tranche = :id_paiement_tranche";
        $countParams = array(':id_paiement_tranche' => $id_paiement_tranche);
        $countResult = metodGet($countQuery, $countParams);
        $countData = $countResult->fetch(PDO::FETCH_ASSOC);
        
        if (!$countData) {
            throw new Exception("No installments found");
        }

        $nombre_tranches = $countData['nombre_tranches'];

        // Now update with the counted number of tranches
        $query = "UPDATE paiements_clients_tranches SET 
                    nombre_tranches = :nombre_tranches,
                    statut_tranches = :statut_tranches,
                    user_upd = :user_upd,
                    date_upd = CURRENT_TIMESTAMP
                  WHERE id_paiement_tranche = :id_paiement_tranche";

        $params = array(
            ':id_paiement_tranche' => $id_paiement_tranche,
            ':nombre_tranches' => $nombre_tranches,
            ':statut_tranches' => $_POST['statut_tranches'],
            ':user_upd' => $_POST['user_upd']
        );

        $result = metodPut($query, $params, 'paiements_clients_tranches');
        
        echo json_encode([
            'success' => true,
            'message' => 'Status updated successfully',
            'nombre_tranches' => $nombre_tranches
        ]);

        exit();

    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}


if ($_POST['METHOD'] === 'DELETE') {
    try {
        if (!isset($_GET['id_paiement_tranche'])) {
            http_response_code(400);
            echo json_encode(['error' => 'id_paiement_tranche parameter is required']);
            exit();
        }

        $id_paiement_tranche = $_GET['id_paiement_tranche'];
        

        $query = "SELECT id_vente FROM paiements_clients_tranches WHERE id_paiement_tranche = :id_paiement_tranche";
        $params = array(':id_paiement_tranche' => $id_paiement_tranche);
        $result = metodGet($query, $params);
        $paiement = $result->fetch(PDO::FETCH_ASSOC);
        
        if (!$paiement) {
            http_response_code(404);
            echo json_encode(['error' => 'Payment record not found']);
            exit();
        }
        
        $id_vente = $paiement['id_vente'];

        // First delete all associated reglements
        $deleteReglementsQuery = "DELETE FROM reglements_tranches_clients WHERE id_paiement_tranche = :id_paiement_tranche";
        $reglementsParams = array(':id_paiement_tranche' => $id_paiement_tranche);
        metodDelete($deleteReglementsQuery, $reglementsParams, 'reglements_tranches_clients');

        // Then delete the paiement record
        $deletePaiementQuery = "DELETE FROM paiements_clients_tranches WHERE id_paiement_tranche = :id_paiement_tranche";
        $paiementParams = array(':id_paiement_tranche' => $id_paiement_tranche);
        $result = metodDelete($deletePaiementQuery, $paiementParams, 'paiements_clients_tranches');

        // Update vente status
        $updateVenteQuery = "UPDATE ventes 
                           SET statut_paiement = 'En attente',
                               date_upd = CURRENT_TIMESTAMP
                           WHERE id_vente = :id_vente";
        metodPut($updateVenteQuery, array(':id_vente' => $id_vente), 'ventes');
        
        echo json_encode(['success' => true, 'message' => 'Successfully deleted payment and associated records']);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}
http_response_code(400);

?>