<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once dirname(__DIR__, 2) . '/include/config.php';

header('Content-Type: application/json; charset=utf-8');

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

$action = trim($_POST['action'] ?? '');
$kyc_id = (int)($_POST['kyc_id'] ?? 0);

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

if ($action === 'approve') {
    try {
        $pdo->prepare("UPDATE kyc_verifications SET status = 'approved', reviewed_by = :admin, reviewed_at = NOW() WHERE id = :id")
            ->execute(['admin' => $_SESSION['user_id'], 'id' => $kyc_id]);

        // Update user's kyc_status
        $kyc = $pdo->prepare("SELECT user_id FROM kyc_verifications WHERE id = :id");
        $kyc->execute(['id' => $kyc_id]);
        $row = $kyc->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $pdo->prepare("UPDATE users SET kyc_status = 'approved' WHERE id = :uid")->execute(['uid' => $row['user_id']]);
        }

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

if ($action === 'reject') {
    $reason = trim($_POST['reason'] ?? 'Rejected by admin.');
    try {
        $pdo->prepare("UPDATE kyc_verifications SET status = 'rejected', admin_note = :note, reviewed_by = :admin, reviewed_at = NOW() WHERE id = :id")
            ->execute(['note' => $reason, 'admin' => $_SESSION['user_id'], 'id' => $kyc_id]);

        $kyc = $pdo->prepare("SELECT user_id FROM kyc_verifications WHERE id = :id");
        $kyc->execute(['id' => $kyc_id]);
        $row = $kyc->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $pdo->prepare("UPDATE users SET kyc_status = 'rejected' WHERE id = :uid")->execute(['uid' => $row['user_id']]);
        }

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

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