<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$repair_data_res = $db->query("pump_repair", "SELECT * FROM pump_repair WHERE record_id = '{$_GET['record_id']}'");
// echo "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'";
$repair_data = $repair_data_res->fetch_assoc();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$repair_data['installation_id']}'");
// echo "SELECT * FROM pump_repair WHERE record_id = '{$repair_data['installation_id']}'";
$jobcard_data = $jobcard_data_res->fetch_assoc();

$jobcard_history_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = '{$jobcard_data['drilling_invoice']}'");
// echo "SELECT * FROM jobcards WHERE jc_no = '{$jobcard_data['drilling_invoice']}'";
$jobcard_history = $jobcard_history_res->fetch_assoc();

$user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '{$_SESSION['user_id']}'");
$user = $user_res->fetch_assoc();

$current_date = date("Y-m-d H:i", strtotime("+2 Hours"));

?>

<style>
    @media (min-width: 651px) and (max-width: 1050px) {
        .save_sign_btn {
            position: relative;
            font-size: 2em;
            cursor: pointer;
            border: 3px solid navy;
            background: white;
            color: black;
            border-radius: 15px;
            padding: 1.5vw;
            height: 15vw;
            width: 55vw;
            text-align: center;
        }

        .signature_form {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
        }

        .div_signatures {
            position: relative;
            display: flex;
            flex-direction: column;
            width: 100%;
            justify-content: space-around;
            width: fit-content;
            /* margin-top: 30vh; */
            /* margin-bottom: 30vh; */
        }

        .history_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }

        .main_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }
    }
</style>

<?php

$res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$repair_data['jobcard_no']}' ORDER BY record_id DESC LIMIT 1");
// echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$repair_data['jobcard_no']}' ORDER BY record_id DESC";
$data = $res_data->fetch_assoc();

if ($res_data->num_rows == 0 || $data['type'] == "DEPARTURE" || $data['type'] == "ARRIVED") {

    $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$repair_data['jobcard_no']}' ORDER BY record_id DESC");

    $has_departed = false;
    $has_arrived = false;

    if ($res_arrival->num_rows > 0) {
        while ($current_status = $res_arrival->fetch_assoc()) {

            if ($current_status['type'] == "DEPARTURE") {
                $has_departed = true;
            }

            if ($current_status['type'] == "ARRIVED") {
                $has_arrived = true;
            }
        }
    }

    if ($has_departed && $has_arrived) {
        $current_jc_status = new input();
        $current_jc_status->value("DEPARTED AND ARRIVED");
        $current_jc_status->readonly();
        $current_jc_status->class("inputs");
        $current_jc_status->type("hidden");
        $current_jc_status->id("jc_current_status");
        $current_jc_status->onchange("check_status()");
        $current_jc_status->add();

        ?>

        <div class="history_div">
            <h2 class="create_h2">JOCARD HISTORY</h2>
            <br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="client_name_label" class="create_details_label" style="width: 100%;">JOBCARD ID : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['jc_no']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="client_name_label" class="create_details_label" style="width: 100%;">CLIENT NAME : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['client_name']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="address_label" class="create_details_label" style="width: 100%;">ADDRESS : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['address']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="contact_no_label" class="create_details_label" style="width: 100%;">CONTACT NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['contact_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="other_no_label" class="create_details_label" style="width: 100%;">OTHER NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['other_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="alternate_no_label" class="create_details_label" style="width: 100%;">ALTERNATE NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['alternate_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="break_found_label" class="create_details_label" style="width: 100%;">BREAK FOUND ON : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['break_found_on']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="water_strike_label" class="create_details_label" style="width: 100%;">WATER STRIKE : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['water_strike']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="water_flow_label" class="create_details_label" style="width: 100%;">WATER FLOW : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['water_flow']; ?>" readonly>
            </div>
        </div>

        <div class="history_div">
            <h2 class="create_h2">INSTALL DETAILS</h2>
            <br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="jobcard_id_label" class="create_details_label" style="width: 100%;">JOBCARD ID : </label>
                <input class="create_details_input" id="jobcard_id" name="jobcard_id"
                    value="<?php echo $jobcard_data['jobcard_no']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="jobcard_id_label" class="create_details_label" style="width: 100%;">ATTENED BY : </label>
                <input class="create_details_input" id="attended_by" name="attended_by"
                    value="<?php echo $jobcard_data['attended_by']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">BOREHOLE METERS</label>
                <input type="text" name="borehole_meters" id="borehole_meters" class="create_details_input"
                    value="<?php echo $jobcard_data['borehole_meters'] ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">HDPE METERS</label>
                <input type="text" name="hdpe_meters" id="hdpe_meters" class="create_details_input"
                    value="<?php echo $jobcard_data['hdpe_meters'] ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">CABLE METERS</label>
                <input type="text" name="cable_meters" id="cable_meters" class="create_details_input"
                    value="<?php echo $jobcard_data['cable_meters'] ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">PUMP DEPTH</label>
                <input type="text" name="pump_depth" id="pump_depth" class="create_details_input"
                    value="<?php echo $jobcard_data['pump_depth'] ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">METERS DRILLED</label>
                <input type="text" name="meters_drilled" id="meters_drilled" class="create_details_input"
                    value="<?php echo $jobcard_data['meters_drilled'] ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="crack_label" class="create_details_label" style="width: 100%;">CRACK</label>
                <input type="text" name="crack" id="crack" class="create_details_input"
                    value="<?php echo $jobcard_data['crack'] ?>" readonly>
            </div><br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_description_label" class="create_details_label" style="width: 100%;">PROBLEM DESCRIPTION :
                </label>
                <textarea name="problem_description" id="problem_description" rows="5" class="create_details_input"
                    style="font-size: 3em;" readonly><?php echo $jobcard_data['problem_description'] ?></textarea>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_solution_label" class="create_details_label" style="width: 100%;">SOLUTION :
                </label>
                <textarea name="problem_solution" id="problem_solution" rows="5" class="create_details_input"
                    style="font-size: 3em;" readonly><?php echo $jobcard_data['problem_solution'] ?></textarea>
            </div><br>

            <!-- CLIENT SIGNATURE -->
            <?php
            $dir = __DIR__ . "/pump_slip/";
            $url = "/app/jobcards/pump/pump_slip/";

            $pump_file = $dir . $jobcard_data['pump_slip'];
            $pump_url = $url . $jobcard_data['pump_slip'];

            // echo $client_file;
            if (file_exists($pump_file)) {
                ?>
                <div style='display: flex; flex-direction: column;align-items: center;'>
                    <h2 style="font-size: 2em;">PUMP SLIP</h2>
                    <input type="image" src="<?php echo $pump_url; ?>" alt="client signature" class="signature_image">
                </div>
                <?php
            } else {
                ?>
                <div style="margin-bottom:1vw; display:flex; flex-direction:column; align-items:center;">
                    <h2 style="font-size: 2em;">PUMP SLIP</h2>
                    <div
                        style="width:80vw; height:20vw; border:2px solid black; border-radius:1vw; display:flex; justify-content:center; align-items:center; background-color:#f0f0f0;">
                        <span style="color:#888888; font-size:1.5vw;">NO SIGNATURE FOUND</span>
                    </div>
                    <?php
            }
            ?>

            </div>
            <br>
        </div>

        <div id="signatures"
            style="display: flex; flex-direction: column; background-color: white; border-radius: 3vw; padding: 4vw; margin-top: 3vw;">
            <h1 class="sign_h1">SIGNATURES</h1>

            <div style="text-align: left; font-size: 3.5vw;">
                Please Note: Savuki Drilling Mpumalanga
                <ul>
                    <li>1. Cannot be held responsible for any damage or borehole collapse.</li>
                    <li>2. Steel casings must be installed on the recommendation of the drill team.</li>
                    <li>3. Will not be held liable for any damage on property.</li>
                    <li>4. No water is guaranteed even if Savuki Drilling surveyed.</li>
                    <li>5. Client pays for service of drilling, not water.</li>
                </ul>
                <b><i>
                        SAFETY PRECAUTION -<br>
                        CUSTOMER IS RESPONSIBLE FOR COVERING OF BOREHOLE AFTER DRILLING.<br>
                        SAVUKI DRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANY UNCOVERED BOREHOLES.
                    </i></b>
            </div>

            <div style="display: flex; flex-direction: column;">
                <div style="display: flex; flex-direction: column; justify-content: center; flex-wrap: wrap;">

                    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

                    <?php

                    $target_dir = __DIR__ . "/signatures/";
                    $target_url = "/app/jobcards/pump/signatures/";

                    $employee_flie = $target_dir . "employee-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
                    $employee_url = $target_url . "employee-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

                    // EMPLOYEE SIGNATURE
                    if (file_exists($employee_flie)) {
                        ?>
                        <div style='display: flex; flex-direction: column;align-items: center;'>
                            <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                            <input type='image' src="<?php echo $employee_url; ?>" alt='employee signature' class="signature_image">
                        </div>
                        <?php
                    } else {
                        ?>
                        <div style='display: flex; flex-direction: column;align-items: center;'>
                            <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                            <canvas id="employee_signature" class="signature-pad"></canvas>
                            <div style="display:flex;gap:10px;">
                                <button type="button" id="clear_employee_signature" class="sign_btn">CLEAR</button>
                            </div>
                        </div>
                        <?php
                    }

                    // CLIENT SIGNATURE
                    $client_file = $target_dir . "client-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
                    $client_url = $target_url . "client-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

                    // echo $client_file;
                    if (file_exists($client_file)) {
                        ?>
                        <div style='display: flex; flex-direction: column;align-items: center;'>
                            <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                            <input type="image" src="<?php echo $client_url; ?>" alt="client signature" class="signature_image">
                        </div>
                        <?php
                    } else {
                        ?>
                        <div style='display: flex; flex-direction: column;align-items: center;'>
                            <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                            <canvas id="client_signature" class="signature-pad"></canvas>
                            <div style="display:flex;gap:10px;">
                                <button type="button" id="clear_client_signature" class="sign_btn">CLEAR</button>
                            </div>
                        </div>
                        <?php
                    }
                    ?>
                </div>

                <div>
                    <?php
                    if (
                        !file_exists($client_file) ||
                        !file_exists($employee_flie)
                    ) {
                        echo "<button type='button' id='save_signatures' class='save_sign_btn' >SAVED</button>";
                    } else {

                    }
                    ?>
                </div>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const clientCanvas = document.getElementById('client_signature');
                const employeeCanvas = document.getElementById('employee_signature');
                const saveButton = document.getElementById('save_signatures');
                const clearClient = document.getElementById('clear_client_signature');
                const clearEmployee = document.getElementById('clear_employee_signature');
                const record_id = '<?php echo htmlspecialchars($_GET['jobcard_no']); ?>';

                // Resize canvas to match CSS dimensions for crisp drawing
                function resizeCanvas(canvas) {
                    if (!canvas) return;
                    const ratio = Math.max(window.devicePixelRatio || 1, 1);
                    const rect = canvas.getBoundingClientRect();
                    canvas.width = rect.width * ratio;
                    canvas.height = rect.height * ratio;
                    const ctx = canvas.getContext("2d");
                    ctx.scale(ratio, ratio);
                }

                resizeCanvas(clientCanvas);
                resizeCanvas(employeeCanvas);

                window.addEventListener("resize", () => {
                    resizeCanvas(clientCanvas);
                    resizeCanvas(employeeCanvas);
                });

                const padOptions = {
                    minWidth: 0.5,
                    maxWidth: 2.5,
                    throttle: 0,
                    velocityFilterWeight: 0.6,
                    penColor: 'black',
                    backgroundColor: 'rgba(255,255,255,0)'
                };

                const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
                const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

                // Prevent page scrolling while signing on mobile
                [clientCanvas, employeeCanvas].forEach(canvas => {
                    if (canvas) {
                        canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                        canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
                    }
                });

                // Clear buttons
                if (clearClient && client_pad) clearClient.addEventListener('click', () => client_pad.clear());
                if (clearEmployee && employee_pad) clearEmployee.addEventListener('click', () => employee_pad.clear());

                // Save button
                if (saveButton) {
                    saveButton.addEventListener('click', function () {
                        const hasClient = client_pad && !client_pad.isEmpty();
                        const hasEmployee = employee_pad && !employee_pad.isEmpty();

                        if (!hasClient && !hasEmployee) {
                            alert("Please provide at least one signature before saving.");
                            return;
                        }

                        saveButton.disabled = true;
                        saveButton.textContent = "Saving...";

                        let uploads = 0;
                        const total = (hasClient ? 1 : 0) + (hasEmployee ? 1 : 0);

                        function checkComplete() {
                            uploads++;
                            if (uploads === total) {
                                location.reload();
                            }
                        }

                        if (hasClient) uploadSignature(client_pad, 'client', checkComplete);
                        if (hasEmployee) uploadSignature(employee_pad, 'employee', checkComplete);
                    });
                }

                // Upload a signature pad image to the server
                function uploadSignature(pad, type, callback) {
                    const dataURL = pad.toDataURL('image/png');
                    const blob = dataURLToBlob(dataURL);
                    const formData = new FormData();

                    formData.append('file', blob, type + '_signature.png');
                    formData.append('record_id', record_id);
                    formData.append('type', type);

                    const xhr = new XMLHttpRequest();
                    xhr.open("POST", "../pump/upload_signature.php", true);

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                console.log(`${type} signature saved successfully.`);
                            } else {
                                alert(`Error saving ${type} signature: ${xhr.responseText}`);
                                // Re-enable save button on error
                                if (saveButton) {
                                    saveButton.disabled = false;
                                    saveButton.textContent = "SAVE";
                                }
                            }
                            if (callback) callback();
                        }
                    };

                    xhr.send(formData);
                }

                // Convert Base64 data URL to Blob for upload
                function dataURLToBlob(dataURL) {
                    const binary = atob(dataURL.split(',')[1]);
                    const array = [];
                    for (let i = 0; i < binary.length; i++) {
                        array.push(binary.charCodeAt(i));
                    }
                    return new Blob([new Uint8Array(array)], { type: 'image/png' });
                }
            });
        </script>

        <div class="main_div">
            <h2 class="create_h2">JOBCARD</h2>
            <br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="jobcard_id_label" class="create_details_label" style="width: 100%;">JOBCARD ID : </label>
                <input class="create_details_input" id="jobcard_no" name="jobcard_id"
                    value="<?php echo $repair_data['jobcard_no']; ?>" readonly>
                <input class="create_details_input" id="record_id" name="jobcard_id"
                    value="<?php echo $repair_data['record_id']; ?>" hidden>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="repaired_by_label" class="create_details_label" style="width: 100%;">REPAIRED BY</label>
                <input type="text" name="repaired_by" id="repaired_by" class="create_details_input"
                    value="<?php echo $user['username'] ?>">
                <input type="text" name="date_time_started" id="date_time_started" class="create_details_input"
                    value="<?php echo $current_date; ?>" hidden>
            </div><br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_description_label" class="create_details_label" style="width: 100%;">PROBLEM DESCRIPTION :
                </label>
                <textarea name="problem_description" id="problem_description" rows="5" class="create_details_input"
                    style="font-size: 3em;"><?php echo $repair_data['problem_description']; ?></textarea>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_solution_label" class="create_details_label" style="width: 100%;">SOLUTION :
                </label>
                <textarea name="problem_solution" id="problem_solution" rows="5" class="create_details_input"
                    style="font-size: 3em;"><?php echo $repair_data['problem_solution']; ?></textarea>
            </div><br>

            <?php

            $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY jobcard_id DESC LIMIT 1");
            // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY record_id DESC LIMIT 1";
    
            $record_res = $res_arrival->fetch_assoc();

            if ($record_res['type'] == "ARRIVED") {
                $next_btn = new button();
                $next_btn->style("margin-top: 5vw; margin-bottom: 3vw;");
                $next_btn->value("SAVE");
                $next_btn->onclick("if (check()) { update_jobcard(); next(); }");
                $next_btn->add();

                $update_ajax = new js_ajax();
                $update_ajax->function_name("update_jobcard");
                $update_ajax->update("pump_repair");
                $update_ajax->selected_div(".main_div input , .main_div select, .main_div textarea");
                $update_ajax->add_column_and_value("record_id={$_GET['record_id']}");
                $update_ajax->on_success("DATA CAPTURED AND SAVED");

                $riem_ajax = new js_ajax();
                $riem_ajax->function_name("next");
                $riem_ajax->selected_div("jobcard_time");
                $riem_ajax->insert("jobcard_timeline");
                $riem_ajax->add_column_and_value("jobcard_id={$_GET['jobcard_no']},date_time={$current_date},type=REPAIR,user_id={$_SESSION['user_id']}");
                $riem_ajax->redirect("repair_actions.php?record_id={$_GET['record_id']}&jobcard_no={$_GET['jobcard_no']}");
                $riem_ajax->exclude_inputs("payment_method");

            } elseif ($record_res['type'] == "DEPARTED") {
                $next_btn = new button();
                $next_btn->value("DISABLED");
                $next_btn->style("background-color: #00008045; color: white;");
                $next_btn->add();
            } else {
                $next_btn = new button();
                $next_btn->value("NEXT");
                $next_btn->onclick("submit_jobcard()");
                $next_btn->add();

                $submit_details = new js_ajax();
                $submit_details->function_name("submit_jobcard");
                $submit_details->update("pump_repair");
                $submit_details->selected_div(".main_div input , .main_div select, .main_div textarea");
                $submit_details->redirect("repair_actions.php?record_id={$_GET['record_id']}");
                $submit_details->exclude_inputs("['jc_current_status', 'eft_type']");
                $submit_details->on_success("DATA CAPTURED AND SAVED");
            }

            ?>
        </div>

        <?php

    } else if ($has_departed) {
        $arrival_btn = new button();
        $arrival_btn->value("ARRIVAL");
        $arrival_btn->onclick("team_arrived()");
        $arrival_btn->id("arrival_button");
        $arrival_btn->class('process_btn');

        $current_jc_status = new input();
        $current_jc_status->value("DEPARTED");
        $current_jc_status->readonly();
        $current_jc_status->class("inputs");
        $current_jc_status->type("hidden");
        $current_jc_status->id("jc_current_status");
        $current_jc_status->onchange("check_status()");

        $depart_ajax = new js_ajax();
        $depart_ajax->function_name("team_arrived");
        $depart_ajax->insert("jobcard_timeline");
        $depart_ajax->selected_div("arrival");
        $depart_ajax->add_column_and_value("jobcard_id={$repair_data['jobcard_no']},date_time={$current_date},type=ARRIVED,user_id={$_SESSION['user_id']}");
        $depart_ajax->on_success("ARRIVAL CAPTURED");

        // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY record_id DESC";

        ?>

            <div class="form_down" id="arrival">
                <?php
                $arrival_btn->add();
                $current_jc_status->add();
                ?>
            </div>

        <?php

    } else {

        $depart_btn = new button();
        $depart_btn->value("DEPARTURE");
        $depart_btn->onclick("team_departed()");
        $depart_btn->id("departure_button");
        $depart_btn->class('process_btn');

        $current_jc_status = new input();
        $current_jc_status->value("START");
        $current_jc_status->readonly();
        $current_jc_status->class("inputs");
        $current_jc_status->type("hidden");
        $current_jc_status->id("jc_current_status");
        $current_jc_status->onchange("check_status()");

        $depart_ajax = new js_ajax();
        $depart_ajax->function_name("team_departed");
        $depart_ajax->insert("jobcard_timeline");
        $depart_ajax->selected_div("departure");
        $depart_ajax->add_column_and_value("jobcard_id={$repair_data['jobcard_no']},date_time={$current_date},type=DEPARTURE,user_id={$_SESSION['user_id']}");
        $depart_ajax->on_success("DEPARTURE CAPTURED");

        ?>

            <div class="form_down" id="departure">
                <?php
                $current_jc_status->add();
                $depart_btn->add();
                ?>
            </div>

        <?php
    }

} else {
    ?>
    <script>
        window.location.href = "../pump/repair_actions.php?record_id=<?= $_GET['record_id'] ?>&jobcard_no=<?= $_GET['jobcard_no'] ?>";
    </script>
    <?php
}

?>

<script>
    function check_status() {
        var status = document.getElementById("jc_current_status").value.trim();
        var arrivalDiv = document.getElementById("arrival");
        var departureDiv = document.getElementById("departure");

        if (status === "ARRIVED") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED AND ARRIVED") {
            departureDiv.style.display = "none";
            arrivalDiv.style.display = "flex";
        }
    }

    function check() {
        var repaired_by = document.getElementById("repaired_by").value;

        if (repaired_by == "") {
            alert("Please enter Repair Name");
            return false;
        }

        return true;
    }

</script>