<?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";

/* ---------- AUTH CHECK ---------- */
if (empty($_SESSION['hotel_id'])) {
    http_response_code(401);
    echo json_encode(["status"=>false,"message"=>"Unauthorized. Please login."]);
    exit;
}

$hotel_id = (int) $_SESSION['hotel_id'];

/* ---------- REQUIRED TEXT FIELDS ---------- */
$required = ['room_name','room_type','price_per_night','max_guests','description'];

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

/* ---------- REQUIRED FEATURES ---------- */
if (empty($_POST['features']) || !is_array($_POST['features'])) {
    http_response_code(422);
    echo json_encode(["status"=>false,"message"=>"At least one feature is required"]);
    exit;
}

/* ---------- REQUIRED IMAGES (EXACTLY 2) ---------- */
if (empty($_FILES['images']['name'][0]) || count($_FILES['images']['name']) != 2) {
    http_response_code(422);
    echo json_encode(["status"=>false,"message"=>"Exactly 2 room images are required"]);
    exit;
}

/* ---------- SANITIZE INPUTS ---------- */
$room_name = trim($_POST['room_name']);
$room_type = trim($_POST['room_type']);
$price = floatval($_POST['price_per_night']);
$max_guests = (int) $_POST['max_guests'];
$description = trim($_POST['description']);

try {
    $pdo->beginTransaction();

    /* ---------- INSERT ROOM ---------- */
    $stmt = $pdo->prepare("
        INSERT INTO hotel_rooms 
        (hotel_id, room_name, room_type, price_per_night, max_guests, description)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $hotel_id,
        $room_name,
        $room_type,
        $price,
        $max_guests,
        $description
    ]);

    $room_id = $pdo->lastInsertId();

    /* ---------- INSERT FEATURES ---------- */
    $featStmt = $pdo->prepare("INSERT INTO room_features (room_id, feature) VALUES (?, ?)");
    foreach ($_POST['features'] as $feature) {
        $featStmt->execute([$room_id, trim($feature)]);
    }

    /* ---------- IMAGE UPLOAD ---------- */
    $uploadDir = __DIR__ . "/images/rooms/";
    $allowedExt = ['jpg','jpeg','png','webp'];
    $imgStmt = $pdo->prepare("INSERT INTO hotel_room_images (room_id, image_path) VALUES (?, ?)");

    foreach ($_FILES['images']['tmp_name'] as $key => $tmp) {
        $ext = strtolower(pathinfo($_FILES['images']['name'][$key], PATHINFO_EXTENSION));

        if (!in_array($ext, $allowedExt)) {
            throw new Exception("Invalid image type");
        }

        $fileName = uniqid("room_", true) . "." . $ext;
        $path = $uploadDir . $fileName;

        if (!move_uploaded_file($tmp, $path)) {
            throw new Exception("Image upload failed");
        }

        $imgStmt->execute([$room_id, "/images/rooms/".$fileName]);
    }

    $pdo->commit();

    echo json_encode([
        "status" => true,
        "message" => "Room added successfully",
        "room_id" => $room_id
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode([
        "status" => false,
        "message" => $e->getMessage()
    ]);
}
