<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$id = (int)($d['id'] ?? 0);

if ($method === 'GET') {
    require_permission('properties.view');
    if ($id) {
        $s = db()->prepare('SELECT rt.*, p.name AS property_name,
            (SELECT COUNT(*) FROM rooms WHERE room_type_id = rt.id AND deleted_at IS NULL) AS room_count
            FROM room_types rt JOIN properties p ON p.id = rt.property_id WHERE rt.id = ?');
        $s->execute([$id]);
        $rt = $s->fetch();
        if (!$rt) json_error('Not found', 404);
        json_ok($rt);
    }
    $where = ['1=1']; $params = [];
    if (!empty($d['property_id'])) { $where[] = 'rt.property_id = ?'; $params[] = (int)$d['property_id']; }
    if (isset($d['is_active'])) { $where[] = 'rt.is_active = ?'; $params[] = (int)$d['is_active']; }
    $sql = "SELECT rt.id, rt.property_id, rt.code, rt.name, rt.bed_type, rt.max_occupancy,
                   rt.base_rate, rt.weekend_rate, rt.is_active, rt.sort_order,
                   (SELECT COUNT(*) FROM rooms WHERE room_type_id = rt.id AND deleted_at IS NULL) AS room_count,
                   p.name AS property_name
            FROM room_types rt
            JOIN properties p ON p.id = rt.property_id
            WHERE " . implode(' AND ', $where) . "
            ORDER BY rt.sort_order, rt.name";
    $s = db()->prepare($sql); $s->execute($params);
    json_ok($s->fetchAll());
}

csrf_check();

if ($method === 'POST') {
    require_permission('properties.manage');
    $errors = v_required($d, ['property_id', 'code', 'name', 'base_rate']);
    if ($errors) json_error('Validation failed', 422, $errors);
    $stmt = db()->prepare('INSERT INTO room_types
        (property_id, code, name, description, bed_type, max_occupancy, base_rate, weekend_rate, size_sqm, amenities, sort_order, is_active)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
    try {
        $stmt->execute([
            (int)$d['property_id'],
            v_str($d, 'code', 20),
            v_str($d, 'name', 100),
            $d['description'] ?? null,
            $d['bed_type'] ?? 'double',
            max(1, (int)($d['max_occupancy'] ?? 2)),
            (float)$d['base_rate'],
            !empty($d['weekend_rate']) ? (float)$d['weekend_rate'] : null,
            !empty($d['size_sqm']) ? (int)$d['size_sqm'] : null,
            $d['amenities'] ?? null,
            (int)($d['sort_order'] ?? 0),
            (int)($d['is_active'] ?? 1),
        ]);
    } catch (PDOException $e) {
        if ($e->getCode() === '23000') json_error('Code already used for this property', 409);
        throw $e;
    }
    audit_log('room_type.create', 'room_type', (int)db()->lastInsertId());
    json_ok(['id' => (int)db()->lastInsertId()], 'Room type created');
}

if ($method === 'PUT' || $method === 'PATCH') {
    require_permission('properties.manage');
    if (!$id) json_error('id required', 422);
    $allowed = ['code','name','description','bed_type','max_occupancy','base_rate','weekend_rate','size_sqm','amenities','sort_order','is_active'];
    $sets = []; $params = [];
    foreach ($allowed as $f) if (array_key_exists($f, $d)) { $sets[] = "$f = ?"; $params[] = $d[$f]; }
    if (!$sets) json_error('No fields to update', 422);
    $params[] = $id;
    $stmt = db()->prepare('UPDATE room_types SET ' . implode(', ', $sets) . ' WHERE id = ?');
    $stmt->execute($params);
    audit_log('room_type.update', 'room_type', $id);
    json_ok([], 'Updated');
}

if ($method === 'DELETE') {
    require_permission('properties.manage');
    if (!$id) json_error('id required', 422);
    $count = db()->prepare('SELECT COUNT(*) FROM rooms WHERE room_type_id = ? AND deleted_at IS NULL');
    $count->execute([$id]);
    if ((int)$count->fetchColumn() > 0) json_error('Cannot delete — rooms exist under this type', 409);
    db()->prepare('DELETE FROM room_types WHERE id = ?')->execute([$id]);
    audit_log('room_type.delete', 'room_type', $id);
    json_ok([], 'Deleted');
}

json_error('Method not allowed', 405);
