<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (!empty($origin)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}

header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Max-Age: 1728000');

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

include_once __DIR__ . '/unified_config.php';
include_once __DIR__ . '/connection.php';

$input = file_get_contents("php://input");
$data = json_decode($input, true);

$kyc_id = $data['kyc_id'] ?? 0;
$admin_remark = $data['admin_remark'] ?? '';
$action = $data['action'] ?? '';

// Fetch the KYC request regardless of its status
$stmt = $conn->prepare("SELECT * FROM kycupload WHERE id = ?");
$stmt->bind_param("i", $kyc_id);
$stmt->execute();
$kycRequest = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$kycRequest) {
    echo json_encode(["success" => false, "error" => "KYC request not found"]);
    exit;
}

// Determine new status based on action
if ($action === 'approve_kyc') {
    $status = 1; // Approved
} elseif ($action === 'reject_kyc') {
    $status = 2; // Rejected
} else {
    echo json_encode(["success" => false, "error" => "Invalid action"]);
    exit;
}

// Update kycupload table
$stmtUpdate = $conn->prepare("UPDATE kycupload SET Status = ?, Admin_Remark = ?, Admin_Remark_Date = NOW() WHERE id = ?");
$stmtUpdate->bind_param("isi", $status, $admin_remark, $kyc_id);

if ($stmtUpdate->execute()) {
    // ✅ Update loginusers table
    $user_id = $kycRequest['user_id'];
    $stmtUser = $conn->prepare("UPDATE loginusers SET kyc_status = ? WHERE id = ?");
    $stmtUser->bind_param("ii", $status, $user_id);
    $stmtUser->execute();
    $stmtUser->close();

    // ------------------
    // Send KYC approval/rejection email
    // ------------------
    if (EMAIL_AUTOMATION_ENABLED && $status === 1) { // Only send email for approval
        // Get user details for email
        $stmtUserDetails = $conn->prepare("SELECT email, first_name, last_name FROM loginusers WHERE id = ?");
        $stmtUserDetails->bind_param("i", $user_id);
        $stmtUserDetails->execute();
        $userResult = $stmtUserDetails->get_result();
        
        if ($userDetails = $userResult->fetch_assoc()) {
            $mailSystem = getMailSystem();
            $fullName = trim($userDetails['first_name'] . ' ' . $userDetails['last_name']);
            
            $emailResult = $mailSystem->sendKYCApproved(
                $userDetails['email'], 
                $fullName
            );
            
            // Log email result
            if (!$emailResult['success']) {
                error_log("Failed to send KYC approval email to " . $userDetails['email'] . ": " . $emailResult['message']);
            }
        }
        $stmtUserDetails->close();
    }

    $msg = ($status === 1) ? "KYC approved successfully" : "KYC rejected successfully";
    echo json_encode(["success" => true, "message" => $msg, "email_sent" => (EMAIL_AUTOMATION_ENABLED && $status === 1)]);
} else {
    echo json_encode(["success" => false, "error" => "Failed to update KYC: ".$stmtUpdate->error]);
}
?>
