<?php
class call_functions
{

    function get_username($user_id)
    {
        if ($user_id == "") {
            return "";
        }
        $db = new db_safeguard();
        $results = $db->query("users", "SELECT * FROM users WHERE record_id = $user_id");
        $data = $results->fetch_assoc();
        return $data['username'];
    }

    function get_user_email($user_id)
    {
        $db = new db_safeguard();
        $results = $db->query("users", "SELECT * FROM users WHERE record_id = $user_id");
        $data = $results->fetch_assoc();
        return $data['email'];
    }

    function get_job_card_status($status_id)
    {
        switch ($status_id) {
            case 0:
                $status = 'INACTIVE';
                break;
            case 1:
                $status = 'SEND TO TECHNICIAN';
                break;
            case 2:
                $status = 'SEND TO PJ';
                break;
            case 3:
                $status = 'SEND TO QUOTATION';
                break;
            case 4:
                $status = 'WAITING FOR PO';
                break;
            case 5:
                $status = 'WAITING FOR PARTS';
                break;
            case 6:
                $status = 'CLIENT DECLINED';
                break;
            case 7:
                $status = 'SEND TO TECHNICIAN FOR WORK';
                break;
            case 8:
                $status = 'SEND FOR INVOICING';
                break;
            case 9:
                $status = 'INVOICED';
                break;
            case 10:
                $status = 'PJ TO ASSIGN';
                break;
            case 11:
                $status = 'WARRANTY NO CHARGE';
                break;
        }
        return $status;

    }

    function get_stock_name($stock_id)
    {
        $db = new db_safeguard();
        $results = $db->query("stock", "SELECT * FROM stock WHERE record_id = $stock_id");
        $data = $results->fetch_assoc();
        return $data['description'];
    }

    function get_po_number($po_id)
    {
        $db = new db_safeguard();
        $results = $db->query("orders", "SELECT * FROM orders WHERE record_id = $po_id");
        $data = $results->fetch_assoc();
        return $data['po_number'];
    }

    function get_stock_price($stock_id)
    {
        $db = new db_safeguard();
        $results = $db->query("stock", "SELECT * FROM stock WHERE record_id = $stock_id");
        $data = $results->fetch_assoc();
        return $data['cost_price'];
    }

    function send_for_email(array $emails, array $names, $subject, $message)
    {
        // implode array into string
        $emails = implode(",", $emails);
        // implode names into string 
        $names = implode(",", $names);
        // send email
        $db = new db_safeguard();
        $message = str_replace("'", "*", $message);
        $message = str_replace('"', "~", $message);
        $db->query("events_manager", "INSERT INTO `events_manager`(`email_accounts`, `email_names`, `subject`, `message_html`, `sent`,`user_id`) VALUES ('$emails','$names','$subject','$message',0,{$_SESSION['user_id']})");
    }
    function get_supplier_name($supplier_id)
    {
        $db = new db_safeguard();
        $results = $db->query("suppliers", "SELECT * FROM suppliers WHERE record_id = $supplier_id");
        if ($results->num_rows > 0) {
            $row = $results->fetch_assoc();
            return $row["name"];
        } else {
            return "NO SUPPLIER NAME FOUND";
        }
    }

    function stock_datalist()
    {
        $db = new db_safeguard();
        $datalist = "<datalist id='stocks'>";

        $stock_res = $db->query("stock", "SELECT * FROM stock WHERE stock_type != 2 AND stock_type != 3 AND stock_type != 1");
        while ($stocks = $stock_res->fetch_assoc()) {
            // get stock amount
            $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE stock_id = {$stocks['record_id']}");
            $stock_amount = $stock_amount_res->fetch_assoc()['amount'];
            $datalist .= "<option>" . $stocks['description'] . "|R~{$stocks['record_id']}~RA~$stock_amount~AB~{$stocks['barcode']}~BT~{$stocks['stock_type']}~T</option>";
        }

        $units_stock = $db->query("order_trans", "SELECT DISTINCT units_stock_id FROM order_trans WHERE units_stock_id != 0");
        while ($units = $units_stock->fetch_assoc()) {
            // check if in stock 
            $order_trans_stock_res = $db->query("order_trans", "SELECT SUM(amount) AS amount,stock_id FROM order_trans WHERE units_stock_id = {$units['units_stock_id']}");
            $order_trans_stock = $order_trans_stock_res->fetch_assoc();
            if ($order_trans_stock['amount'] > 0) {

                // // get units order_item_id 
                $unit_stock_id_res = $db->query("units_stock", "SELECT * FROM units_stock WHERE record_id = {$units['units_stock_id']}");
                $unit_stock_id = $unit_stock_id_res->fetch_assoc();

                // get the stock_id form stock
                $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$order_trans_stock['stock_id']}");
                $stock = $stock_res->fetch_assoc();

                // get stock amount
                $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE units_stock_id = {$units['units_stock_id']}");
                $stock_amount = $stock_amount_res->fetch_assoc()['amount'];

                if (strlen($unit_stock_id['barcode']) > 5 && strlen($unit_stock_id['serial_number']) > 0) {
                    $datalist .= "<option>" . $stock['description'] . "|R~{$stock['record_id']}~RS~{$unit_stock_id['serial_number']}~SA~$stock_amount~AB~{$unit_stock_id['barcode']}~BT~{$stock['stock_type']}~T</option>";
                }

            }
        }
        $non_stock_res = $db->query("order_trans", "SELECT DISTINCT non_stock_id FROM order_trans WHERE non_stock_id != 0 AND units_stock_id = 0");
        while ($non_stock = $non_stock_res->fetch_assoc()) {
            // check if in stock 
            $order_trans_stock_res = $db->query("order_trans", "SELECT SUM(amount) AS amount, stock_id FROM order_trans WHERE non_stock_id = {$non_stock['non_stock_id']}");
            $order_trans_stock = $order_trans_stock_res->fetch_assoc();
            if ($order_trans_stock['amount'] > 0) {
                // get units order_item_id 
                $unit_stock_id_res = $db->query("non_stock", "SELECT * FROM non_stock WHERE record_id = {$non_stock['non_stock_id']}");
                $unit_stock_id = $unit_stock_id_res->fetch_assoc();

                // get the stock_id form stock
                $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$order_trans_stock['stock_id']}");
                $stock = $stock_res->fetch_assoc();

                // get stock amount
                $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE non_stock_id = {$non_stock['non_stock_id']}");
                $stock_amount = $stock_amount_res->fetch_assoc()['amount'];

                if (strlen($unit_stock_id['barcode']) > 5) {
                    $datalist .= "<option>" . $stock['description'] . "|R~{$stock['record_id']}~RA~$stock_amount~AB~{$unit_stock_id['barcode']}~BT~{$stock['stock_type']}~T</option>";
                }
            }
        }
        $datalist .= "</datalist>";
        return $datalist;
    }


    function stock_datalist_into_session()
    {
        $db = new db_safeguard();
        $datalist = "<datalist id='stocks'>";

        $stock_res = $db->query("stock", "SELECT * FROM stock WHERE stock_type != 2 AND stock_type != 3 AND stock_type != 1");
        while ($stocks = $stock_res->fetch_assoc()) {
            // get stock amount
            $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE stock_id = {$stocks['record_id']}");
            $stock_amount = $stock_amount_res->fetch_assoc()['amount'];
            $datalist .= "<option>" . $stocks['description'] . "|R~{$stocks['record_id']}~RA~$stock_amount~AB~{$stocks['barcode']}~BT~{$stocks['stock_type']}~T</option>";
        }

        $units_stock = $db->query("order_trans", "SELECT DISTINCT units_stock_id FROM order_trans WHERE units_stock_id != 0");
        while ($units = $units_stock->fetch_assoc()) {
            // check if in stock 
            $order_trans_stock_res = $db->query("order_trans", "SELECT SUM(amount) AS amount,stock_id FROM order_trans WHERE units_stock_id = {$units['units_stock_id']}");
            $order_trans_stock = $order_trans_stock_res->fetch_assoc();
            if ($order_trans_stock['amount'] > 0) {

                // // get units order_item_id 
                $unit_stock_id_res = $db->query("units_stock", "SELECT * FROM units_stock WHERE record_id = {$units['units_stock_id']}");
                $unit_stock_id = $unit_stock_id_res->fetch_assoc();

                // get the stock_id form stock
                $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$order_trans_stock['stock_id']}");
                $stock = $stock_res->fetch_assoc();

                // get stock amount
                $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE units_stock_id = {$units['units_stock_id']}");
                $stock_amount = $stock_amount_res->fetch_assoc()['amount'];

                if (strlen($unit_stock_id['barcode']) > 5 && strlen($unit_stock_id['serial_number']) > 0) {
                    $datalist .= "<option>" . $stock['description'] . "|R~{$stock['record_id']}~RS~{$unit_stock_id['serial_number']}~SA~$stock_amount~AB~{$unit_stock_id['barcode']}~BT~{$stock['stock_type']}~T</option>";
                }

            }
        }
        $non_stock_res = $db->query("order_trans", "SELECT DISTINCT non_stock_id FROM order_trans WHERE non_stock_id != 0 AND units_stock_id = 0");
        while ($non_stock = $non_stock_res->fetch_assoc()) {
            // check if in stock 
            $order_trans_stock_res = $db->query("order_trans", "SELECT SUM(amount) AS amount, stock_id FROM order_trans WHERE non_stock_id = {$non_stock['non_stock_id']}");
            $order_trans_stock = $order_trans_stock_res->fetch_assoc();
            if ($order_trans_stock['amount'] > 0) {
                // get units order_item_id 
                $unit_stock_id_res = $db->query("non_stock", "SELECT * FROM non_stock WHERE record_id = {$non_stock['non_stock_id']}");
                $unit_stock_id = $unit_stock_id_res->fetch_assoc();

                // get the stock_id form stock
                $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = {$order_trans_stock['stock_id']}");
                $stock = $stock_res->fetch_assoc();

                // get stock amount
                $stock_amount_res = $db->query("order_trans", "SELECT SUM(amount) AS amount FROM order_trans WHERE non_stock_id = {$non_stock['non_stock_id']}");
                $stock_amount = $stock_amount_res->fetch_assoc()['amount'];

                if (strlen($unit_stock_id['barcode']) > 5) {
                    $datalist .= "<option>" . $stock['description'] . "|R~{$stock['record_id']}~RA~$stock_amount~AB~{$unit_stock_id['barcode']}~BT~{$stock['stock_type']}~T</option>";
                }
            }
        }
        $datalist .= "</datalist>";
        $_SESSION['stock_datalist'] = $datalist;
    }


    function get_job_card_datalist()
    {
        $db = new db_safeguard();
        $jobcard_numbers_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE `status` = 1");
        $job_card_datalist = "<datalist id='job_cards'>";
        while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard['jc_number'] . "'>" . $jobcard['jc_number'] . "</option>";
        }

        $jobcard_numbers_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE (`status` != 0)");
        while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard['jc_number'] . "'>" . $jobcard['jc_number'] . "</option>";
        }

        $jobcard_accounts_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `status` = 1");
        while ($jobcard_accounts = $jobcard_accounts_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard_accounts['name'] . "'>" . $jobcard_accounts['name'] . "</option>";
        }
        $job_card_datalist .= "</datalist>";
        return $job_card_datalist;
    }

    function get_job_cards_into_session()
    {
        $db = new db_safeguard();
        $jobcard_numbers_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE `status` = 1");
        $job_card_datalist = "<datalist id='job_cards'>";
        while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard['jc_number'] . "'>" . $jobcard['jc_number'] . "</option>";
        }

        $jobcard_numbers_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE (`status` != 0)");
        while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard['jc_number'] . "'>" . $jobcard['jc_number'] . "</option>";
        }

        $jobcard_accounts_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `status` = 1");
        while ($jobcard_accounts = $jobcard_accounts_res->fetch_assoc()) {
            $job_card_datalist .= "<option value='" . $jobcard_accounts['name'] . "'>" . $jobcard_accounts['name'] . "</option>";
        }
        $job_card_datalist .= "</datalist>";
        $_SESSION['job_cards_list'] = $job_card_datalist;
    }
}

class signature
{
    function __construct($html_input_for_file_name = '', $save_is_submit = 0, $width = 300, $height = 200)
    {
        ?>
        <style>
            #signature-container {
                width:
                    <?php echo $width; ?>
                    px;
                height:
                    <?php echo $height; ?>
                    px;
                border: 1px solid #ccc;
                background-color: #fff;
                touch-action: none;
                position: relative;
            }

            #signature-pad {
                width: 100%;
                /* height: 100%; */
            }

            #buttons {
                margin-top: 10px;
            }
        </style>

        <h2>Signature Pad</h2>
        <div id="signature-container">
            <canvas id="signature-pad"></canvas>
        </div>

        <div id="buttons">
            <button class="submit_btn" onclick="clearPad()">Clear</button>
            <button class="submit_btn" onclick="savePad()">SIGN</button>
        </div>

        <script>
            const canvas = document.getElementById('signature-pad');
            const container = document.getElementById('signature-container');
            const ctx = canvas.getContext('2d');

            // Match canvas resolution to container size
            canvas.width = container.offsetWidth;
            canvas.height = container.offsetHeight;

            let drawing = false;

            canvas.addEventListener('mousedown', startDraw);
            canvas.addEventListener('mouseup', stopDraw);
            canvas.addEventListener('mouseout', stopDraw);
            canvas.addEventListener('mousemove', draw);

            canvas.addEventListener('touchstart', startDraw, { passive: false });
            canvas.addEventListener('touchend', stopDraw, { passive: false });
            canvas.addEventListener('touchmove', drawTouch, { passive: false });

            function getPos(e) {
                const rect = canvas.getBoundingClientRect();
                const clientX = e.clientX || (e.touches && e.touches[0].clientX);
                const clientY = e.clientY || (e.touches && e.touches[0].clientY);
                return {
                    x: (clientX - rect.left) * (canvas.width / rect.width),
                    y: (clientY - rect.top) * (canvas.height / rect.height)
                };
            }

            function startDraw(e) {
                e.preventDefault();
                drawing = true;
                ctx.beginPath();
                const pos = getPos(e);
                ctx.moveTo(pos.x, pos.y);
            }

            function stopDraw() {
                drawing = false;
            }

            function draw(e) {
                if (!drawing) return;
                const pos = getPos(e);
                ctx.lineTo(pos.x, pos.y);
                ctx.stroke();
            }

            function drawTouch(e) {
                e.preventDefault();
                if (!drawing) return;
                const pos = getPos(e);
                ctx.lineTo(pos.x, pos.y);
                ctx.stroke();
            }

            function clearPad() {
                event.preventDefault();
                ctx.clearRect(0, 0, canvas.width, canvas.height);
            }

            function savePad() {
                // Prevent form from submitting
                event.preventDefault();
                const dataURL = canvas.toDataURL('image/png');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'save_signature.php', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        if (xhr.responseText !== '0') {
                            alert('Signature saved successfully!');
                            const inputName = '<?php echo $html_input_for_file_name; ?>';
                            const saveIsSubmit = <?php echo (int) $save_is_submit; ?>;

                            if (inputName !== '') {
                                // alert(inputName);
                                const inputElement = document.getElementById(inputName);
                                if (inputElement) {
                                    inputElement.setAttribute('value', xhr.responseText);
                                    // alert(inputElement.value);

                                }
                            }
                            if (inputElement.value == xhr.responseText) {
                                // ✅ Only try submitting form if save_is_submit == 1
                                if (<?php echo (int) $save_is_submit; ?> === 1) {
                                    const form = document.forms[0];
                                    const requiredInputs = form.querySelectorAll('input[required], select[required], textarea[required]');
                                    let valid = true;

                                    requiredInputs.forEach(el => {
                                        if (el.value.trim() === '') {
                                            valid = false;
                                        }
                                    });

                                    if (valid) {
                                        // alert(document.getElementById('signature1').value);
                                        form.dispatchEvent(new Event('submit'));
                                    } else {
                                        alert('Please fill in all required fields!');
                                    }
                                }
                            }
                        } else {
                            alert('Error saving signature!');
                        }
                    }
                };

                xhr.send('image=' + encodeURIComponent(dataURL));
            }
        </script>
        <?php
    }
}
?>