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

require_once "config.php";

/* ---------- REQUIRED TEXT FIELDS ---------- */
$required = ['hotel_name','email','phone','password','location'];

foreach ($required as $field) {
    if (empty($_POST[$field])) {
        http_response_code(422);
        echo json_encode([
            "status" => false,
            "message" => "$field is required"
        ]);
        exit;
    }
}

/* ---------- SANITIZE INPUTS ---------- */
$hotel_name  = trim($_POST['hotel_name']);
$email       = strtolower(trim($_POST['email']));
$phone       = trim($_POST['phone']);
$password    = password_hash($_POST['password'], PASSWORD_BCRYPT);
$location    = trim($_POST['location']);
$description = $_POST['description'] ?? '';
$hotel_id    = random_int(100000, 999999);
$status = "active";

/* ---------- CHECK DUPLICATE EMAIL ---------- */
$check = $pdo->prepare("SELECT id FROM hotels WHERE email = ?");
$check->execute([$email]);

if ($check->rowCount() > 0) {
    http_response_code(409);
    echo json_encode([
        "status" => false,
        "message" => "Email already registered"
    ]);
    exit;
}

/* ---------- HANDLE LOGO UPLOAD ---------- */
$logoPath = null;

if (!empty($_FILES['logo']['name'])) {

    $uploadDir = __DIR__ . "/images/hotels/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $allowedExt = ['jpg','jpeg','png','webp'];
    $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedExt)) {
        http_response_code(422);
        echo json_encode([
            "status" => false,
            "message" => "Invalid logo image format"
        ]);
        exit;
    }

    $fileName = uniqid("hotel_logo_", true) . "." . $ext;
    $fullPath = $uploadDir . $fileName;

    if (!move_uploaded_file($_FILES['logo']['tmp_name'], $fullPath)) {
        http_response_code(500);
        echo json_encode([
            "status" => false,
            "message" => "Failed to upload logo"
        ]);
        exit;
    }

    $logoPath = "/images/hotels/" . $fileName;
}

/* ---------- INSERT HOTEL ---------- */
try {
    $stmt = $pdo->prepare("
        INSERT INTO hotels 
        (hotel_id, hotel_name, email, phone, password, location, description, logo, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");

    $stmt->execute([
        $hotel_id,
        $hotel_name,
        $email,
        $phone,
        $password,
        $location,
        $description,
        $logoPath,
        $status
    ]);

    echo json_encode([
        "status" => true,
        "message" => "Hotel account created successfully"
    ]);

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