<?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_fournisseurs_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_fournisseurs_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_fournisseurs_cash(
                    id_achat, categorie_code, numero_paiement, date_paiement,
                    montant_a_payer, montant_paye, mode_paiement, reference_paiement,
                    commentaire, user_cre
                ) VALUES (
                    :id_achat, :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_fournisseurs_cash";
        
        $params = array(
            ':id_achat' => $_POST['id_achat'],
            ':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_fournisseurs_cash');
        $status_result = handlePurchasePaymentStatusChange('CREATE', $_POST['id_achat']);
        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_fournisseurs_cash SET 
                id_achat = :id_achat,
                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_achat' => $_POST['id_achat'],
        ':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_fournisseurs_cash');
    $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_cash'];
    
    $query = "SELECT id_achat FROM paiements_fournisseurs_cash WHERE id_paiement_cash = :id";
    $params = array(':id' => $id);
    $result = metodGet($query, $params)->fetch(PDO::FETCH_ASSOC);
    $id_achat = $result['id_achat'];
    
    $query = "DELETE FROM paiements_fournisseurs_cash WHERE id_paiement_cash = :id";
    $params = array(':id' => $id);
    $delete_result = metodDelete($query, $params, 'paiements_fournisseurs_cash');
    
    $status_result = handlePurchasePaymentStatusChange('DELETE', $id_achat);
    
    echo json_encode($status_result);
    header("HTTP/1.1 200 OK");
    exit();
}

http_response_code(400);

// function handlePurchasePaymentStatusChange($action, $id_achat) {
//     try {
//         // Get total amount from purchase
//         $queryTotal = "SELECT montant_total FROM achats WHERE id_achat = :id_achat";
//         $resultTotal = metodGet($queryTotal, array(':id_achat' => $id_achat));
//         $total = $resultTotal->fetch(PDO::FETCH_ASSOC)['montant_total'];

//         // Get sum of all cash payments
//         $queryCashPayments = "SELECT COALESCE(SUM(montant_paye), 0) as total_cash 
//                              FROM paiements_fournisseurs_cash 
//                              WHERE id_achat = :id_achat";
//         $resultCash = metodGet($queryCashPayments, array(':id_achat' => $id_achat));
//         $totalCash = $resultCash->fetch(PDO::FETCH_ASSOC)['total_cash'];

//         // Get sum of all installment payments
//         $queryInstallments = "SELECT COALESCE(SUM(montant_paye), 0) as total_tranches 
//                              FROM paiements_fournisseurs_tranches 
//                              WHERE id_achat = :id_achat";
//         $resultInstallments = metodGet($queryInstallments, array(':id_achat' => $id_achat));
//         $totalInstallments = $resultInstallments->fetch(PDO::FETCH_ASSOC)['total_tranches'];

//         $totalPaid = $totalCash + $totalInstallments;

//         // Determine payment status
//         $status = 'En attente';
//         if ($totalPaid >= $total) {
//             $status = 'Payé';
//         } else if ($totalPaid > 0) {
//             $status = 'Partiel';
//         }

//         // Update purchase status
//         $queryUpdate = "UPDATE achats 
//                        SET statut_paiement = :status,
//                            date_upd = CURRENT_TIMESTAMP,
//                            user_upd = 'SYSTEM'
//                        WHERE id_achat = :id_achat";
//         $params = array(
//             ':status' => $status,
//             ':id_achat' => $id_achat
//         );
//         metodPut($queryUpdate, $params, 'achats');

//         return array(
//             'success' => true,
//             'message' => "Purchase payment status updated to: $status",
//             'new_status' => $status,
//             'total_amount' => $total,
//             'total_paid' => $totalPaid
//         );
//     } catch (Exception $e) {
//         throw new Exception("Failed to update purchase payment status: " . $e->getMessage());
//     }
// }
?>
