<?php
require_once("../../autoloader.php");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

$response = array();
$controller = new SubscriberModel;

date_default_timezone_set('Africa/Lagos');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response = array('status' => 'error', 'msg' => 'Invalid request method');
    file_put_contents("kyc_fail_log.txt", json_encode($response));
    echo json_encode($response);
    exit();
}

// Get POST data
$user_id = trim($_POST['user_id'] ?? '');
$type = trim($_POST['type'] ?? ''); // BVN or NIN
$number = trim($_POST['number'] ?? '');

// Validate inputs
if (empty($user_id)) {
    $response['status'] = 'fail';
    $response['msg'] = 'User ID is required.';
    echo json_encode($response);
    exit();
}

if (empty($type) || !in_array($type, ['NIN', 'BVN'])) {
    $response['status'] = 'fail';
    $response['msg'] = 'Invalid verification type. Must be NIN or BVN.';
    echo json_encode($response);
    exit();
}

if (empty($number)) {
    $response['status'] = 'fail';
    $response['msg'] = "$type is required.";
    echo json_encode($response);
    exit();
}

// Validate number (11 digits)
if (!preg_match('/^\d{11}$/', $number)) {
    $response['status'] = 'fail';
    $response['msg'] = "Invalid $type number. It must be exactly 11 digits.";
    echo json_encode($response);
    exit();
}

// Check if the number is already used by another user
$existingNumber = $controller->checkKYCNumber($type, $number, $user_id);
if ($existingNumber) {
    $response['status'] = 'fail';
    $response['msg'] = "This $type is already in use by another user.";
    echo json_encode($response);
    exit();
}

// Insert or update KYC details
$result = $controller->insertUserNewKyc($user_id, $type, $number);

// Log result
file_put_contents("kyc_log.txt", json_encode($result, JSON_UNESCAPED_SLASHES));
if ($result['status'] === "fail") {
    $response['status'] = 'fail';
    $response['msg'] = 'Failed to submit KYC details. User may have already submitted.';
    file_put_contents("kyc_fail_log.txt", json_encode($response));
    echo json_encode($response);
    exit();
}

$controller->getVirtualAccount($user_id);
$response = array('status' => 'success', 'msg' => 'KYC details submitted successfully.');
echo json_encode($response);
exit();
?>