<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
session_start();
require_once "config.php";

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

if (empty($data['email']) || empty($data['password'])) {
    http_response_code(422);
    echo json_encode(["status"=>false,"message"=>"Email and password required"]);
    exit;
}

$email = strtolower(trim($data['email']));
$password = $data['password'];

try {
    $stmt = $pdo->prepare("SELECT hotel_id, hotel_name, password, status FROM hotels WHERE email = ?");
    $stmt->execute([$email]);
    $hotel = $stmt->fetch();

    if (!$hotel || !password_verify($password, $hotel['password'])) {
        http_response_code(401);
        echo json_encode(["status"=>false,"message"=>"Invalid login credentials"]);
        exit;
    }

    if ($hotel['status'] !== 'active') {
        http_response_code(403);
        echo json_encode(["status"=>false,"message"=>"Account not active"]);
        exit;
    }

    // Create session
    $_SESSION['hotel_id'] = $hotel['hotel_id'];
    $_SESSION['hotel_name'] = $hotel['hotel_name'];

    echo json_encode([
        "status" => true,
        "message" => "Login successful",
        "hotel" => [
            "id" => $hotel['hotel_id'],
            "name" => $hotel['hotel_name']
        ]
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["status"=>false,"message"=>"Server error"]);
}
