<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors directly
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// Set proper headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Function to send JSON response
function sendJsonResponse($success, $message, $data = null) {
    $response = [
        'success' => $success,
        'message' => $message
    ];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

try {
    // Check if required files exist
    if (!file_exists('config/auth_config.php')) {
        throw new Exception('Configuration file not found');
    }
    if (!file_exists('onesignal-api.php')) {
        throw new Exception('OneSignal API file not found');
    }

    require_once('config/auth_config.php');
    require_once('onesignal-api.php');

    // Get request data
    $rawData = file_get_contents('php://input');
    $data = json_decode($rawData, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON data: ' . json_last_error_msg());
    }

    $action = $_GET['action'] ?? '';
    
    // Log request for debugging
    error_log("Request received - Action: $action, Data: " . print_r($data, true));

    switch ($action) {
        case 'send-otp':
            $email = $data['email'] ?? '';
            if (empty($email)) {
                throw new Exception('Email is required');
            }
            
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Invalid email format');
            }
            
            list($success, $message, $otp) = onesignal_sendOTP($email);
            sendJsonResponse($success, $message, ['otp' => $otp]);
            break;
            
        case 'verify-otp':
            $email = $data['email'] ?? '';
            $otp = $data['otp'] ?? '';
            
            if (empty($email) || empty($otp)) {
                throw new Exception('Email and OTP are required');
            }
            
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('Invalid email format');
            }
            
            list($success, $message) = onesignal_verifyOTP($email, $otp);
            
            if ($success) {
                // Generate token after successful verification
                $user = [
                    'num' => 1, // You might want to get this from your database
                    'email' => $email
                ];
                $token = onesignal_generateToken($user);
                sendJsonResponse(true, $message, ['token' => $token]);
            } else {
                sendJsonResponse(false, $message, ['token' => null]);
            }
            break;
            
        default:
            throw new Exception('Invalid action: ' . $action);
    }
} catch (Exception $e) {
    error_log("Exception in test-otp.php: " . $e->getMessage());
    http_response_code(400);
    sendJsonResponse(false, $e->getMessage(), null);
} catch (Error $e) {
    error_log("Error in test-otp.php: " . $e->getMessage() . "\n" . $e->getTraceAsString());
    http_response_code(500);
    sendJsonResponse(false, 'Internal server error: ' . $e->getMessage(), null);
} 