<?php
require_once __DIR__ . '/includes/cors.php';
configureCors();

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// kyc_verify.php
require_once __DIR__ . '../../backend-main/includes/config_loader.php';

// Load dependencies
require_once __DIR__ . '../../backend-main/includes/config.php';
require_once './includes/functions.php';
header("Content-Type: application/json");

// Debug logging
ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "/error_log.log");

// --- Config ---
$MAX_ATTEMPTS = 3;

// --- Helpers ---
function jsonResponse($status, $message, $extra = []) {
    echo json_encode(array_merge([
        "status"  => $status,
        "message" => $message
    ], $extra));
    exit;
}

function getMember($pdo, $memberId) {
    $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
    $stmt->execute([$memberId]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function validateInputs($data) {
    $errors = [];
    $fields = [
        'phone_number'    => 'Phone number',
        'email_address'   => 'Email address',
        'personal_number' => 'Personal number',
        'id_number'       => 'ID number'
    ];

    foreach ($fields as $field => $label) {
        if (empty(trim($data[$field] ?? ''))) {
            $errors[] = "$label is required";
        }
    }

    if (!empty($data['email_address']) && !filter_var($data['email_address'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }

    return $errors;
}

function compareMemberData($input, $member) {
    $results = [
        "matches" => 0,
        "details" => ""
    ];

    $systemValues = [
        "phone_number"    => $member['phone_number'] ?? '',
        "email_address"   => $member['email_address'] ?? '',
        "personal_number" => $member['personal_number'] ?? '',
        "id_number"       => $member['id_number'] ?? ''
    ];

    $results["details"] .= "KYC Verification Attempt:\n";
    $results["details"] .= "System Values:\n";
    foreach ($systemValues as $key => $val) {
        $results["details"] .= "- {$key}: {$val}\n";
    }

    $results["details"] .= "\nUser Provided:\n";
    foreach ($input as $key => $val) {
        $results["details"] .= "- {$key}: {$val}\n";
    }

    $results["details"] .= "\nMatch Results:\n";
    foreach ($systemValues as $key => $sysVal) {
        $userVal = $input[$key] ?? '';
        if (strcasecmp(trim($sysVal), trim($userVal)) === 0) {
            $results["details"] .= "- {$key}: MATCH\n";
            $results["matches"]++;
        } else {
            $results["details"] .= "- {$key}: NO MATCH\n";
        }
    }

    return $results;
}

function handleVerificationSuccess($pdo, $memberId, $details) {
    $stmt = $pdo->prepare("UPDATE members 
        SET kyc_verified = 1, kyc_verified_at = NOW(), kyc_attempts = 0 
        WHERE id = ?");
    $stmt->execute([$memberId]);

    logActivity($pdo, $memberId, 'kyc_verification', $details . "\nResult: SUCCESS ✅");

    jsonResponse("success", "KYC verification successful", ["kyc_required" => false]);
}

function handleVerificationFailure($pdo, $memberId, $attempts, $MAX_ATTEMPTS, $details) {
    $attempts++;
    $locked = $attempts >= $MAX_ATTEMPTS ? 1 : 0;

    $stmt = $pdo->prepare("UPDATE members SET kyc_attempts = ?, kyc_locked = ? WHERE id = ?");
    $stmt->execute([$attempts, $locked, $memberId]);

    $extraNote = "Result: FAILED ❌ (Attempt #{$attempts})";
    logActivity($pdo, $memberId, 'kyc_attempt', $details . "\n" . $extraNote);

    if ($locked) {
        jsonResponse("error", "Too many failed attempts. Your KYC is now locked. Please contact support.", [
            "kyc_required" => true
        ]);
    } else {
        $remaining = $MAX_ATTEMPTS - $attempts;
        jsonResponse("error", "Verification failed. Attempts remaining: {$remaining}", [
            "kyc_required" => true
        ]);
    }
}

// --- Main Flow ---
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse("error", "Invalid request method");
}

// Start session but also accept POST member_id
$memberId = $_SESSION['member_id'] ?? ($_POST['member_id'] ?? null);

if (!$memberId) {
    jsonResponse("error", "Unauthorized access - Member ID missing");
}

$member = getMember($pdo, $memberId);
if (!$member) {
    jsonResponse("error", "Member not found");
}

if ($member['kyc_verified']) {
    jsonResponse("success", "KYC already verified", ["kyc_required" => false]);
}

if ($member['kyc_locked']) {
    jsonResponse("error", "Your KYC has been locked due to too many failed attempts. Please contact support.");
}

// Collect input
$input = [
    'phone_number'    => trim($_POST['phone_number'] ?? ''),
    'email_address'   => trim($_POST['email_address'] ?? ''),
    'personal_number' => trim($_POST['personal_number'] ?? ''),
    'id_number'       => trim($_POST['id_number'] ?? '')
];

// Validate
$errors = validateInputs($input);
if (!empty($errors)) {
    jsonResponse("error", "Validation failed", ["errors" => $errors]);
}

// Compare with DB
$result = compareMemberData($input, $member);

if ($result["matches"] === 4) {
    handleVerificationSuccess($pdo, $memberId, $result["details"]);
} else {
    handleVerificationFailure($pdo, $memberId, (int)$member['kyc_attempts'], $MAX_ATTEMPTS, $result["details"]);
}
