<?php

require __DIR__ . '/../tests/unit/SegmentSeatAvailabilityBootstrap.php';

use App\Libraries\SegmentSeatAvailability;

$stops = SegmentSeatAvailability::parseStoppage('32,41,43,54,65,66,67,77,78,90,55');

$request = ['pick' => '54', 'drop' => '43', 'stoppage' => '54,43'];

$bookings = [
    ['label' => 'Ras→Tor seats 2,3 (404)', 'pick' => '54', 'drop' => '43', 'stoppage' => '54,43', 'seats' => '2,3'],
    ['label' => 'Ras→Tor seats 11,12 (404)', 'pick' => '54', 'drop' => '43', 'stoppage' => '54,43', 'seats' => '11,12'],
    ['label' => 'Cairo→Sharm seats 5,6 (237)', 'pick' => '32', 'drop' => '41', 'stoppage' => '32,43,54,66,67,78,41', 'seats' => '5,6'],
    ['label' => 'Sharm→Cairo seats 2,3 (14641 reversed)', 'pick' => '41', 'drop' => '32', 'stoppage' => '32,43,54,66,67,78,41', 'seats' => '2,3'],
];

echo "Trip 75 stops: " . implode(' → ', $stops) . "\n\n";
echo "Search segment: Ras Sudr (54) → El Tor (43)\n\n";

$blocked = [];
foreach ($bookings as $b) {
    $overlap = SegmentSeatAvailability::segmentsOverlapWithPath(
        $stops,
        $request['pick'],
        $request['drop'],
        $request['stoppage'],
        $b['pick'],
        $b['drop'],
        $b['stoppage']
    );
    $plain = SegmentSeatAvailability::segmentsOverlap(
        $stops,
        $request['pick'],
        $request['drop'],
        $b['pick'],
        $b['drop']
    );
    echo sprintf(
        "%-40s path=%s  plain=%s  seats=%s\n",
        $b['label'],
        $overlap ? 'BLOCK' : 'free ',
        $plain ? 'BLOCK' : 'free ',
        $b['seats']
    );
    if ($overlap) {
        foreach (explode(',', $b['seats']) as $s) {
            $blocked[$s] = true;
        }
    }
}

echo "\nExpected blocked for Ras→Tor search: 2,3,5,6,11,12\n";
echo "Computed blocked: " . implode(',', array_keys($blocked)) . "\n";

$expected = ['2', '3', '5', '6', '11', '12'];
$missing = array_diff($expected, array_keys($blocked));
$extra = array_diff(array_keys($blocked), $expected);

if ($missing) {
    echo "MISSING from blocked: " . implode(',', $missing) . "\n";
}
if ($extra) {
    echo "EXTRA blocked: " . implode(',', $extra) . "\n";
}
if (!$missing && !$extra) {
    echo "OK — overlap logic matches expectation.\n";
}
