<?php
include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
$calls = new call_functions();
$disptach_res = $db->query("order_trans", "SELECT * FROM order_trans LEFT JOIN stock ON order_trans.stock_id = stock.record_id WHERE (((order_trans.date_time BETWEEN '{$_POST['date_from']} 00:00' AND '{$_POST['date_to']} 23:59' AND order_trans.amount < 0) AND (order_trans.job_card_no != '' AND order_trans.user_id != 0 AND order_trans.order_id = 0))  OR ((order_trans.date_time BETWEEN '{$_POST['date_from']} 00:00' AND '{$_POST['date_to']} 23:59' AND order_trans.amount > 0) AND (order_trans.job_card_no != '' AND order_trans.user_id != 0 AND order_trans.order_id = 0))) AND stock.item_code = 'TECSPA' ORDER BY `order_trans`.`record_id` DESC;");

// echo  "SELECT * FROM order_trans WHERE ((date_time BETWEEN '{$_POST['date_from']} 00:00' AND '{$_POST['date_to']} 23:59' AND amount < 0) AND (job_card_no != NULL AND user_id != 0 AND order_id = 0))  OR ((date_time BETWEEN '2025-09-01 00:00' AND '2025-09-30 23:59' AND amount > 0) AND (job_card_no != '' AND user_id != 0 AND order_id = 0)) ORDER BY `order_trans`.`amount` DESC;";

// exit;
?>
<div id="loadingOverlay"
    style="display: none; position: sticky; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(255, 255, 255, 0.8); z-index: 1000; display: flex; justify-content: center; align-items: center;">
    <div class="spinner"
        style="border: 8px solid #f3f3f3; border-top: 8px solid #3498db; border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite;">
    </div>
</div>

<style>
    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }

    .table-responsive {
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 14px;
        color: #333;
        background: #fff;
        box-shadow: 0 2px 8px rgb(0 0 0 / 0.1);
        border-radius: 8px;
        overflow: hidden;
        min-width: 700px;
    }

    thead th {
        position: sticky;
        top: 0;
        background-color: #1e90ff;
        color: white;
        text-align: left;
        padding: 12px 15px;
        font-weight: 600;
        letter-spacing: 0.03em;
        user-select: none;
        z-index: 1;
    }

    table td {
        padding: 12px 15px;
        border-bottom: 1px solid #eaeaea;
    }

    table tr:nth-child(even) {
        background: #f9f9f9;
    }

    table tbody tr:hover {
        background-color: #d0e7ff;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
</style>

<script>
    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }

    window.addEventListener("load", function () {
        hideLoading();
    });

    function change(obj, column, record_id) {
        var value = obj.value;
        var data = {
            column: column,
            value: value,
            record_id: record_id
        };
        var row = obj.closest('tr');

        fetch("update_data.ajax.php", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: new URLSearchParams(data)
        })
            .then(response => response.text())
            .then(result => {
                row.style.transition = "background-color 0.5s ease";
                row.style.backgroundColor = result.trim() === '1' ? "green" : "red";
                setTimeout(() => row.style.backgroundColor = "", 1000);
            })
            .catch(error => console.error('Error:', error));
    }
</script>

<div class="container"
    style="position: sticky; top: 0; display: flex; flex-direction: column;background-color: lightgray;">
    <div style=" display: flex; flex-direction: row; padding: 1vw; ">
        <input type="submit"
            onclick="window.location.href = 'pj_report_pdf.php?from_date=<?php echo $_POST['date_from']; ?>&to_date=<?php echo $_POST['date_to']; ?>';this.value='Loading...';this.disabled=true;"
            value="PDF" class="submit_btn" style='width:10vw;margin-right: 3vw' />
        <input type="submit"
            onclick="window.location.href = 'pj_report_excel.php?from_date=<?php echo $_POST['date_from']; ?>&to_date=<?php echo $_POST['date_to']; ?>';this.value='Loading...';this.disabled=true;"
            value="EXCEL" class="submit_btn" style='width:10vw' />
    </div>
    <div style=" display: flex; flex-direction: row; padding: 1vw; ">
        <input type="text" id="search_details" style='width: 30vw; margin-right: 3vw;border-radius: 1vw;padding: 1vw;'
            placeholder="Search..." class="submit" />
        <input type="submit" onclick="search()" value="SEARCH" class="submit_btn" />
    </div>
    <script>
        function search() {
            search_details = document.getElementById('search_details').value.toUpperCase();
            let textareas = document.getElementsByTagName('textarea');
            showLoading();
            let found = false;
            for (let i = 0; i < textareas.length; i++) {
                if (textareas[i].value.includes(search_details)) {
                    if (!found) {
                        textareas[i].focus();
                        found = true;
                    }
                    textareas[i].style.backgroundColor = 'yellow';
                } else {
                    textareas[i].style.backgroundColor = 'white';
                }
            }
            hideLoading();


        }
    </script>
</div>

<div class="table-responsive">
    <table class="table">
        <tbody>
            <?php $index = 0;
            while ($disptach = $disptach_res->fetch_assoc()) {
                $item_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$disptach['stock_id']}");
                $item = $item_res->fetch_assoc();
                // check if job card is on project job card:
                $job_card_project_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE jc_number = '{$disptach['job_card_no']}'");
                $job_card_tech_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE jc_number ='{$disptach['job_card_no']}'");
                $job_card_acc_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `name` = '{$disptach['job_card_no']}'");
                if ($job_card_project_res->num_rows > 0) {
                    $job_card = $job_card_project_res->fetch_assoc();
                    $job_card_name = $job_card["project_name"];

                } else if ($job_card_tech_res->num_rows > 0) {
                    $job_card = $job_card_tech_res->fetch_assoc();

                    $job_card_name = $job_card["company_name"];

                } else if ($job_card_acc_res->num_rows > 0) {
                    $job_card = $job_card_acc_res->fetch_assoc();

                    $job_card_name = $job_card["description"];
                } else {

                    $job_card_name = "N/A";
                }



                ?>
                <tr>
                    </td>
                    <td>
                        <label>Date</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $disptach['date_time']; ?></textarea>
                    </td>
                    <td>
                        <label>Item</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $item['description']; ?></textarea>
                    </td>
                    <td>
                        <label>Code</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $item['item_code']; ?></textarea>
                    </td>
                    <td>
                        <label>Amount</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $disptach['amount']; ?></textarea>
                    </td>

                    <td>
                        <label>Disp/Rec By.</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $calls->get_username($disptach['user_id']); ?></textarea>

                    </td>

                    <td>
                        <label>J.C.</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $disptach['job_card_no']; ?></textarea>

                    </td>
                    <td>
                        <label>J.C. Name</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $job_card_name; ?></textarea>

                    </td>
                    <td>
                        <label>Disp/Rec. To.</label>
                        <textarea class="inputs" style="overflow:hidden; height:auto;"
                            onchange="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $disptach['received']; ?>
                                </textarea>
                </tr>

                <?php $index++;
            } ?>
        </tbody>
    </table>
</div>