<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) { session_start(); }

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

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

// ── Auth: admin only ───────────────────────────���──────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
    exit();
}
try {
    $auth = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id");
    $auth->execute(['id' => $_SESSION['user_id']]);
    $row = $auth->fetch(PDO::FETCH_ASSOC);
    if (!$row || $row['is_admin'] != 1) {
        echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
        exit();
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Auth error']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = trim($_POST['action'] ?? '');
$id     = intval($_POST['id']   ?? 0);

if (!$id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid withdrawal ID']);
    exit();
}

// ── Fetch the withdrawal ──────────────────────────────────────────────────
try {
    $w_stmt = $pdo->prepare("SELECT * FROM withdrawals WHERE id = :id LIMIT 1");
    $w_stmt->execute([':id' => $id]);
    $withdrawal = $w_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    exit();
}

if (!$withdrawal) {
    echo json_encode(['status' => '0', 'msg' => 'Withdrawal record not found']);
    exit();
}

// ════════════════════════════════════════════════════════════════
// APPROVE — mark as completed
// ════════════════════════════════════════════════════════════════
if ($action === 'approve') {
    if ($withdrawal['status'] === 'completed') {
        echo json_encode(['status' => '0', 'msg' => 'This withdrawal has already been completed.']);
        exit();
    }
    if ($withdrawal['status'] === 'rejected') {
        echo json_encode(['status' => '0', 'msg' => 'Cannot approve a rejected withdrawal.']);
        exit();
    }

    try {
        $pdo->prepare(
            "UPDATE withdrawals
             SET status       = 'completed',
                 processed_by = :admin_id,
                 processed_at = NOW(),
                 updated_at   = NOW()
             WHERE id = :id"
        )->execute([
            'admin_id' => $_SESSION['user_id'],
            'id'       => $id,
        ]);

        echo json_encode([
            'status' => '1',
            'msg'    => 'Withdrawal #' . $id . ' approved and marked as completed.',
        ]);

    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// PROCESSING — mark as processing
// ════════════════════════════════════════════════════════════════
if ($action === 'processing') {
    if (!in_array($withdrawal['status'], ['pending'])) {
        echo json_encode(['status' => '0', 'msg' => 'Can only mark pending withdrawals as processing.']);
        exit();
    }

    try {
        $pdo->prepare(
            "UPDATE withdrawals
             SET status       = 'processing',
                 processed_by = :admin_id,
                 updated_at   = NOW()
             WHERE id = :id"
        )->execute([
            'admin_id' => $_SESSION['user_id'],
            'id'       => $id,
        ]);

        echo json_encode([
            'status' => '1',
            'msg'    => 'Withdrawal #' . $id . ' marked as processing.',
        ]);

    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// REJECT — refund amount to user's referral_balance
// ════════════════════════════════════════════════════════════════
if ($action === 'reject') {
    if ($withdrawal['status'] === 'completed') {
        echo json_encode(['status' => '0', 'msg' => 'Cannot reject an already completed withdrawal.']);
        exit();
    }
    if ($withdrawal['status'] === 'rejected') {
        echo json_encode(['status' => '0', 'msg' => 'This withdrawal has already been rejected.']);
        exit();
    }

    $admin_note = trim($_POST['admin_note'] ?? 'Your withdrawal was rejected by admin.');
    if (empty($admin_note)) {
        echo json_encode(['status' => '0', 'msg' => 'Please provide a rejection reason.']);
        exit();
    }

    $refund_amount = floatval($withdrawal['amount']); // refund the full requested amount

    try {
        $pdo->beginTransaction();

        // Update withdrawal status
        $pdo->prepare(
            "UPDATE withdrawals
             SET status       = 'rejected',
                 admin_note   = :note,
                 processed_by = :admin_id,
                 processed_at = NOW(),
                 updated_at   = NOW()
             WHERE id = :id"
        )->execute([
            'note'     => $admin_note,
            'admin_id' => $_SESSION['user_id'],
            'id'       => $id,
        ]);

        // Refund to user's referral_balance
        $pdo->prepare(
            "UPDATE users SET referral_balance = referral_balance + :amount WHERE id = :uid"
        )->execute([
            'amount' => $refund_amount,
            'uid'    => $withdrawal['user_id'],
        ]);

        $pdo->commit();

        error_log('[Admin] Withdrawal #' . $id . ' rejected by admin ' . $_SESSION['user_id']
            . ' | Refunded ₦' . $refund_amount . ' to user ' . $withdrawal['user_id']);

        echo json_encode([
            'status' => '1',
            'msg'    => 'Withdrawal rejected. ₦' . number_format($refund_amount, 2) . ' refunded to ' . $withdrawal['username'] . '\'s referral balance.',
        ]);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'Error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// DELETE — remove record (no refund for non-pending)
// ════════════════════════════════════════════════════════════════
if ($action === 'delete') {
    try {
        $pdo->prepare("DELETE FROM withdrawals WHERE id = :id")->execute([':id' => $id]);

        echo json_encode([
            'status' => '1',
            'msg'    => 'Withdrawal record #' . $id . ' deleted successfully.',
        ]);

    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Unknown action']);