<?php
ob_start();
session_start();
include '../functions.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || !isset($_SESSION['email'])) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Session expired. Please log in again.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$otp   = trim($input['otp'] ?? '');

if ($otp === '' || strlen($otp) !== 6 || !ctype_digit($otp)) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Please enter a valid 6-digit OTP.']);
    exit;
}

$email = $_SESSION['email'];

$stmt = $connect->prepare("SELECT otp FROM users WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row || $otp !== (string)$row['otp']) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Incorrect or expired OTP. Please try again.']);
    exit;
}

$acc_no    = (string)(getUserDetails('acc_no', $email) ?? '');
$cot_code  = $_SESSION['lt_cot_code'] ?? '';
$tax_code  = $_SESSION['lt_tax_code'] ?? '';

// Clear OTP
$stmt = $connect->prepare("UPDATE users SET otp = NULL WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->close();

// Expire COT code
if ($cot_code !== '' && $acc_no !== '') {
    $stmt = $connect->prepare("UPDATE cot_codes SET status = 'Expired', used_by = ? WHERE cot_code = ?");
    $stmt->bind_param("ss", $acc_no, $cot_code);
    $stmt->execute();
    $stmt->close();
}

// Expire Tax code
if ($tax_code !== '' && $acc_no !== '') {
    $stmt = $connect->prepare("UPDATE tax_codes SET status = 'Expired', used_by = ? WHERE tax_code = ?");
    $stmt->bind_param("ss", $acc_no, $tax_code);
    $stmt->execute();
    $stmt->close();
}

// Clear COT/Tax session keys
unset($_SESSION['lt_cot_code'], $_SESSION['lt_tax_code'], $_SESSION['lt_amount']);

// Set verified flag — PHP POST handler in internationaltransfer.php checks this
$_SESSION['it_otp_verified'] = true;

ob_end_clean();
echo json_encode(['success' => true]);
