<?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') {
    try {
        if (isset($_GET['id_paiement_tranche'])) {
            $query = "SELECT * FROM refund_client 
                     WHERE id_paiement_tranche = :id_paiement_tranche 
                     AND statut_refund = 'Remboursé'";
            $params = array(':id_paiement_tranche' => $_GET['id_paiement_tranche']);
            $result = metodGet($query, $params);
            echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'id_paiement_tranche parameter is required']);
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);
    try {
        $query = "INSERT INTO refund_client(
            id_vente,
            id_paiement_tranche,
            montant_refund,
            motif,
            statut_refund,
            date_refund,
            mode_refund,
            reference_refund,
            commentaire,
            user_cre
        ) VALUES (
            :id_vente,
            :id_paiement_tranche,
            :montant_refund,
            :motif,
            :statut_refund,
            :date_refund,
            :mode_refund,
            :reference_refund,
            :commentaire,
            :user_cre
        )";

        $queryAutoIncrement = "SELECT MAX(id_refund) as id FROM refund_client";
        
        $params = array(
            ':id_vente' => $_POST['id_vente'],
            ':id_paiement_tranche' => $_POST['id_paiement_tranche'],
            ':montant_refund' => $_POST['montant_refund'],
            ':motif' => $_POST['motif'],
            ':statut_refund' => $_POST['statut_refund'] ?? 'En attente',
            ':date_refund' => $_POST['date_refund'] ?? null,
            ':mode_refund' => $_POST['mode_refund'] ?? null,
            ':reference_refund' => $_POST['reference_refund'] ?? null,
            ':commentaire' => $_POST['commentaire'] ?? null,
            ':user_cre' => $_POST['user_cre']
        );

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

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    try {
        if (!isset($_GET['id_refund'])) {
            throw new Exception('id_refund parameter is required');
        }

        $query = "UPDATE refund_client SET
            statut_refund = :statut_refund,
            date_refund = :date_refund,
            mode_refund = :mode_refund,
            reference_refund = :reference_refund,
            commentaire = :commentaire,
            user_upd = :user_upd,
            date_upd = CURRENT_TIMESTAMP
            WHERE id_refund = :id_refund";

        $params = array(
            ':id_refund' => $_GET['id_refund'],
            ':statut_refund' => $_POST['statut_refund'],
            ':date_refund' => $_POST['date_refund'] ?? null,
            ':mode_refund' => $_POST['mode_refund'] ?? null,
            ':reference_refund' => $_POST['reference_refund'] ?? null,
            ':commentaire' => $_POST['commentaire'] ?? null,
            ':user_upd' => $_POST['user_upd']
        );

        $result = metodPut($query, $params, 'refund_client');
        echo json_encode($result);
        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_refund'])) {
            throw new Exception('id_refund parameter is required');
        }

        $query = "DELETE FROM refund_client WHERE id_refund = :id_refund";
        $params = array(':id_refund' => $_GET['id_refund']);
        $result = metodDelete($query, $params, 'refund_client');
        
        echo json_encode($result);
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}

http_response_code(400);
?>