<?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');

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || empty($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Not authenticated.']); exit();
}

$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

// Ensure table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS kyc_verifications (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        user_id      INT NOT NULL,
        full_name    VARCHAR(200) NOT NULL,
        dob          DATE NOT NULL,
        bvn          VARCHAR(11) DEFAULT NULL,
        nin          VARCHAR(11) DEFAULT NULL,
        id_card_file VARCHAR(255) DEFAULT NULL,
        selfie_file  VARCHAR(255) DEFAULT NULL,
        status       ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
        admin_note   TEXT,
        reviewed_by  INT DEFAULT NULL,
        reviewed_at  DATETIME DEFAULT NULL,
        created_at   TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_user (user_id),
        INDEX idx_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    // Fix columns if table already existed with NOT NULL
    $pdo->exec("ALTER TABLE kyc_verifications MODIFY COLUMN bvn VARCHAR(11) DEFAULT NULL");
    $pdo->exec("ALTER TABLE kyc_verifications MODIFY COLUMN nin VARCHAR(11) DEFAULT NULL");
    $pdo->exec("ALTER TABLE kyc_verifications ADD COLUMN IF NOT EXISTS id_card_file VARCHAR(255) DEFAULT NULL");
    $pdo->exec("ALTER TABLE kyc_verifications ADD COLUMN IF NOT EXISTS selfie_file VARCHAR(255) DEFAULT NULL");
} catch (PDOException $e) {}

if ($action === 'submit_kyc') {
    $full_name = trim($_POST['full_name'] ?? '');
    $dob       = trim($_POST['dob'] ?? '');
    $bvn       = trim($_POST['bvn'] ?? '');
    $nin       = trim($_POST['nin'] ?? '');

    // Validation
    if (empty($full_name) || empty($dob)) {
        echo json_encode(['status' => '0', 'msg' => 'Full name and date of birth are required.']); exit();
    }
    if (empty($bvn) && empty($nin)) {
        echo json_encode(['status' => '0', 'msg' => 'Please provide either your BVN or NIN.']); exit();
    }
    if (!empty($bvn) && !preg_match('/^\d{11}$/', $bvn)) {
        echo json_encode(['status' => '0', 'msg' => 'BVN must be exactly 11 digits.']); exit();
    }
    if (!empty($nin) && !preg_match('/^\d{11}$/', $nin)) {
        echo json_encode(['status' => '0', 'msg' => 'NIN must be exactly 11 digits.']); exit();
    }

    // File upload validation
    $upload_dir = dirname(__DIR__, 2) . '/uploads/kyc/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

    $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp', 'application/pdf'];
    $max_size = 5 * 1024 * 1024; // 5MB

    // ID Card upload
    if (empty($_FILES['id_card']['name'])) {
        echo json_encode(['status' => '0', 'msg' => 'Please upload your ID card photo.']); exit();
    }
    if ($_FILES['id_card']['size'] > $max_size) {
        echo json_encode(['status' => '0', 'msg' => 'ID card file too large. Max 5MB.']); exit();
    }
    if (!in_array($_FILES['id_card']['type'], $allowed_types)) {
        echo json_encode(['status' => '0', 'msg' => 'ID card must be JPG, PNG, or PDF.']); exit();
    }

    // Selfie upload
    if (empty($_FILES['selfie']['name'])) {
        echo json_encode(['status' => '0', 'msg' => 'Please upload your selfie photo.']); exit();
    }
    if ($_FILES['selfie']['size'] > $max_size) {
        echo json_encode(['status' => '0', 'msg' => 'Selfie file too large. Max 5MB.']); exit();
    }
    if (!in_array($_FILES['selfie']['type'], ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'])) {
        echo json_encode(['status' => '0', 'msg' => 'Selfie must be JPG or PNG image.']); exit();
    }

    // Save files
    $id_ext = pathinfo($_FILES['id_card']['name'], PATHINFO_EXTENSION);
    $selfie_ext = pathinfo($_FILES['selfie']['name'], PATHINFO_EXTENSION);
    $id_filename = 'id_' . $user_id . '_' . time() . '.' . $id_ext;
    $selfie_filename = 'selfie_' . $user_id . '_' . time() . '.' . $selfie_ext;

    if (!move_uploaded_file($_FILES['id_card']['tmp_name'], $upload_dir . $id_filename)) {
        echo json_encode(['status' => '0', 'msg' => 'Failed to upload ID card. Please try again.']); exit();
    }
    if (!move_uploaded_file($_FILES['selfie']['tmp_name'], $upload_dir . $selfie_filename)) {
        echo json_encode(['status' => '0', 'msg' => 'Failed to upload selfie. Please try again.']); exit();
    }

    // Check if already has pending/approved KYC
    try {
        $check = $pdo->prepare("SELECT status FROM kyc_verifications WHERE user_id = :uid AND status IN ('pending','approved') LIMIT 1");
        $check->execute(['uid' => $user_id]);
        $existing = $check->fetchColumn();
        if ($existing === 'approved') {
            echo json_encode(['status' => '0', 'msg' => 'Your KYC is already verified.']); exit();
        }
        if ($existing === 'pending') {
            echo json_encode(['status' => '0', 'msg' => 'You already have a pending submission. Please wait for review.']); exit();
        }
    } catch (PDOException $e) {}

    // Insert KYC record
    try {
        // Ensure file columns exist
        try {
            $pdo->exec("ALTER TABLE kyc_verifications ADD COLUMN IF NOT EXISTS id_card_file VARCHAR(255) DEFAULT NULL");
            $pdo->exec("ALTER TABLE kyc_verifications ADD COLUMN IF NOT EXISTS selfie_file VARCHAR(255) DEFAULT NULL");
        } catch (PDOException $e) {}

        $pdo->prepare(
            "INSERT INTO kyc_verifications (user_id, full_name, dob, bvn, nin, id_card_file, selfie_file, status) VALUES (:uid, :name, :dob, :bvn, :nin, :id_card, :selfie, 'pending')"
        )->execute([
            'uid'     => $user_id,
            'name'    => $full_name,
            'dob'     => $dob,
            'bvn'     => $bvn ?: null,
            'nin'     => $nin ?: null,
            'id_card' => $id_filename,
            'selfie'  => $selfie_filename,
        ]);

        // Update user's kyc_status field
        try {
            $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS kyc_status ENUM('none','pending','approved','rejected') NOT NULL DEFAULT 'none'");
            $pdo->prepare("UPDATE users SET kyc_status = 'pending' WHERE id = :uid")->execute(['uid' => $user_id]);
        } catch (PDOException $e) {}

        echo json_encode(['status' => '1', 'msg' => 'KYC submitted successfully! You will be notified once reviewed.']);
    } catch (PDOException $e) {
        error_log('[KYC] Insert error for user ' . $user_id . ': ' . $e->getMessage());
        echo json_encode(['status' => '0', 'msg' => 'Submission failed. Please try again.']);
    }
    exit();
}

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