<?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' => '', 'kyc' => null];

// Helper function to process KYC document uploads
function processKycUpload($fileInputName, $upload_dir) {
    if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {
        $tmp_name = $_FILES[$fileInputName]['tmp_name'];
        $original_name = $_FILES[$fileInputName]['name'];
        $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
        
        // Max file size: 5MB
        if ($_FILES[$fileInputName]['size'] > 5 * 1024 * 1024) return false;
        
        $allowed_exts = ['jpg', 'jpeg', 'png', 'pdf'];
        if (!in_array($ext, $allowed_exts)) return false;
        
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $tmp_name);
        finfo_close($finfo);
        
        $allowed_mimes = ['image/jpeg', 'image/png', 'application/pdf'];
        if (!in_array($mime, $allowed_mimes)) return false;
        
        $filename = bin2hex(random_bytes(16)) . '.' . $ext;
        if (move_uploaded_file($tmp_name, $upload_dir . '/' . $filename)) {
            return 'uploads/kyc_documents/' . $filename;
        }
    }
    return false;
}

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

$currentUser = getCurrentUser();

// Fetch existing KYC details
$kyc = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt->execute([$currentUser['id']]);
    $kyc = $stmt->fetch(PDO::FETCH_ASSOC);
    $response['kyc'] = $kyc;
} catch (PDOException $e) { }

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

    if (isset($_POST['submit_kyc'])) {
        $doc1_type = 'Aadhaar Card';
        $doc1_number = trim($_POST['doc1_number'] ?? '');
        $doc2_type = 'PAN Card';
        $doc2_number = trim($_POST['doc2_number'] ?? '');
        $bank_name = trim($_POST['bank_name'] ?? '');
        $account_holder = trim($_POST['account_holder'] ?? '');
        $account_number = trim($_POST['account_number'] ?? '');
        $routing_number = strtoupper(trim($_POST['routing_number'] ?? ''));

        $doc1_file = $kyc['doc1_file'] ?? '';
        $doc2_file = $kyc['doc2_file'] ?? '';

        $upload_dir = __DIR__ . '/../uploads/kyc_documents';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $uploaded_doc1 = processKycUpload('doc1_file', $upload_dir);
        if ($uploaded_doc1) $doc1_file = $uploaded_doc1;
        
        $uploaded_doc2 = processKycUpload('doc2_file', $upload_dir);
        if ($uploaded_doc2) $doc2_file = $uploaded_doc2;

        if (empty($doc1_file) || empty($doc2_file) || empty($doc1_number) || empty($doc2_number)) {
            $response['message'] = "Please upload both Aadhaar Card and PAN Card verification documents and enter their numbers.";
        } elseif (empty($bank_name) || empty($account_holder) || empty($account_number) || empty($routing_number)) {
            $response['message'] = "Please fill in all bank account details.";
        } elseif (!preg_match('/^[0-9]{12}$/', $doc1_number)) {
            $response['message'] = "Aadhaar Card number must be exactly 12 numeric digits.";
        } elseif (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i', $doc2_number)) {
            $response['message'] = "PAN Card ID must be a valid 10-character alphanumeric ID matching format (e.g. ABCDE1234F).";
        } elseif (!preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/i', $routing_number)) {
            $response['message'] = "Invalid Bank IFSC Code format. Must be 11 characters starting with 4 letters, then 0, and 6 digits/characters (e.g. SBIN0001234).";
        } else {
            $stmt_min = $pdo->query("SELECT value FROM system_settings WHERE key = 'bank_verification_min_deposit'");
            $min_dep = (float)($stmt_min->fetchColumn() ?: 1.01);

            $stmt_max = $pdo->query("SELECT value FROM system_settings WHERE key = 'bank_verification_max_deposit'");
            $max_dep = (float)($stmt_max->fetchColumn() ?: 1.99);

            $min_cents = (int)round($min_dep * 100);
            $max_cents = (int)round($max_dep * 100);

            $deposit_1 = rand($min_cents, $max_cents) / 100.0;
            $deposit_2 = rand($min_cents, $max_cents) / 100.0;
            $bank_status = 'initiated';

            try {
                if ($kyc) {
                    // Only reset doc status if the file actually changed (don't invalidate already-approved docs)
                    $doc1_status_new = (!empty($uploaded_doc1)) ? 'pending' : ($kyc['doc1_status'] ?? 'pending');
                    $doc2_status_new = (!empty($uploaded_doc2)) ? 'pending' : ($kyc['doc2_status'] ?? 'pending');

                    // Always reset bank status when bank details are re-submitted
                    $deposit_expiry = date('Y-m-d H:i:s', strtotime('+48 hours'));

                    $stmt = $pdo->prepare("
                        UPDATE kyc_records 
                        SET doc1_type = ?, doc1_number = ?, doc1_file = ?, doc1_status = ?,
                            doc2_type = ?, doc2_number = ?, doc2_file = ?, doc2_status = ?,
                            bank_name = ?, account_holder = ?, account_number = ?, routing_number = ?,
                            deposit_1 = ?, deposit_2 = ?, bank_status = ?, deposit_expires_at = ?, updated_at = CURRENT_TIMESTAMP
                        WHERE user_id = ?
                    ");
                    $stmt->execute([
                        $doc1_type, $doc1_number, $doc1_file, $doc1_status_new,
                        $doc2_type, $doc2_number, $doc2_file, $doc2_status_new,
                        $bank_name, $account_holder, $account_number, $routing_number,
                        $deposit_1, $deposit_2, $bank_status, $deposit_expiry, $currentUser['id']
                    ]);
                } else {
                    $deposit_expiry = date('Y-m-d H:i:s', strtotime('+48 hours'));
                    $stmt = $pdo->prepare("
                        INSERT INTO kyc_records (user_id, doc1_type, doc1_number, doc1_file, doc2_type, doc2_number, doc2_file, bank_name, account_holder, account_number, routing_number, deposit_1, deposit_2, bank_status, deposit_expires_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $currentUser['id'], $doc1_type, $doc1_number, $doc1_file, $doc2_type, $doc2_number, $doc2_file,
                        $bank_name, $account_holder, $account_number, $routing_number,
                        $deposit_1, $deposit_2, $bank_status, $deposit_expiry
                    ]);
                }
                
                // Fetch updated
                $stmt = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
                $stmt->execute([$currentUser['id']]);
                $response['kyc'] = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $response['success'] = true;
                $response['message'] = "KYC details saved and bank verification initiated!";
            } catch (PDOException $e) {
                error_log("KYC save error: " . $e->getMessage());
                $response['message'] = "Failed to save KYC details. Please try again.";
            }
        }
    } elseif (isset($_POST['verify_deposits'])) {
        $entered_1 = (float)($_POST['deposit_1'] ?? 0.00);
        $entered_2 = (float)($_POST['deposit_2'] ?? 0.00);

        if ($kyc && $kyc['bank_status'] === 'initiated') {
            // Check if verification window has expired
            if (!empty($kyc['deposit_expires_at']) && strtotime($kyc['deposit_expires_at']) < time()) {
                $response['message'] = "The verification session has expired. Please re-submit your bank details to get new verification amounts.";
            } else {
                $real_1 = (float)$kyc['deposit_1'];
                $real_2 = (float)$kyc['deposit_2'];

                if (($entered_1 === $real_1 && $entered_2 === $real_2) || ($entered_1 === $real_2 && $entered_2 === $real_1)) {
                    try {
                        $stmt = $pdo->prepare("UPDATE kyc_records SET bank_status = 'verified', updated_at = CURRENT_TIMESTAMP WHERE user_id = ?");
                        $stmt->execute([$currentUser['id']]);
                        
                        // Fetch updated
                        $stmt = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
                        $stmt->execute([$currentUser['id']]);
                        $response['kyc'] = $stmt->fetch(PDO::FETCH_ASSOC);

                        $response['success'] = true;
                        $response['message'] = "Bank account verified successfully!";
                    } catch (PDOException $e) {
                        $response['message'] = "Failed to update bank verification status: " . $e->getMessage();
                    }
                } else {
                    $response['message'] = "Verification failed. The micro-deposit amounts entered do not match.";
                }
            }
        } else {
            $response['message'] = "No initiated verification session found.";
        }
    }
} else {
    // GET requests return KYC status
    $response['success'] = true;
}

echo json_encode($response);
