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

if ($method === 'GET') {
    require_permission('calendar.view');
    $from = !empty($d['from']) ? v_date($d['from'], 'from') : date('Y-m-d', strtotime('-7 days'));
    $to = !empty($d['to']) ? v_date($d['to'], 'to') : date('Y-m-d', strtotime('+60 days'));
    $propertyId = !empty($d['property_id']) ? (int)$d['property_id'] : null;

    $bookings = [];
    $sql = "SELECT b.id, b.reference, b.property_id, p.name AS property_name, b.guest_name, b.check_in AS start_date, b.check_out AS end_date, b.status, b.total, b.currency, 'booking' AS block_type
            FROM bookings b JOIN properties p ON p.id=b.property_id
            WHERE b.status NOT IN ('cancelled','no_show') AND b.check_out >= ? AND b.check_in <= ?";
    $params = [$from, $to];
    if ($propertyId) { $sql .= ' AND b.property_id=?'; $params[] = $propertyId; }
    $sql .= ' ORDER BY b.check_in';
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $bookings = $stmt->fetchAll();

    $blocks = [];
    if (function_exists('hv4_table_exists') && hv4_table_exists('calendar_blocks')) {
        $bsql = 'SELECT cb.*, p.name AS property_name FROM calendar_blocks cb JOIN properties p ON p.id=cb.property_id WHERE cb.end_date >= ? AND cb.start_date <= ?';
        $bparams = [$from, $to];
        if ($propertyId) { $bsql .= ' AND cb.property_id=?'; $bparams[] = $propertyId; }
        $bstmt = db()->prepare($bsql);
        $bstmt->execute($bparams);
        $blocks = $bstmt->fetchAll();
    }

    $properties = db()->query('SELECT id, name, status FROM properties WHERE deleted_at IS NULL ORDER BY name')->fetchAll();
    json_ok(['from' => $from, 'to' => $to, 'bookings' => $bookings, 'blocks' => $blocks, 'properties' => $properties]);
}

csrf_check();
require_permission('calendar.manage');

if ($method === 'POST') {
    if (!hv4_table_exists('calendar_blocks')) json_error('Run V4 migration first', 503);
    $err = v_required($d, ['property_id', 'start_date', 'end_date', 'block_type']);
    if ($err) json_error('Validation failed', 422, $err);
    db()->prepare('INSERT INTO calendar_blocks (property_id, block_type, title, start_date, end_date, color) VALUES (?,?,?,?,?,?)')
        ->execute([
            (int)$d['property_id'],
            v_enum($d['block_type'], ['maintenance', 'cleaning', 'owner_block', 'ota_block'], 'block_type'),
            v_str($d, 'title', 190) ?: 'Block',
            v_date($d['start_date'], 'start_date'),
            v_date($d['end_date'], 'end_date'),
            v_str($d, 'color', 20) ?: '#f59e0b',
        ]);
    $id = (int)db()->lastInsertId();
    if (function_exists('hv4_emit_event')) hv4_emit_event('calendar.block.created', ['id' => $id], 'calendar', $id);
    json_ok(['id' => $id], 'Block created');
}

if ($method === 'PUT' && !empty($d['booking_id'])) {
    require_permission('bookings.manage');
    $bid = (int)$d['booking_id'];
    if (empty($d['check_in']) || empty($d['check_out'])) json_error('Dates required', 422);
    $in = v_date($d['check_in'], 'check_in');
    $out = v_date($d['check_out'], 'check_out');
    $pdo = db();
    $pdo->beginTransaction();
    try {
        $b = $pdo->prepare('SELECT property_id FROM bookings WHERE id=? FOR UPDATE');
        $b->execute([$bid]);
        $row = $b->fetch();
        if (!$row) { $pdo->rollBack(); json_error('Not found', 404); }
        $free = function_exists('hv4_availability_is_free')
            ? hv4_availability_is_free($pdo, (int)$row['property_id'], $in, $out, $bid)
            : true;
        if (!$free) {
            $pdo->rollBack();
            json_error('Conflict: dates not available', 409);
        }
        $pdo->prepare('UPDATE bookings SET check_in=?, check_out=? WHERE id=?')->execute([$in, $out, $bid]);
        if (function_exists('hv4_sync_calendar_block')) hv4_sync_calendar_block($pdo, $bid);
        $pdo->commit();
        if (function_exists('hv4_emit_event')) hv4_emit_event('booking.updated', ['id' => $bid], 'booking', $bid);
        json_ok([], 'Booking moved');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        json_error('Update failed', 500);
    }
}

json_error('Method not allowed', 405);
