<?php
require_once '../../config/db.php';

header('Content-Type: application/json');

// Admin Auth check needed here

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // LIST
        $sql = "SELECT w.*, u.username, u.email 
                FROM withdrawals w 
                JOIN users u ON w.user_id = u.id 
                ORDER BY w.created_at DESC";
        $withdrawals = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['data' => $withdrawals]);

    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // UPDATE STATUS
        $data = json_decode(file_get_contents("php://input"));
        $id = (int)$data->id;
        $status = $data->status; // 'approved', 'rejected'
        $note = isset($data->note) ? $data->note : '';

        if ($status === 'rejected') {
            // Refund user logic should go here
        }

        $stmt = $pdo->prepare("UPDATE withdrawals SET status = ?, admin_note = ? WHERE id = ?");
        $stmt->execute([$status, $note, $id]);
        
        echo json_encode(['status' => 'success']);
    }

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