<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

header('Content-Type: application/json');

$orderId   = (int)($_POST['order_id'] ?? 0);
$newIn     = trim((string)($_POST['check_in'] ?? ''));
$newOut    = trim((string)($_POST['check_out'] ?? ''));

if ($orderId <= 0 || $newIn === '' || $newOut === '') {
    echo json_encode([
        'ok' => false,
        'message' => 'Missing booking or dates'
    ]);
    exit;
}

$inTs  = strtotime($newIn);
$outTs = strtotime($newOut);

if (!$inTs || !$outTs || $outTs <= $inTs) {
    echo json_encode([
        'ok' => false,
        'message' => 'Invalid date range'
    ]);
    exit;
}

try {
    $stmt = $pdo->prepare("
        SELECT id, room_id, room_type_id
        FROM orders
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        echo json_encode([
            'ok' => false,
            'message' => 'Booking not found'
        ]);
        exit;
    }

    $roomId = (int)($order['room_id'] ?? 0);

    if ($roomId > 0) {
        $conflict = $pdo->prepare("
            SELECT COUNT(*)
            FROM orders
            WHERE room_id = :room_id
              AND id <> :order_id
              AND check_in < :check_out
              AND check_out > :check_in
        ");
        $conflict->execute([
            ':room_id'   => $roomId,
            ':order_id'  => $orderId,
            ':check_in'  => $newIn,
            ':check_out' => $newOut
        ]);

        if ((int)$conflict->fetchColumn() > 0) {
            echo json_encode([
                'ok' => false,
                'message' => 'This room has another booking in the resized date range'
            ]);
            exit;
        }
    }

    $pdo->beginTransaction();

    $upd = $pdo->prepare("
        UPDATE orders
        SET check_in = :check_in,
            check_out = :check_out
        WHERE id = :id
    ");
    $upd->execute([
        ':check_in'  => $newIn,
        ':check_out' => $newOut,
        ':id'        => $orderId
    ]);

    $pdo->prepare("DELETE FROM rel_orders_prices WHERE order_id = :order_id")
        ->execute([':order_id' => $orderId]);

    $nightDates = [];
    $cursor = $inTs;
    while ($cursor < $outTs) {
        $nightDates[] = date('Y-m-d', $cursor);
        $cursor = strtotime('+1 day', $cursor);
    }

    if (!empty($nightDates)) {
        $priceSource = $pdo->prepare("
            SELECT price
            FROM rel_orders_prices
            WHERE order_id = :order_id
            ORDER BY date ASC, id ASC
            LIMIT 1
        ");
        $priceSource->execute([':order_id' => $orderId]);
        $firstOldPrice = (float)($priceSource->fetchColumn() ?: 0);

        $insert = $pdo->prepare("
            INSERT INTO rel_orders_prices (order_id, date, room_id, price)
            VALUES (:order_id, :date, :room_id, :price)
        ");

        foreach ($nightDates as $nightDate) {
            $insert->execute([
                ':order_id' => $orderId,
                ':date'     => $nightDate,
                ':room_id'  => $roomId > 0 ? $roomId : null,
                ':price'    => $firstOldPrice
            ]);
        }
    }

    $pdo->commit();

    echo json_encode([
        'ok' => true,
        'check_in' => $newIn,
        'check_out' => $newOut
    ]);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    echo json_encode([
        'ok' => false,
        'message' => $e->getMessage()
    ]);
}