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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

requireAuth();

// GET request to fetch refunds
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $query = "SELECT r.*, v.numero_vente, c.nom as client_nom, c.prenom as client_prenom 
                 FROM refund_client r
                 LEFT JOIN ventes v ON r.id_vente = v.id_vente
                 LEFT JOIN client c ON v.id_client = c.id_client
                 WHERE 1=1";
        
        $params = array();

        // Apply filters
        if (isset($_GET['tab'])) {
            switch ($_GET['tab']) {
                case 'pending':
                    $query .= " AND r.statut_refund = 'En attente'";
                    break;
                case 'processed':
                    $query .= " AND r.statut_refund = 'Remboursé'";
                    break;
                case 'rejected':
                    $query .= " AND r.statut_refund = 'Rejeté'";
                    break;
            }
        }

        $query .= " ORDER BY r.date_refund DESC";
        
        $result = metodGet($query, $params);
        $refunds = $result->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode($refunds);
        exit();

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

// POST request to process refunds
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['METHOD']) && $_POST['METHOD'] === 'PUT') {
    try {
        if (!isset($_POST['id_refund']) || !isset($_POST['action'])) {
            throw new Exception('Missing required parameters');
        }

        $id_refund = $_POST['id_refund'];
        $action = $_POST['action'];
        $user_upd = $_POST['user_upd'] ?? 'SYSTEM';

        // Get refund details before updating
        $getRefundQuery = "SELECT * FROM refund_client WHERE id_refund = :id_refund";
        $refundResult = metodGet($getRefundQuery, [':id_refund' => $id_refund]);
        $refundData = $refundResult->fetch(PDO::FETCH_ASSOC);

        if (!$refundData) {
            throw new Exception('Refund not found');
        }

        // Update refund status
        $status = $action === 'approve' ? 'Remboursé' : 'Rejeté';
        
        $updateQuery = "UPDATE refund_client 
                       SET statut_refund = :status,
                           date_upd = CURRENT_TIMESTAMP,
                           user_upd = :user_upd
                       WHERE id_refund = :id_refund";
        
        $params = [
            ':status' => $status,
            ':user_upd' => $user_upd,
            ':id_refund' => $id_refund
        ];

        metodPut($updateQuery, $params, 'refund_client');

        echo json_encode(['success' => true, 'message' => 'Refund status updated successfully']);
        exit();

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

// If no valid request method is found
http_response_code(400);
echo json_encode(['error' => 'Invalid request method']);
exit();
?>