<?php
/**
 * OTP API Handler
 * Handles OTP generation, sending, and verification
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/otp-helper.php';
require_once __DIR__ . '/../config/mailer.php';

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

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$action = sanitize($action);

try {
    switch ($action) {
        case 'send_otp':
            sendOTPHandler();
            break;

        case 'verify_otp':
            verifyOTPHandler();
            break;

        case 'resend_otp':
            resendOTPHandler();
            break;

        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
    error_log($e->getMessage());
}

/**
 * Send OTP handler
 */
function sendOTPHandler() {
    global $conn;

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $email = trim((string)($_POST['email'] ?? ''));
    $firstName = trim((string)($_POST['first_name'] ?? 'User'));
    $purpose = trim((string)($_POST['purpose'] ?? 'verification'));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        return;
    }

    if (!in_array($purpose, ['verification', 'password_reset'])) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid purpose']);
        return;
    }

    try {
        // Generate OTP
        $otp = generateOTP(6);

        // Store OTP in database
        if (!storeOTP($email, $otp, $purpose)) {
            throw new Exception('Failed to store OTP');
        }

        // Send OTP email
        if (!sendOTPEmail($email, $firstName, $otp, $purpose)) {
            throw new Exception('Failed to send OTP email');
        }

        echo json_encode([
            'success' => true,
            'message' => 'OTP sent successfully to ' . htmlspecialchars($email),
            'email' => htmlspecialchars($email),
            'data' => [
                'otp_sent_at' => date('Y-m-d H:i:s'),
                'expires_in' => 600 // 10 minutes in seconds
            ]
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to send OTP: ' . $e->getMessage()]);
        error_log('Send OTP Error: ' . $e->getMessage());
    }
}

/**
 * Verify OTP handler
 */
function verifyOTPHandler() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $email = trim((string)($_POST['email'] ?? ''));
    $otp = trim((string)($_POST['otp'] ?? ''));
    $purpose = trim((string)($_POST['purpose'] ?? 'verification'));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        return;
    }

    if ($otp === '' || strlen($otp) !== 6 || !ctype_digit($otp)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid OTP format']);
        return;
    }

    $result = verifyOTP($email, $otp, $purpose);
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'message' => $result['message'],
            'data' => ['verified_at' => date('Y-m-d H:i:s')]
        ]);
    } else {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => $result['message']]);
    }
}

/**
 * Resend OTP handler
 */
function resendOTPHandler() {
    global $conn;

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $email = trim((string)($_POST['email'] ?? ''));
    $firstName = trim((string)($_POST['first_name'] ?? 'User'));
    $purpose = trim((string)($_POST['purpose'] ?? 'verification'));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        return;
    }

    try {
        // Generate new OTP
        $otp = generateOTP(6);

        // Store new OTP (replaces old one)
        if (!storeOTP($email, $otp, $purpose)) {
            throw new Exception('Failed to store OTP');
        }

        // Send OTP email
        if (!sendOTPEmail($email, $firstName, $otp, $purpose)) {
            throw new Exception('Failed to send OTP email');
        }

        echo json_encode([
            'success' => true,
            'message' => 'OTP resent successfully',
            'data' => ['resent_at' => date('Y-m-d H:i:s')]
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to resend OTP']);
        error_log('Resend OTP Error: ' . $e->getMessage());
    }
}

?>
