<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'payouts' => [],
    'total_pages' => 1,
    'page' => 1
];

if (!isLoggedIn() || getCurrentUser()['role'] !== 'admin') {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF).";
        echo json_encode($response);
        exit();
    }

    $action = $_POST['action'] ?? '';
    $payoutId = (int)($_POST['payout_id'] ?? 0);

    try {
        $stmt_get_pay = $pdo->prepare("SELECT user_id, amount FROM payouts WHERE id = ?");
        $stmt_get_pay->execute([$payoutId]);
        $pay_data = $stmt_get_pay->fetch(PDO::FETCH_ASSOC);

        if (!$pay_data) {
            $response['message'] = "Payout request not found.";
            echo json_encode($response);
            exit();
        }

        require_once __DIR__ . '/../../includes/notification_helper.php';

        if ($action === 'approve') {
            $stmt = $pdo->prepare("UPDATE payouts SET status = 'paid', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$payoutId]);
            
            sendMultichannelNotification($pay_data['user_id'], 'payout_status', [
                'amount' => number_format($pay_data['amount'], 2),
                'status' => 'Paid'
            ]);
            $response['success'] = true;
            $response['message'] = "Payout marked as Paid.";
            logAuditEvent('admin_approve_payout', 'payout', $payoutId, "Approved payout of ₹" . number_format($pay_data['amount'], 2) . " for user #" . $pay_data['user_id']);
        } elseif ($action === 'reject') {
            $stmt = $pdo->prepare("UPDATE payouts SET status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$payoutId]);

            sendMultichannelNotification($pay_data['user_id'], 'payout_status', [
                'amount' => number_format($pay_data['amount'], 2),
                'status' => 'Rejected'
            ]);
            $response['success'] = true;
            $response['message'] = "Payout rejected.";
            logAuditEvent('admin_reject_payout', 'payout', $payoutId, "Rejected payout of ₹" . number_format($pay_data['amount'], 2) . " for user #" . $pay_data['user_id']);
        }
    } catch (PDOException $e) {
        $response['message'] = "Action failed.";
    }
} else {
    // GET requests
    try {
        $status = $_GET['status'] ?? '';
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $count_q = "SELECT COUNT(*) FROM payouts WHERE 1=1";
        $data_q = "
            SELECT p.*, u.username, u.email 
            FROM payouts p 
            JOIN users u ON p.user_id = u.id 
            WHERE 1=1
        ";
        $params = [];

        if ($status !== '') {
            $count_q .= " AND p.status = ?";
            $data_q .= " AND p.status = ?";
            $params[] = $status;
        }

        $stmt_c = $pdo->prepare($count_q);
        $stmt_c->execute($params);
        $total = (int)$stmt_c->fetchColumn();

        $data_q .= " ORDER BY p.id DESC LIMIT ? OFFSET ?";
        $stmt_d = $pdo->prepare($data_q);
        foreach ($params as $idx => $val) {
            $stmt_d->bindValue($idx + 1, $val);
        }
        $stmt_d->bindValue(count($params) + 1, $limit, PDO::PARAM_INT);
        $stmt_d->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
        $stmt_d->execute();

        $response['payouts'] = $stmt_d->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['total_pages'] = max(1, ceil($total / $limit));
        $response['page'] = $page;
        $response['success'] = true;
    } catch (PDOException $e) {
        $response['message'] = "Database error.";
    }
}

echo json_encode($response);
