<?php
//statut_paiement


function updatePaymentStatus($id_vente, $pdo) {
    try {
        // First, get the sale type
        $query = "SELECT type_paiement FROM ventes WHERE id_vente = :id_vente";
        $stmt = $pdo->prepare($query);
        $stmt->execute([':id_vente' => $id_vente]);
        $vente = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $newStatus = 'En attente';
        
        if ($vente['type_paiement'] === 'Cash') {
            // Check if payment exists in paiements_clients_cash
            $query = "SELECT montant_a_payer, montant_paye 
                     FROM paiements_clients_cash 
                     WHERE id_vente = :id_vente";
            $stmt = $pdo->prepare($query);
            $stmt->execute([':id_vente' => $id_vente]);
            $payment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($payment) {
                if ($payment['montant_paye'] >= $payment['montant_a_payer']) {
                    $newStatus = 'Payé';
                } else if ($payment['montant_paye'] > 0) {
                    $newStatus = 'Partiel';
                }
            }
            
        } else if ($vente['type_paiement'] === 'Tranche') {
            // First check if installment plan exists
            $query = "SELECT id_paiement_tranche, nombre_tranches 
                     FROM paiements_clients_tranches 
                     WHERE id_vente = :id_vente";
            $stmt = $pdo->prepare($query);
            $stmt->execute([':id_vente' => $id_vente]);
            $tranche = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($tranche) {
                // Count paid installments
                $query = "SELECT COUNT(*) as total_paid 
                         FROM reglements_tranches_clients 
                         WHERE id_paiement_tranche = :id_paiement_tranche 
                         AND statut = 'Payé'";
                $stmt = $pdo->prepare($query);
                $stmt->execute([':id_paiement_tranche' => $tranche['id_paiement_tranche']]);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($result['total_paid'] == $tranche['nombre_tranches']) {
                    $newStatus = 'Payé';
                } else if ($result['total_paid'] > 0) {
                    $newStatus = 'Partiel';
                }
            }
        }
        

        $query = "UPDATE ventes 
                 SET statut_paiement = :statut_paiement 
                 WHERE id_vente = :id_vente";
        $stmt = $pdo->prepare($query);
        $result = $stmt->execute([
            ':statut_paiement' => $newStatus,
            ':id_vente' => $id_vente
        ]);
        
        return [
            'success' => $result,
            'new_status' => $newStatus
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}
?>
