<?php
require_once '../../config/headers.php';
require_once '../../config/database.php';
require_once '../../utils/response.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

$data = json_decode(file_get_contents("php://input"));

if (empty($data->email) || empty($data->password)) {
    sendResponse(400, 'error', 'Email and password are required');
}

$database = new Database();
$db = $database->getConnection();

try {
    $stmt = $db->prepare("SELECT id, email, password_hash, hotel_name, status FROM hotel_registrations WHERE email = :email LIMIT 1");
    $stmt->execute([':email' => $data->email]);
    
    if ($stmt->rowCount() > 0) {
        $hotel = $stmt->fetch();
        
        // Verify the hashed password
        if (password_verify($data->password, $hotel['password_hash'])) {
            
            // Block login if the status is NOT approved
            if ($hotel['status'] === 'pending') {
                sendResponse(403, 'error', 'Your hotel registration is still under review. Please wait for admin approval.');
            } elseif ($hotel['status'] === 'rejected') {
                sendResponse(403, 'error', 'Your hotel registration was rejected. Please contact support.');
            } elseif ($hotel['status'] !== 'approved') {
                sendResponse(403, 'error', 'Your account is not approved for login. Please contact support.');
            }

            // If we reach this point, the status is 'approved'
            // Remove password hash from the response data for security
            unset($hotel['password_hash']);
            
            sendResponse(200, 'success', 'Login successful', $hotel);
        } else {
            sendResponse(401, 'error', 'Invalid email or password');
        }
    } else {
        sendResponse(401, 'error', 'Invalid email or password');
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error occurred');
}
?>