<?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 calculatePaymentStatus($id_paiement_tranche)
{
    $query = "SELECT 
        pft.montant_total,
        pft.id_achat,
        pft.categorie_code,
        pft.numero_paiement,
        a.numero_achat,
        f.raison_sociale,
        f.numero_fiscal,
        (
            SELECT COUNT(*) 
            FROM reglements_tranches_fournisseurs rtf 
            WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
        ) as total_tranches,
        (
            SELECT COUNT(*) 
            FROM reglements_tranches_fournisseurs rtf 
            WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche 
            AND rtf.statut_reglements = 'Payé'
            AND rtf.date_paiement IS NOT NULL
        ) as tranches_payees,
        (
            SELECT COALESCE(SUM(montant), 0)
            FROM reglements_tranches_fournisseurs rtf
            WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche 
            AND rtf.statut_reglements = 'Payé'
            AND rtf.date_paiement IS NOT NULL
        ) as total_montant_paye,
        (
            SELECT COALESCE(SUM(montant_refund), 0)
            FROM refund_fournisseur rc
            WHERE rc.id_paiement_tranche = pft.id_paiement_tranche
            AND rc.statut_refund = 'Remboursé'
        ) as total_montant_refund,
        (
            SELECT rtf.montant
            FROM reglements_tranches_fournisseurs rtf
            WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
            AND rtf.statut_reglements = 'En attente'
            ORDER BY rtf.date_echeance ASC
            LIMIT 1
        ) as prochain_montant,
        (
            SELECT rtf.date_echeance
            FROM reglements_tranches_fournisseurs rtf
            WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
            AND rtf.statut_reglements = 'En attente'
            ORDER BY rtf.date_echeance ASC
            LIMIT 1
        ) as prochaine_echeance
    FROM paiements_fournisseurs_tranches pft
    LEFT JOIN achats a ON pft.id_achat = a.id_achat
    LEFT JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur
    WHERE pft.id_paiement_tranche = :id_paiement_tranche";

    $result = metodGet($query, [':id_paiement_tranche' => $id_paiement_tranche]);
    $payment = $result->fetch(PDO::FETCH_ASSOC);

    $montant_total = floatval($payment['montant_total']);
    $montant_paye = floatval($payment['total_montant_paye']);
    $montant_refund = floatval($payment['total_montant_refund']);
    $tranches_total = intval($payment['total_tranches']);
    $tranches_payees = intval($payment['tranches_payees']);

    // Calculate net amount paid (payments minus refunds)
    $montant_net_paye = $montant_paye - $montant_refund;

    // Determine payment status
    $is_completed = ($montant_net_paye >= $montant_total) &&
        ($tranches_payees == $tranches_total);

    $statut_paiement = $is_completed ? 'Terminé' :
        ($montant_net_paye > 0 ? 'En cours' : 'En attente');

    return [
        'montant_total' => $montant_total,
        'montant_paye' => $montant_paye,
        'montant_refund' => $montant_refund,
        'montant_net_paye' => $montant_net_paye,
        'solde_restant' => max(0, $montant_total - $montant_net_paye),
        'total_tranches' => $tranches_total,
        'tranches_payees' => $tranches_payees,
        'tranches_restantes' => $tranches_total - $tranches_payees,
        'statut_paiement' => $statut_paiement,
        'prochain_montant' => $payment['prochain_montant'],
        'prochaine_echeance' => $payment['prochaine_echeance'],
        'fournisseur_nom' => $payment['raison_sociale'],
        'numero_fiscal' => $payment['numero_fiscal'],
        'numero_achat' => $payment['numero_achat'],
        'categorie_code' => $payment['categorie_code'],
        'numero_paiement' => $payment['numero_paiement']
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id_paiement_tranche']) && isset($_GET['details'])) {
    try {
        // First, calculate and update status
        $status = calculateAndUpdateStatus($_GET['id_paiement_tranche']);

        if (!$status) {
            http_response_code(404);
            echo json_encode(['error' => 'Payment not found']);
            exit();
        }

        // Get complete payment details
        $query = "SELECT 
            pft.*,
            a.numero_achat,
            a.montant_total as achat_montant_total,
            f.raison_sociale as fournisseur_nom,
            f.numero_fiscal as numero_fiscal,
            (
                SELECT rtf.montant
                FROM reglements_tranches_fournisseurs rtf
                WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
                AND rtf.statut_reglements = 'En attente'
                ORDER BY rtf.date_echeance ASC
                LIMIT 1
            ) as prochain_montant,
            (
                SELECT rtf.date_echeance
                FROM reglements_tranches_fournisseurs rtf
                WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
                AND rtf.statut_reglements = 'En attente'
                ORDER BY rtf.date_echeance ASC
                LIMIT 1
            ) as prochaine_echeance
            FROM paiements_fournisseurs_tranches pft
            LEFT JOIN achats a ON pft.id_achat = a.id_achat
            LEFT JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur
            WHERE pft.id_paiement_tranche = :id_paiement_tranche";

        $result = metodGet($query, [':id_paiement_tranche' => $_GET['id_paiement_tranche']]);
        $payment = $result->fetch(PDO::FETCH_ASSOC);

        if ($payment) {
            $response = array_merge($payment, $status);
            echo json_encode($response);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Payment not found']);
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'GET') {


    try {

        if (isset($_GET['id_paiement_tranche']) && !isset($_GET['details'])) {
            $query = "SELECT * FROM reglements_tranches_fournisseurs WHERE id_paiement_tranche = :id_paiement_tranche";
            $params = array(':id_paiement_tranche' => $_GET['id_paiement_tranche']);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode($data);
            exit();
        }

        if (isset($_GET['id_paiement_tranche']) && isset($_GET['details'])) {
            $query = "SELECT 
                pft.*,
                a.montant_total as achat_montant_total,
                (
                    SELECT COUNT(*) 
                    FROM reglements_tranches_fournisseurs rtf 
                    WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche
                ) as total_tranches,
                (
                    SELECT COUNT(*) 
                    FROM reglements_tranches_fournisseurs rtf 
                    WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche 
                    AND rtf.statut_reglements = 'Payé'
                ) as tranches_payees,
                (
                    SELECT COALESCE(SUM(montant), 0)
                    FROM reglements_tranches_fournisseurs rtf
                    WHERE rtf.id_paiement_tranche = pft.id_paiement_tranche 
                    AND rtf.statut_reglements = 'Payé'
                ) as total_montant_paye
                FROM paiements_fournisseurs_tranches pft
                LEFT JOIN achats a ON pft.id_achat = a.id_achat
                WHERE pft.id_paiement_tranche = :id_paiement_tranche";

            $params = [':id_paiement_tranche' => $_GET['id_paiement_tranche']];
            $result = metodGet($query, $params);
            $payment = $result->fetch(PDO::FETCH_ASSOC);

            if ($payment) {
                $paymentStatus = calculatePaymentStatus($_GET['id_paiement_tranche']);
                $payment = array_merge($payment, $paymentStatus);
                echo json_encode($payment);
                exit();
            }
        }

        if (isset($_GET['status'])) {
            $baseQuery = "
                SELECT 
                    rtf.*,
                    pft.numero_paiement,
                    pft.montant_total,
                    a.numero_achat,
                    f.raison_sociale,
                    f.numero_fiscal,
                    f.telephone
                FROM reglements_tranches_fournisseurs rtf
                LEFT JOIN paiements_fournisseurs_tranches pft ON rtf.id_paiement_tranche = pft.id_paiement_tranche
                LEFT JOIN achats a ON pft.id_achat = a.id_achat
                LEFT JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur
                WHERE 1=1
            ";

            $params = array();

            if ($_GET['status'] === 'pending') {
                $baseQuery .= " AND rtf.statut_reglements = 'En attente'";

                if (isset($_GET['id_fournisseur']) && !empty($_GET['id_fournisseur'])) {
                    $baseQuery .= " AND f.id_fournisseur = :id_fournisseur";
                    $params[':id_fournisseur'] = $_GET['id_fournisseur'];
                } else {
                    if (!isset($_GET['date_start']) && !isset($_GET['date_end'])) {
                        $baseQuery .= " AND DATE(rtf.date_echeance) <= CURRENT_DATE()";
                    }
                }

                if (isset($_GET['date_start']) && !empty($_GET['date_start'])) {
                    $baseQuery .= " AND rtf.date_echeance >= :date_start";
                    $params[':date_start'] = $_GET['date_start'];
                }

                if (isset($_GET['date_end']) && !empty($_GET['date_end'])) {
                    $baseQuery .= " AND rtf.date_echeance <= :date_end";
                    $params[':date_end'] = $_GET['date_end'] . ' 23:59:59';
                }

            } elseif ($_GET['status'] === 'paid') {
                $baseQuery .= " AND rtf.statut_reglements = 'Payé'";

                if (isset($_GET['id_fournisseur']) && !empty($_GET['id_fournisseur'])) {
                    $baseQuery .= " AND f.id_fournisseur = :id_fournisseur";
                    $params[':id_fournisseur'] = $_GET['id_fournisseur'];
                } else {
                    if (!isset($_GET['date_start']) && !isset($_GET['date_end'])) {
                        $baseQuery .= " AND DATE(rtf.date_paiement) = CURRENT_DATE()";
                    }
                }

                if (isset($_GET['date_start']) && !empty($_GET['date_start'])) {
                    $baseQuery .= " AND rtf.date_paiement >= :date_start";
                    $params[':date_start'] = $_GET['date_start'];
                }

                if (isset($_GET['date_end']) && !empty($_GET['date_end'])) {
                    $baseQuery .= " AND rtf.date_paiement <= :date_end";
                    $params[':date_end'] = $_GET['date_end'] . ' 23:59:59';
                }
            }

            $baseQuery .= " ORDER BY CASE 
                WHEN rtf.statut_reglements = 'Payé' THEN rtf.date_paiement 
                ELSE rtf.date_echeance 
            END DESC";

            $result = metodGet($baseQuery, $params);
            $payments = $result->fetchAll(PDO::FETCH_ASSOC);

            foreach ($payments as &$payment) {
                $paymentStatus = calculatePaymentStatus($payment['id_paiement_tranche']);
                $payment = array_merge($payment, $paymentStatus);
            }

            echo json_encode($payments);
            exit();
        }

        if (isset($_GET['all'])) {
            $baseQuery = "
                SELECT 
                    rtf.*,
                    pft.numero_paiement,
                    pft.montant_total as paiement_montant_total,
                    a.numero_achat,
                    a.montant_total as achat_montant_total,
                    f.raison_sociale,
                    f.numero_fiscal,
                    f.telephone
                FROM reglements_tranches_fournisseurs rtf
                LEFT JOIN paiements_fournisseurs_tranches pft ON rtf.id_paiement_tranche = pft.id_paiement_tranche
                LEFT JOIN achats a ON pft.id_achat = a.id_achat
                LEFT JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur
                WHERE 1=1
            ";

            $params = array();

            if (isset($_GET['id_fournisseur']) && !empty($_GET['id_fournisseur'])) {
                $baseQuery .= " AND f.id_fournisseur = :id_fournisseur";
                $params[':id_fournisseur'] = $_GET['id_fournisseur'];
            }

            $baseQuery .= " ORDER BY 
                pft.numero_paiement ASC,
                rtf.numero_tranche ASC";

            $result = metodGet($baseQuery, $params);
            $payments = $result->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode($payments);
            exit();
        }

        http_response_code(400);
        echo json_encode(['error' => 'Invalid parameters']);
        exit();

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

// POST Request Handler
if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);

    try {
        $query = "INSERT INTO reglements_tranches_fournisseurs(
            id_paiement_tranche,
            numero_tranche,
            date_echeance,
            montant,
            date_paiement,
            mode_paiement,
            reference_paiement,
            statut_reglements,
            commentaire,
            user_cre
        ) VALUES (
            :id_paiement_tranche,
            :numero_tranche,
            :date_echeance,
            :montant,
            :date_paiement,
            :mode_paiement,
            :reference_paiement,
            :statut_reglements,
            :commentaire,
            :user_cre
        )";

        $queryAutoIncrement = "SELECT MAX(id_reglement) as id_reglement FROM reglements_tranches_fournisseurs";

        $params = array(
            ':id_paiement_tranche' => $_POST['id_paiement_tranche'],
            ':numero_tranche' => $_POST['numero_tranche'],
            ':date_echeance' => $_POST['date_echeance'],
            ':montant' => $_POST['montant'],
            ':date_paiement' => !empty($_POST['date_paiement']) ? $_POST['date_paiement'] : null,
            ':mode_paiement' => !empty($_POST['mode_paiement']) ? $_POST['mode_paiement'] : null,
            ':reference_paiement' => !empty($_POST['reference_paiement']) ? $_POST['reference_paiement'] : null,
            ':statut_reglements' => $_POST['statut_reglements'] ?? 'En attente',
            ':commentaire' => !empty($_POST['commentaire']) ? $_POST['commentaire'] : null,
            ':user_cre' => $_POST['user_cre']
        );
        $result = metodPost($query, $queryAutoIncrement, $params, 'reglements_tranches_fournisseurs');
        echo json_encode($result);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}

// PUT Request Handler


if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    try {
        if (!isset($_GET['id_reglement'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing id_reglement parameter']);
            exit();
        }

        $id_reglement = $_GET['id_reglement'];


        $getPaymentQuery = "
            SELECT rtf.id_paiement_tranche, pft.montant_total
            FROM reglements_tranches_fournisseurs rtf
            JOIN paiements_fournisseurs_tranches pft ON rtf.id_paiement_tranche = pft.id_paiement_tranche
            WHERE rtf.id_reglement = :id_reglement";

        $paymentResult = metodGet($getPaymentQuery, [':id_reglement' => $id_reglement]);
        $paymentData = $paymentResult->fetch(PDO::FETCH_ASSOC);

        if (!$paymentData) {
            http_response_code(404);
            echo json_encode(['error' => 'Payment not found']);
            exit();
        }


        $totalPaymentsQuery = "
            SELECT COALESCE(SUM(montant), 0) as total_paid
            FROM reglements_tranches_fournisseurs 
            WHERE id_paiement_tranche = :id_paiement_tranche 
            AND id_reglement != :id_reglement
            AND statut_reglements = 'Payé'";

        $totalResult = metodGet($totalPaymentsQuery, [
            ':id_paiement_tranche' => $paymentData['id_paiement_tranche'],
            ':id_reglement' => $id_reglement
        ]);
        $totalData = $totalResult->fetch(PDO::FETCH_ASSOC);


        $newTotal = floatval($totalData['total_paid']);
        if ($_POST['statut_reglements'] == 'Payé') {
            $newTotal += floatval($_POST['montant']);
        }

        if ($newTotal > floatval($paymentData['montant_total'])) {
            http_response_code(400);
            echo json_encode([
                'error' => 'Le montant total des paiements ne peut pas dépasser le montant total initial',
                'montant_total' => $paymentData['montant_total'],
                'total_paid' => $newTotal
            ]);
            exit();
        }


        $updateQuery = "UPDATE reglements_tranches_fournisseurs 
            SET 
                date_paiement = :date_paiement,
                montant = :montant,
                date_echeance = :date_echeance,
                mode_paiement = :mode_paiement,
                reference_paiement = :reference_paiement,
                statut_reglements = :statut_reglements,
                commentaire = :commentaire,
                user_upd = :user_upd,
                date_upd = CURRENT_TIMESTAMP
            WHERE id_reglement = :id_reglement";

        $params = array(
            ':id_reglement' => $id_reglement,
            ':date_paiement' => !empty($_POST['date_paiement']) ? $_POST['date_paiement'] : null,
            ':montant' => $_POST['montant'],
            ':date_echeance' => $_POST['date_echeance'],
            ':mode_paiement' => !empty($_POST['mode_paiement']) ? $_POST['mode_paiement'] : null,
            ':reference_paiement' => !empty($_POST['reference_paiement']) ? $_POST['reference_paiement'] : null,
            ':statut_reglements' => $_POST['statut_reglements'],
            ':commentaire' => !empty($_POST['commentaire']) ? $_POST['commentaire'] : null,
            ':user_upd' => $_POST['user_upd']
        );

        $result = metodPut($updateQuery, $params, 'reglements_tranches_fournisseurs');


        $updateStatus = "
            SELECT 
                COUNT(*) as total_tranches,
                SUM(CASE WHEN statut_reglements = 'Payé' AND date_paiement IS NOT NULL THEN 1 ELSE 0 END) as paid_tranches,
                SUM(CASE WHEN statut_reglements = 'Payé' AND date_paiement IS NOT NULL THEN montant ELSE 0 END) as total_paid
            FROM reglements_tranches_fournisseurs 
            WHERE id_paiement_tranche = :id_paiement_tranche";

        $statusResult = metodGet($updateStatus, [':id_paiement_tranche' => $paymentData['id_paiement_tranche']]);
        $statusData = $statusResult->fetch(PDO::FETCH_ASSOC);

        $isCompleted = ($statusData['total_tranches'] == $statusData['paid_tranches']) &&
            (abs(floatval($statusData['total_paid']) - floatval($paymentData['montant_total'])) < 0.01);

        $newStatus = $isCompleted ? 'Terminé' : ($statusData['paid_tranches'] > 0 ? 'En cours' : 'En attente');


        $updatePaiementQuery = "
            UPDATE paiements_fournisseurs_tranches 
            SET statut_tranches = :status,
                date_upd = CURRENT_TIMESTAMP,
                user_upd = :user_upd
            WHERE id_paiement_tranche = :id_paiement_tranche";

        metodPut($updatePaiementQuery, [
            ':status' => $newStatus,
            ':user_upd' => $_POST['user_upd'],
            ':id_paiement_tranche' => $paymentData['id_paiement_tranche']
        ], 'paiements_fournisseurs_tranches');

        echo json_encode(['success' => true]);
        exit();

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

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    try {
        if (isset($_GET['id_reglement'])) {
            $query = "DELETE FROM reglements_tranches_fournisseurs WHERE id_reglement = :id_reglement";
            $params = array(':id_reglement' => $_GET['id_reglement']);
        } else if (isset($_GET['id_paiement_tranche'])) {
            $query = "DELETE FROM reglements_tranches_fournisseurs WHERE id_paiement_tranche = :id_paiement_tranche";
            $params = array(':id_paiement_tranche' => $_GET['id_paiement_tranche']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required parameter']);
            exit();
        }

        $result = metodDelete($query, $params, 'reglements_tranches_fournisseurs');
        echo json_encode($result);
        http_response_code(200);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}

http_response_code(400);
?>