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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    http_response_code(204);
    exit();
}

requireAuth();

// function handleRefund($id_vente, $refund_amount, $motif, $user_cre, $date_refund, $mode_refund, $reference_refund = null, $commentaire = null) {
//     try {
//         error_log("Starting handleRefund process...");
//         error_log("Parameters received: " . json_encode([
//             'id_vente' => $id_vente,
//             'refund_amount' => $refund_amount,
//             'motif' => $motif,
//             'date_refund' => $date_refund,
//             'mode_refund' => $mode_refund
//         ]));

//         // First check if there's a payment plan
//         $checkQuery = "SELECT pct.id_paiement_tranche, pct.montant_total
//                       FROM paiements_clients_tranches pct 
//                       WHERE pct.id_vente = :id_vente";
//         $result = metodGet($checkQuery, array(':id_vente' => $id_vente));
//         $paymentPlan = $result->fetch(PDO::FETCH_ASSOC);
        
//         error_log("Payment plan found: " . json_encode($paymentPlan));

//         // Create refund record
//         $refundQuery = "INSERT INTO refund_client (
//             id_vente, 
//             id_paiement_tranche,
//             montant_refund,
//             motif,
//             date_refund,
//             mode_refund,
//             reference_refund,
//             commentaire,
//             statut_refund, 
//             user_cre
//         ) VALUES (
//             :id_vente,
//             :id_paiement_tranche,
//             :montant_refund,
//             :motif,
//             :date_refund,
//             :mode_refund,
//             :reference_refund,
//             :commentaire,
//             'En attente',
//             :user_cre
//         )";
        
//         $params = array(
//             ':id_vente' => $id_vente,
//             ':id_paiement_tranche' => $paymentPlan ? $paymentPlan['id_paiement_tranche'] : null,
//             ':montant_refund' => $refund_amount,
//             ':motif' => $motif,
//             ':date_refund' => $date_refund,
//             ':mode_refund' => $mode_refund,
//             ':reference_refund' => $reference_refund,
//             ':commentaire' => $commentaire,
//             ':user_cre' => $user_cre
//         );
        
//         error_log("Executing refund insert with params: " . json_encode($params));
        
//         $queryAutoIncrement = "SELECT MAX(id_refund) as id FROM refund_client";
//         $refundResult = metodPost($refundQuery, $queryAutoIncrement, $params, 'refund_client');
        
//         error_log("Refund record created with ID: " . json_encode($refundResult));

//         // If there are pending payments, adjust them
//         if ($paymentPlan) {
//             $pendingQuery = "SELECT id_reglement, montant 
//                            FROM reglements_tranches_clients 
//                            WHERE id_paiement_tranche = :id_paiement_tranche 
//                            AND statut_reglements = 'En attente'
//                            ORDER BY date_echeance ASC";
            
//             $result = metodGet($pendingQuery, array(':id_paiement_tranche' => $paymentPlan['id_paiement_tranche']));
//             $pendingPayments = $result->fetchAll(PDO::FETCH_ASSOC);
            
//             error_log("Found pending payments: " . json_encode($pendingPayments));

//             if (!empty($pendingPayments)) {
//                 $remainingRefund = $refund_amount;
//                 foreach ($pendingPayments as $payment) {
//                     if ($remainingRefund <= 0) break;
                    
//                     if ($remainingRefund >= $payment['montant']) {
//                         // Delete this payment
//                         $deleteQuery = "DELETE FROM reglements_tranches_clients WHERE id_reglement = :id_reglement";
//                         metodDelete($deleteQuery, array(':id_reglement' => $payment['id_reglement']), 'reglements_tranches_clients');
//                         $remainingRefund -= $payment['montant'];
//                     } else {
//                         // Reduce this payment
//                         $updateQuery = "UPDATE reglements_tranches_clients 
//                                       SET montant = montant - :refund_amount,
//                                           user_upd = :user_upd,
//                                           date_upd = CURRENT_TIMESTAMP
//                                       WHERE id_reglement = :id_reglement";
//                         metodPut($updateQuery, [
//                             ':refund_amount' => $remainingRefund,
//                             ':user_upd' => $user_cre,
//                             ':id_reglement' => $payment['id_reglement']
//                         ], 'reglements_tranches_clients');
//                         break;
//                     }
//                 }
//                 error_log("Updated payment installments");
//             }

//             // Update payment plan status
//             updatePaymentPlanStatus($paymentPlan['id_paiement_tranche']);
//         }

//         // Verify the refund was created
//         $verifyQuery = "SELECT * FROM refund_client WHERE id_refund = :id_refund";
//         $verifyResult = metodGet($verifyQuery, array(':id_refund' => $refundResult['id']))->fetch(PDO::FETCH_ASSOC);
//         error_log("Verification of refund record: " . json_encode($verifyResult));

//         return array(
//             'success' => true,
//             'message' => 'Pending payments cancelled and refund record created',
//             'action' => 'refund_created',
//             'refund_amount' => $refund_amount,
//             'refund_id' => $refundResult['id']
//         );

//     } catch (Exception $e) {
//         error_log("Error in handleRefund: " . $e->getMessage());
//         throw $e;
//     }
// }


// function deletePendingPayments($payments) {
//     if (empty($payments)) return;
    
//     try {
//         $ids = array_column($payments, 'id_reglement');
//         $placeholders = str_repeat('?,', count($ids) - 1) . '?';
        
//         $query = "DELETE FROM reglements_tranches_clients 
//                  WHERE id_reglement IN ($placeholders)";
        
//         $params = array_values($ids);
//         return metodDelete($query, $params, 'reglements_tranches_clients');
        
//     } catch (Exception $e) {
//         error_log("Error in deletePendingPayments: " . $e->getMessage());
//         throw new Exception("Failed to delete pending payments: " . $e->getMessage());
//     }
// }

// function updatePaymentPlanStatus($id_paiement_tranche) {
//     try {
//         $query = "UPDATE paiements_clients_tranches 
//                  SET statut_tranches = 
//                     CASE 
//                         WHEN NOT EXISTS (
//                             SELECT 1 FROM reglements_tranches_clients 
//                             WHERE id_paiement_tranche = :id_paiement_tranche 
//                             AND statut_reglements = 'En attente'
//                         ) THEN 'Terminé'
//                         ELSE 'En cours'
//                     END,
//                  date_upd = CURRENT_TIMESTAMP,
//                  user_upd = 'SYSTEM'
//                  WHERE id_paiement_tranche = :id_paiement_tranche";
                 
//         $params = array(':id_paiement_tranche' => $id_paiement_tranche);
//         return metodPut($query, $params, 'paiements_clients_tranches');
        
//     } catch (Exception $e) {
//         error_log("Error in updatePaymentPlanStatus: " . $e->getMessage());
//         throw new Exception("Failed to update payment plan status: " . $e->getMessage());
//     }
// }

function handleRefundScenarios($id_vente, $refundAmount, $user_cre = 'SYSTEM') {
    try {
        error_log("Starting refund scenario handling for vente ID: $id_vente, amount: $refundAmount");
        
        // Get payment plan ID and pending payments
        $queryPlan = "SELECT id_paiement_tranche 
                     FROM paiements_clients_tranches 
                     WHERE id_vente = :id_vente";
        $resultPlan = metodGet($queryPlan, array(':id_vente' => $id_vente));
        $paymentPlan = $resultPlan->fetch(PDO::FETCH_ASSOC);
        
        if (!$paymentPlan) {
            throw new Exception("No payment plan found for vente ID: $id_vente");
        }
        
        $id_paiement_tranche = $paymentPlan['id_paiement_tranche'];
        
        // Get pending payments in chronological order
        $queryPending = "SELECT id_reglement, montant, date_echeance
                        FROM reglements_tranches_clients
                        WHERE id_paiement_tranche = :id_paiement_tranche
                        AND statut_reglements = 'En attente'
                        ORDER BY date_echeance ASC";
        $resultPending = metodGet($queryPending, array(':id_paiement_tranche' => $id_paiement_tranche));
        $pendingPayments = $resultPending->fetchAll(PDO::FETCH_ASSOC);
        
        // Calculate total pending amount
        $totalPending = array_reduce($pendingPayments, function($carry, $payment) {
            return $carry + floatval($payment['montant']);
        }, 0);
        
        error_log("Total pending amount: $totalPending");
        error_log("Refund amount: $refundAmount");
        
        // Scenario 1: Refund equals pending payments
        if (abs($refundAmount - $totalPending) < 0.01) {
            error_log("Scenario 1: Refund equals pending payments");
            deletePendingPayments($id_paiement_tranche);
            return array(
                'success' => true,
                'scenario' => 1,
                'message' => 'All pending payments cancelled',
                'amount_cancelled' => $totalPending
            );
        }
        
        // Scenario 2: Refund less than pending payments
        if ($refundAmount < $totalPending) {
            error_log("Scenario 2: Refund less than pending payments");
            $remainingRefund = $refundAmount;
            $paymentsToDelete = array();
            
            foreach ($pendingPayments as $payment) {
                if ($remainingRefund <= 0) break;
                
                $paymentAmount = floatval($payment['montant']);
                if ($remainingRefund >= $paymentAmount) {
                    $paymentsToDelete[] = $payment['id_reglement'];
                    $remainingRefund -= $paymentAmount;
                } else {
                    // Update last payment instead of deleting
                    $newAmount = $paymentAmount - $remainingRefund;
                    $updateQuery = "UPDATE reglements_tranches_clients 
                                  SET montant = :new_amount,
                                      user_upd = :user_upd,
                                      date_upd = CURRENT_TIMESTAMP
                                  WHERE id_reglement = :id_reglement";
                    metodPut($updateQuery, array(
                        ':new_amount' => $newAmount,
                        ':user_upd' => $user_cre,
                        ':id_reglement' => $payment['id_reglement']
                    ), 'reglements_tranches_clients');
                    $remainingRefund = 0;
                }
            }
            
            if (!empty($paymentsToDelete)) {
                $ids = implode(',', $paymentsToDelete);
                $deleteQuery = "DELETE FROM reglements_tranches_clients 
                              WHERE id_reglement IN ($ids)";
                metodDelete($deleteQuery, array(), 'reglements_tranches_clients');
            }
            
            return array(
                'success' => true,
                'scenario' => 2,
                'message' => 'Pending payments partially cancelled',
                'amount_cancelled' => $refundAmount
            );
        }
        
        // Scenario 3: Refund exceeds pending payments
        error_log("Scenario 3: Refund exceeds pending payments");
        if ($pendingPayments) {
            deletePendingPayments($id_paiement_tranche);
        }
        
        $actualRefundAmount = $refundAmount - $totalPending;
        error_log("Creating refund record for amount: $actualRefundAmount");
        
        // Create refund record
        $refundQuery = "INSERT INTO refund_client (
            id_vente,
            id_paiement_tranche,
            montant_refund,
            motif,
            statut_refund,
            date_refund,
            user_cre
        ) VALUES (
            :id_vente,
            :id_paiement_tranche,
            :montant_refund,
            'Modification vente',
            'En attente',
            CURRENT_DATE,
            :user_cre
        )";
        
        $queryAutoIncrement = "SELECT MAX(id_refund) as id FROM refund_client";
        $refundResult = metodPost($refundQuery, $queryAutoIncrement, array(
            ':id_vente' => $id_vente,
            ':id_paiement_tranche' => $id_paiement_tranche,
            ':montant_refund' => $actualRefundAmount,
            ':user_cre' => $user_cre
        ), 'refund_client');
        
        return array(
            'success' => true,
            'scenario' => 3,
            'message' => 'Pending payments cancelled and refund created',
            'amount_cancelled' => $totalPending,
            'amount_to_refund' => $actualRefundAmount,
            'refund_id' => $refundResult['id']
        );
        
    } catch (Exception $e) {
        error_log("Error in handleRefundScenarios: " . $e->getMessage());
        throw $e;
    }
}

function deletePendingPayments($id_paiement_tranche) {
    $deleteQuery = "DELETE FROM reglements_tranches_clients 
                   WHERE id_paiement_tranche = :id_paiement_tranche 
                   AND statut_reglements = 'En attente'";
    return metodDelete($deleteQuery, array(':id_paiement_tranche' => $id_paiement_tranche), 'reglements_tranches_clients');
}

// Usage in the PUT method of details_ventes.php
if ($_POST['METHOD'] == 'PUT') {
    try {
        // Get current detail info
        $currentDetail = getCurrentDetailInfo($_GET['id_detail_vente']);
        
        // Calculate new total after update
        $newTotal = calculateNewTotal($currentDetail['id_vente'], $_POST, $currentDetail);
        
        // If refund needed
        if ($newTotal < $currentDetail['montant_total']) {
            $refundAmount = $currentDetail['montant_total'] - $newTotal;
            $refundResult = handleRefundScenarios(
                $currentDetail['id_vente'],
                $refundAmount,
                $_POST['user_upd'] ?? 'SYSTEM'
            );
            
            // Process result based on scenario
            switch ($refundResult['scenario']) {
                case 1:
                case 2:
                    // Just update the sale detail as payments are handled
                    updateSaleDetail($_GET['id_detail_vente'], $_POST);
                    break;
                    
                case 3:
                    // Update sale detail and handle refund process
                    updateSaleDetail($_GET['id_detail_vente'], $_POST);
                    // Additional refund processing if needed
                    break;
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Sale detail updated and refund processed',
                'refund_info' => $refundResult
            ]);
            
        } else {
            // Regular update without refund
            updateSaleDetail($_GET['id_detail_vente'], $_POST);
            echo json_encode([
                'success' => true,
                'message' => 'Sale detail updated successfully'
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

// // Handle POST requests

// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//     try {
//         $data = json_decode(file_get_contents('php://input'), true);
//         error_log("Received refund request data: " . print_r($data, true));
        
//         if (json_last_error() !== JSON_ERROR_NONE) {
//             throw new Exception("Invalid JSON: " . json_last_error_msg());
//         }


//         $date_refund = date('Y-m-d', strtotime($data['date_refund']));
//         $user_cre = $data['user_cre'] ?? 'SYSTEM';

//         $result = handleRefund(
//             $data['id_vente'],
//             $data['montant_refund'],
//             $data['motif'] ?? 'Modification vente',
//             $user_cre,
//             $date_refund,
//             $data['mode_refund'],
//             $data['reference_refund'] ?? null,
//             $data['commentaire'] ?? null
//         );
        
//         header('Content-Type: application/json');
//         echo json_encode($result);
        
//     } catch (Exception $e) {
//         error_log("Error processing refund: " . $e->getMessage());
//         http_response_code(500);
//         header('Content-Type: application/json');
//         echo json_encode([
//             'success' => false,
//             'error' => $e->getMessage()
//         ]);
//     }
// }

// if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//     try {
//         if (isset($_GET['id_vente'])) {
//             $query = "SELECT * FROM refund_client WHERE id_vente = :id_vente";
//             $result = metodGet($query, array(':id_vente' => $_GET['id_vente']));
//             echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
//         } else {
//             $query = "SELECT * FROM refund_client";
//             $result = metodGet($query);
//             echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
//         }
//     } catch (Exception $e) {
//         http_response_code(500);
//         echo json_encode([
//             'success' => false,
//             'error' => $e->getMessage()
//         ]);
//     }
// }

?>