<?php

date_default_timezone_set('Asia/Kolkata');

$output = '';
$todayStart = strtotime(date('Y-m-d') . ' 00:00:00');
$todayEnd = strtotime(date('Y-m-d') . ' 23:59:59');

function getFreshOrdersData($conn, $todayStart, $todayEnd) {
    $orders = [];
    $query = "SELECT TIME(start_date) AS start_time, DATE(start_date) AS start_date, part_id, cycle, table_id, total_hours 
              FROM cnc_machine_table 
              WHERE machine_id = 8";

    $result = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        $startTimestamp = strtotime($row['start_date'] . ' ' . $row['start_time']);
        $hours = floor($row['total_hours']);
        $minutes = ($row['total_hours'] - $hours) * 60;
        $endTimestamp = strtotime("+$hours hours +$minutes minutes", $startTimestamp);

        if ($endTimestamp > $todayEnd) $endTimestamp = $todayEnd;

        if ($endTimestamp >= $todayStart && $startTimestamp <= $todayEnd) {
            $orders[$row['part_id']] = [
                'start' => date('H:i', max($startTimestamp, $todayStart)),
                'end' => date('H:i', $endTimestamp),
                'cycle' => (int)$row['cycle'],
                'table' => (int)$row['table_id']
            ];
        }
    }
    return $orders;
}

function toMinutes($time) {
    [$h, $m] = explode(':', $time);
    return $h * 60 + $m;
}

function processOrders($orders) {
    $table1 = [];
    $table2 = [];
    $orderDurations = [];

    foreach ($orders as $key => $order) {
        $startMin = toMinutes($order['start']);
        $endMin = toMinutes($order['end']);
        $durationMin = $endMin - $startMin;
        $durationHours = $durationMin / 60;
        $cycles = $order['cycle'] > 0 ? floor($durationMin / $order['cycle']) : 0;

        $orderDurations[$key] = [
            'hours' => $durationHours,
            'cycles' => $cycles,
            'durationMin' => $durationMin,
            'cycleTime' => $order['cycle'],
        ];

        $order['startMin'] = $startMin;
        $order['endMin'] = $endMin;

        if ($order['table'] == 1) $table1[$key] = $order;
        else $table2[$key] = $order;
    }

    return ['table1' => $table1, 'table2' => $table2, 'orderDurations' => $orderDurations];
}

function findOverlaps($table1, $table2) {
    $overlaps = [];
    foreach ($table1 as $key1 => $o1) {
        foreach ($table2 as $key2 => $o2) {
            $start = max($o1['startMin'], $o2['startMin']);
            $end = min($o1['endMin'], $o2['endMin']);
            if ($start < $end) {
                $overlaps[] = [
                    'order1' => $key1,
                    'order2' => $key2,
                    'start' => sprintf("%02d:%02d", intdiv($start, 60), $start % 60),
                    'end' => sprintf("%02d:%02d", intdiv($end, 60), $end % 60),
                    'duration' => ($end - $start) / 60
                ];
            }
        }
    }
    return $overlaps;
}

// Initial display of order durations
$orders = getFreshOrdersData($conn, $todayStart, $todayEnd);
$processedData = processOrders($orders);
$orderDurations = $processedData['orderDurations'];

$output .= "Order Durations and Number of Cycles:<br>";
foreach ($orderDurations as $key => $data) {
    $output .= "Order $key: {$data['hours']} hours, {$data['cycles']} cycles<br>";
}

$output .= "<br>Overlapping Periods (Table 1 vs Table 2):<br>";

// Find all overlaps first
$overlaps = findOverlaps($processedData['table1'], $processedData['table2']);

foreach ($overlaps as $overlap) {
    // Get fresh data for each overlap processing
    $freshOrders = getFreshOrdersData($conn, $todayStart, $todayEnd);
    $freshProcessedData = processOrders($freshOrders);
    $freshOrderDurations = $freshProcessedData['orderDurations'];
    
    $order1Key = $overlap['order1'];
    $order2Key = $overlap['order2'];

    $output .= "Order {$order1Key} (Table 1) overlaps with Order {$order2Key} (Table 2) from {$overlap['start']} to {$overlap['end']} ({$overlap['duration']} hours)<br>";

    $checkQuery = "SELECT * FROM processed_overlaps 
                   WHERE order1_id = $order1Key 
                   AND order2_id = $order2Key 
                   AND date = CURDATE()";
    $checkResult = mysqli_query($conn, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        $output .= "<i>This overlap was already processed earlier.</i><br><br>";
        continue;
    }

    $order1_cycles = $freshOrderDurations[$order1Key]['cycles'];
    $order1_duration = $freshOrderDurations[$order1Key]['cycleTime'];

    $order2_cycles = $freshOrderDurations[$order2Key]['cycles'];
    $order2_duration = $freshOrderDurations[$order2Key]['cycleTime'];

    $output .= "<br><b>🔄 Alternating Schedule:</b><br>";

    $result = calculateAlternatingSchedule(
        $conn,
        $order1Key, $order1_cycles, $order1_duration,
        $order2Key, $order2_cycles, $order2_duration,
        $output
    );

    $insertQuery = "INSERT INTO processed_overlaps 
                    (order1_id, order2_id, date, alternating_cycles, total_time_minutes) 
                    VALUES 
                    ($order1Key, $order2Key, CURDATE(), {$result['alternating_cycles']}, {$result['total_time']})";
    mysqli_query($conn, $insertQuery);
}

echo $output;

function calculateAlternatingSchedule($conn, $order1Key, $order1_cycles, $order1_duration,
                                      $order2Key, $order2_cycles, $order2_duration, &$output) {

    $output .= "🔧 Input:<br>";
    $output .= "Order {$order1Key}: {$order1_cycles} cycles × {$order1_duration} min<br>";
    $output .= "Order {$order2Key}: {$order2_cycles} cycles × {$order2_duration} min<br><br>";

    $alternating_cycles = min($order1_cycles, $order2_cycles);
    $time_1_in_alt = $alternating_cycles * $order1_duration;
    $time_2_in_alt = $alternating_cycles * $order2_duration;
    $total_alt_time = $time_1_in_alt + $time_2_in_alt;

    $finished_order = ($order1_cycles < $order2_cycles) ? $order1Key : $order2Key;

    $output .= "Step 1: Alternate until Order {$finished_order} finishes:<br>";
    $output .= "- {$alternating_cycles} cycles of {$order1Key} = {$time_1_in_alt} min<br>";
    $output .= "- {$alternating_cycles} cycles of {$order2Key} = {$time_2_in_alt} min<br>";
    $output .= "→ Total alternating time = {$total_alt_time} min (" . round($total_alt_time / 60, 2) . " hr)<br>";

    $updateQuery = "UPDATE cnc_machine_table 
                    SET total_hours = " . round($total_alt_time / 60, 2) . " 
                    WHERE part_id = $finished_order AND machine_id = 8";
    $output .= $updateQuery . "<br>";
    mysqli_query($conn, $updateQuery);

    $remaining1 = $order1_cycles - $alternating_cycles;
    $remaining2 = $order2_cycles - $alternating_cycles;

    $time_remaining1 = $remaining1 * $order1_duration;
    $time_remaining2 = $remaining2 * $order2_duration;

    $total_time = $total_alt_time + $time_remaining1 + $time_remaining2;

    if ($remaining1 > 0) {
        $updateQuery = "UPDATE cnc_machine_table 
                        SET total_hours = " . round($total_time / 60, 2) . " 
                        WHERE part_id = $order1Key AND machine_id = 8";
        $output .= "Remaining {$order1Key}: {$remaining1} × {$order1_duration} = {$time_remaining1} min (" . round($time_remaining1 / 60, 2) . " hr)<br>";
        $output .= $updateQuery . "<br>";
        mysqli_query($conn, $updateQuery);
    }

    if ($remaining2 > 0) {
        $updateQuery = "UPDATE cnc_machine_table 
                        SET total_hours = " . round($total_time / 60, 2) . " 
                        WHERE part_id = $order2Key AND machine_id = 8";
        $output .= "Remaining {$order2Key}: {$remaining2} × {$order2_duration} = {$time_remaining2} min (" . round($time_remaining2 / 60, 2) . " hr)<br>";
        $output .= $updateQuery . "<br>";
        mysqli_query($conn, $updateQuery);
    }

    $output .= "✅ Final makespan: {$total_alt_time} + {$time_remaining1} + {$time_remaining2} = {$total_time} min<br>";
    $output .= "Updated total hours for remaining order: " . round($total_time / 60, 2) . " hr<br><br>";

    return [
        'alternating_cycles' => $alternating_cycles,
        'total_time' => $total_time,
        'remaining1' => $remaining1,
        'remaining2' => $remaining2
    ];
}

?>