<?php
//statut_paiement_achat

function updatePaymentStatus($id_achat, $pdo) {
    try {
        // First, get the purchase type
        $query = "SELECT type_paiement FROM achats WHERE id_achat = :id_achat";
        $stmt = $pdo->prepare($query);
        $stmt->execute([':id_achat' => $id_achat]);
        $achat = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $newStatus = 'En attente';
        
        if ($achat['type_paiement'] === 'Cash') {
            // Check if payment exists in paiements_fournisseurs_cash
            $query = "SELECT montant_a_payer, montant_paye 
                     FROM paiements_fournisseurs_cash 
                     WHERE id_achat = :id_achat";
            $stmt = $pdo->prepare($query);
            $stmt->execute([':id_achat' => $id_achat]);
            $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 ($achat['type_paiement'] === 'Tranche') {
            // First check if installment plan exists
            $query = "SELECT id_paiement_tranche, nombre_tranches 
                     FROM paiements_fournisseurs_tranches 
                     WHERE id_achat = :id_achat";
            $stmt = $pdo->prepare($query);
            $stmt->execute([':id_achat' => $id_achat]);
            $tranche = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($tranche) {
                // Count paid installments
                $query = "SELECT COUNT(*) as total_paid 
                         FROM reglements_tranches_fournisseurs 
                         WHERE id_paiement_tranche = :id_paiement_tranche 
                         AND statut_reglements = '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 achats 
                 SET statut_paiement = :statut_paiement 
                 WHERE id_achat = :id_achat";
        $stmt = $pdo->prepare($query);
        $result = $stmt->execute([
            ':statut_paiement' => $newStatus,
            ':id_achat' => $id_achat
        ]);
        
        return [
            'success' => $result,
            'new_status' => $newStatus
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}
?>
