<?php
/**
 * Auth API Endpoints
 * Handles OTP-based authentication
 */

require_once('../../otp_service.php');
require_once('../../auth_middleware.php');

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

$otpService = new OTPService();
$auth = new AuthMiddleware();

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    exit;
}

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Get request method and path
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = str_replace('/api/v1/auth/', '', $path);

// Handle requests
switch ($path) {
    case 'send-otp':
        if ($method !== 'POST') {
            http_response_code(405);
            die(json_encode(['error' => 'Method not allowed']));
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        $email = $data['email'] ?? '';
        
        list($success, $message, $otp) = $otpService->generateAndSendOTP($email);
        
        if ($success) {
            echo json_encode(['message' => $message]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $message]);
        }
        break;
        
    case 'verify-otp':
        if ($method !== 'POST') {
            http_response_code(405);
            die(json_encode(['error' => 'Method not allowed']));
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        $email = $data['email'] ?? '';
        $otp = $data['otp'] ?? '';
        
        list($success, $message, $token) = $otpService->verifyOTP($email, $otp);
        
        if ($success) {
            echo json_encode([
                'message' => $message,
                'token' => $token
            ]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => $message]);
        }
        break;
        
    case 'me':
        if ($method !== 'GET') {
            http_response_code(405);
            die(json_encode(['error' => 'Method not allowed']));
        }
        
        $auth->requireAuth();
        $user = $auth->getAuthenticatedUser();
        
        // Remove sensitive data
        unset($user['password']);
        unset($user['facebook_access_token']);
        
        echo json_encode(['user' => $user]);
        break;
        
    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
        break;
} 