<?php
/**
 * IBVTE OTP Handler API
 * Handles OTP generation and verification requests
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../middleware.php';

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

// Ensure session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Send OTP using Fast2SMS API
 */
function sendOTP($phone, $otp) {
    // For development, just log it
    if (ENVIRONMENT === 'development' || !SMS_ENABLED) {
        logError('SMS OTP (Development)', ['phone' => $phone, 'otp' => $otp]);
        $_SESSION['last_otp'] = $otp;
        $_SESSION['otp_expiry'] = time() + (OTP_EXPIRY_MINUTES * 60);
        return true;
    }
    
    $apiKey = SMS_API_KEY;
    if (empty($apiKey)) {
        logError('SMS Error: No API key configured');
        return false;
    }
    
    $fields = array(
        "variables_values" => "$otp",
        "route" => "otp",
        "numbers" => "$phone",
    );

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://www.fast2sms.com/dev/bulkV2",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($fields),
        CURLOPT_HTTPHEADER => array(
            "authorization: $apiKey",
            "accept: */*",
            "cache-control: no-cache",
            "content-type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) {
        logError('SMS Error', ['error' => $err]);
        return false;
    } else {
        $res = json_decode($response, true);
        if(isset($res['return']) && $res['return'] == true) {
            $_SESSION['last_otp'] = $otp;
            $_SESSION['otp_expiry'] = time() + (OTP_EXPIRY_MINUTES * 60);
            return true;
        }
        logError('SMS API Error', ['response' => $response]);
        return false;
    }
}

// Handle OTP Request
if (isset($_POST['action']) && $_POST['action'] == 'request_otp') {
    $otp = rand(100000, 999999);
    $phone = "9627769817"; // Default contact for IBVTE or dynamic phone from college profile
    
    if (sendOTP($phone, $otp)) {
        echo json_encode(['status' => 'success', 'message' => 'OTP sent successfully to registered mobile.', 'debug_otp' => $otp]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to send OTP. Try again.']);
    }
    exit;
}

// Verify OTP
if (isset($_POST['action']) && $_POST['action'] == 'verify_otp') {
    $user_otp = $_POST['otp'] ?? '';
    
    if ($user_otp == $_SESSION['last_otp'] && time() <= $_SESSION['otp_expiry']) {
        $_SESSION['otp_verified'] = true;
        echo json_encode(['status' => 'success', 'message' => 'OTP Verified. Saving changes...']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid or expired OTP.']);
    }
    exit;
}
?>
