<?php 
//error_reporting(E_ALL);
//ini_set('display_errors',1);
$today = date('Y-m-d');

// Update remaining hours for ongoing tasks
$query = "
    SELECT id, remaing_hours, total_hours
    FROM cnc_machine_table
    WHERE DATE(start_date) < '$today'
      AND DATE(end_date) >= '$today'
      AND is_break = 1
";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $remaingHoursStr = $row['remaing_hours'];
    $totalHours = $row['total_hours'];

    $newRemaingStrParts = [];
    $pastHours = 0;

    $dayHourPairs = explode(',', $remaingHoursStr);
    foreach ($dayHourPairs as $pair) {
        if (strpos($pair, '=') !== false) {
            list($date, $hours) = explode('=', $pair);
            if (strtotime($date) < strtotime($today)) {
                $pastHours += floatval($hours);
            } else {
                $newRemaingStrParts[] = "$date=$hours";
            }
        }
    }

    $updatedRemaingStr = implode(',', $newRemaingStrParts);
    $updatedTotalHours = max(0, $totalHours - $pastHours);

    $updateSql = "
        UPDATE cnc_machine_table
        SET 
            remaing_hours = '$updatedRemaingStr',
            total_hours_update = '$updatedTotalHours', 
			setup_hours = 0,
            total_hours = '$updatedTotalHours'
        WHERE id = $id
    ";
    mysqli_query($conn, $updateSql);
}


?>
<?php 
//error_reporting(E_ALL);
//ini_set('display_errors',1);

$today = date('Y-m-d');

 $query = "
    SELECT 
        v.id,
        v.work_order_id,
        v.part_id,
        v.quantity,
        v.machine_id,
        v.is_break,
		v.start_date, 
        m.total_hours AS hours,
        m.end_date
    FROM vac_machine_table AS v
    LEFT JOIN manufacture_machine_table AS m
        ON v.work_order_id = m.work_order_id
       AND v.part_id = m.part_id
    WHERE v.finished = 0 AND v.is_break = 0
      AND v.start_date < '$today'
";

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

while ($row = mysqli_fetch_assoc($result)) {

    $vacId       = intval($row['id']);
    $workOrderId = intval($row['work_order_id']);
    $partId      = intval($row['part_id']);
    $machineId   = intval($row['machine_id']);

    $totalQty = floatval($row['quantity']);
    $hours    = floatval($row['hours']);

    $uph = ($hours > 0 && $totalQty > 0) ? ($totalQty / $hours) : 0;

    if ($uph <= 0 || $totalQty <= 0) {
        continue;
    }

    $okQtyQuery = "
        SELECT SUM(quantity) AS ok_qty
        FROM vac_part_count_log
        WHERE work_order_id = '$workOrderId'
          AND part_id = '$partId'
          AND partIds = '$partId'
          AND type = 'ok'
    ";

    $okQtyResult = mysqli_query($conn, $okQtyQuery);
    $okQtyRow    = mysqli_fetch_assoc($okQtyResult);

    $okQty = floatval($okQtyRow['ok_qty'] ?? 0);

    $remainingQty   = max(0, $totalQty - $okQty);
    $remainingHours = ($uph > 0) ? ($remainingQty / $uph) : 0;

    $finishedVal = ($remainingQty <= 0) ? 1 : 0;

    $updateSql = "
    UPDATE vac_machine_table
    SET
        total_hours_update = '$remainingHours',
        total_hours        = '$remainingHours',
        setup_hours        = 0,
        finished           = '$finishedVal'
    WHERE id = '$vacId'
    ";

    mysqli_query($conn, $updateSql);

    recalculateMachineDatesforvac($conn, $machineId);
}



?>


<?php
function recalculateMachineDatesforvac($conn, $machineId) {

    set_time_limit(300);

    // Load shifts grouped by day
    $shiftsByDay = [];
    $shiftResult = mysqli_query($conn, "SELECT * FROM working_hours");

    while ($row = mysqli_fetch_assoc($shiftResult)) {
        $day = (int)$row['day_shifts'];
        $shiftsByDay[$day][] = $row;
    }

    $currentDateStr = date('Y-m-d');

    // ------------------------------------------------
    // Load machine tasks
    // ------------------------------------------------
    $taskResult = mysqli_query($conn,
        "SELECT 
            v.id,
            v.work_order_id,
            v.part_id,
            v.is_break,
            v.is_breakdown_affected,
            v.breakdown_hours,
            v.start_date,
            v.total_hours_update AS hours_to_schedule,
            v.total_hours AS hours,
            v.setting_instruction
        FROM vac_machine_table v
        LEFT JOIN manufacture_machine_table m
            ON v.work_order_id = m.work_order_id
            AND v.part_id = m.part_id
        WHERE v.machine_id = $machineId
        AND (v.finished = 0 OR v.is_breakdown_affected = 1)
        ORDER BY v.priority"
    );

    $tasks = [];
    while ($row = mysqli_fetch_assoc($taskResult)) {
        $tasks[] = $row;
    }

    // Start scheduling from today
    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

    $previous_setting_instruction = null;

    foreach ($tasks as $task) {

        $taskId = $task['id'];

        // ------------------------------------------------
        // Check if production already started
        // ------------------------------------------------
        $checkResult = mysqli_query($conn, "
            SELECT 1 
            FROM vac_part_count_log 
            WHERE vac_machine_table_id = $taskId 
            LIMIT 1
        ");

        $productionStarted = mysqli_num_rows($checkResult) > 0;

        $total_hours = (float)$task['hours_to_schedule'];
        $setting_instruction = $task['setting_instruction'];
        $start_date = $task['start_date'];
        $is_break = (int)$task['is_break'];
        $breakdown_hours = (float)$task['breakdown_hours'];

        $setup_hours = 0.00;

        if ($is_break === 1) {

            $total_hours = (float)$task['hours'];
            $setup_hours = 0.00;

        } else {

            // If production already started → no setup
            if ($productionStarted) {

                $setup_hours = 0.00;

            } else {

                if ($previous_setting_instruction !== null) {

                    if (strcasecmp($previous_setting_instruction, $setting_instruction) === 0) {
                        $setup_hours = 1.00;
                    } else {
                        $setup_hours = 2.00;
                    }

                } else {
                    $setup_hours = 2.00;
                }

            }

            $total_hours = (float)($total_hours + $setup_hours + $breakdown_hours);
        }

        $hoursRemaining = $total_hours;

        $dateHoursMap = [];
        $taskStartTime = null;
        $taskEndTime = null;
        $firstShiftUsed = null;

        while ($hoursRemaining > 0) {

            $currentDate = date('Y-m-d', $currentDateTime);
            $dayOfWeek = date('w', $currentDateTime);

            if (!isset($shiftsByDay[$dayOfWeek])) {
                $currentDateTime = strtotime($currentDate . ' +1 day');
                continue;
            }

            foreach ($shiftsByDay[$dayOfWeek] as $shift) {

                $shiftStart = strtotime($currentDate . ' ' . $shift['start_time']);
                $shiftEnd   = strtotime($currentDate . ' ' . $shift['end_time']);
                $shiftName  = $shift['shift_name'];

                if ($shiftEnd <= $currentDateTime) continue;

                $actualStart = max($currentDateTime, $shiftStart);

                $availableSeconds = max(0, $shiftEnd - $actualStart);
                $availableHours = $availableSeconds / 3600;

                if ($availableHours <= 0) continue;

                $allocatable = min($hoursRemaining, $availableHours);

                if (!$taskStartTime) {
                    $taskStartTime = $actualStart;
                    $firstShiftUsed = $shiftName;
                }

                $taskEndTime = $actualStart + ($allocatable * 3600);

                $hoursRemaining -= $allocatable;

                $dateOnly = date('Y-m-d', $actualStart);

                if (!isset($dateHoursMap[$dateOnly])) {
                    $dateHoursMap[$dateOnly] = 0;
                }

                $dateHoursMap[$dateOnly] += $allocatable;

                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

            if ($hoursRemaining > 0) {
                $currentDateTime = strtotime(date('Y-m-d', $currentDateTime) . ' +1 day 00:00:00');
            }
        }

        // Format remaining hours string
        $remainingHoursStr = '';

        foreach ($dateHoursMap as $date => $hrs) {
            $remainingHoursStr .= $date . '=' . round($hrs, 2) . ',';
        }

        $remainingHoursStr = rtrim($remainingHoursStr, ',');

        $startStr = date('Y-m-d H:i:s', $taskStartTime);
        $endStr   = date('Y-m-d H:i:s', $taskEndTime);

        $query = "UPDATE vac_machine_table SET 
            start_date = '$startStr',
            end_date = '$endStr',
            shift_ids = '$firstShiftUsed',
            remaing_hours = '$remainingHoursStr',
            setup_hours = $setup_hours,
            total_hours = $total_hours
            WHERE id = {$task['id']}";

        mysqli_query($conn, $query);

        $previous_setting_instruction = $setting_instruction;
    }
}
?>
