<?php




class inner_app
{

    public function __construct()
    {
        ?>
        <div class="app_body_container">
            <?php
    }


    public function quick_bar_button($text, $link)
    {
        ?>
            <button class="quick_bar_buttons"
                onclick="window.location.href = '<?php echo $link; ?>'"><?php echo $text; ?></button>
            <?php
    }

    public function quick_bar_section_button($text, $link)
    {
        ?>
            <button class="quick_bar_heading"
                onclick="window.location.href = '<?php echo $link; ?>'"><?php echo $text; ?></button>
            <?php
    }


    public function quick_bar_button_onclick($text, $function)
    {
        ?>
            <button class="quick_bar_buttons" onclick="<?php echo $function; ?>"><?php echo $text; ?></button>
            <?php
    }


    public function search_button()
    {
        ?>
            <!--<button class="quick_bar_buttons" onclick="search()">SEARCH</button>-->

            <script>

                function search() {
                    var popup = document.getElementById('search_bar');
                    popup.style.display = 'flex';
                    // helper: clear old highlights and borders
                    function clearHighlights() {
                        document.querySelectorAll(".highlighted-search").forEach(el => {
                            el.style.backgroundColor = '';
                            el.classList.remove("highlighted-search");
                        });
                        document.querySelectorAll(".highlighted-input").forEach(el => {
                            el.style.border = '';
                            el.classList.remove("highlighted-input");
                        });
                    }

                    // search button action
                    document.getElementById("search_btn").addEventListener("click", () => {
                        var input = document.getElementById('search_input').value.trim().toLowerCase();
                        clearHighlights();

                        if (input !== '') {
                            // Highlight normal text
                            var elements = document.querySelectorAll('body *:not(script):not(style):not(input):not(button)');
                            elements.forEach(el => {
                                if (el.childElementCount === 0 && el.textContent.toLowerCase().includes(input)) {
                                    el.style.backgroundColor = 'yellow';
                                    el.classList.add("highlighted-search");
                                }
                            });

                            // Search inside input values
                            var inputs = document.querySelectorAll('input[type=text], input[type=number], input[type=email], textarea');
                            inputs.forEach(el => {
                                if (el.value.toLowerCase().includes(input)) {
                                    el.style.border = '2px solid red';
                                    el.classList.add("highlighted-input");
                                    el.focus(); // focus on match
                                }
                            });
                        }
                    });

                    // close button action
                    document.getElementById("close_search_btn").addEventListener("click", () => {
                        clearHighlights();
                        popup.style.display = 'none';
                    });
                }

            </script>
            <?php
    }
    public function quick_bar($folder_path = "/default_app_data")
    {
        $db = new db();
        ?>
            <div class="app_quick_bar">
                <button class="quick_bar_heading"
                    onclick="window.location.href = ''"><?php echo strtoupper(str_replace('_', ' ', basename(dirname($_SERVER['REQUEST_URI'])))); ?></button>
                <?php
                if ($folder_path == '/default_app_data') {
                    $folder_path = dirname($_SERVER['REQUEST_URI']);
                    $folder_path_changed = str_replace(dirname($_SERVER['REQUEST_URI']), "" . dirname($_SERVER['REQUEST_URI']), $folder_path);
                    $path = $_SERVER["DOCUMENT_ROOT"] . '' . $folder_path_changed . '/';
                    foreach (new DirectoryIterator($path) as $fileInfo) {
                        if ($fileInfo->isFile()) {

                            if ($fileInfo->getFilename() === "." || $fileInfo->getFilename() === "..")
                                continue;

                            // check db if file path is there 
                            $file_exclude_res = $db->query("excluded_file_identifiers", "SELECT * FROM excluded_file_identifiers WHERE 1");
                            while ($file_exclude_row = $file_exclude_res->fetch_assoc()) {
                                if (strpos($fileInfo->getFilename(), $file_exclude_row['text']) !== false) {
                                    continue 2; // skip this file entirely
                                }
                            }

                            if ($fileInfo->getFilename() == basename($_SERVER['PHP_SELF']))
                                continue;

                            $button_name = strtoupper((ucfirst(str_replace("_", " ", str_replace(".php", "", $fileInfo->getFilename())))));
                            $button_name = str_replace(strtoupper(str_replace('_', ' ', basename(dirname($_SERVER['REQUEST_URI'])))), "", $button_name);

                            self::quick_bar_button($button_name, '' . $folder_path_changed . '/' . $fileInfo->getFilename());
                        }
                    }
                    self::search_button();
                    foreach (scandir($_SERVER["DOCUMENT_ROOT"] . '/default_app_data/') as $item) {
                        if ($item === '.' || $item === '..')
                            continue;
                        // check db if file path is there 
                        $file_exclude_res = $db->query("excluded_file_identifiers", "SELECT * FROM excluded_file_identifiers WHERE 1");
                        while ($file_exclude_row = $file_exclude_res->fetch_assoc()) {
                            if (strpos($item, $file_exclude_row['text']) !== false) {
                                continue 2; // skip this file entirely
                            }
                        }
                        if (is_dir($_SERVER["DOCUMENT_ROOT"] . '/default_app_data/' . DIRECTORY_SEPARATOR . $item)) {
                            if ($item == basename(dirname($_SERVER['REQUEST_URI']))) {
                                continue;
                            }
                            self::quick_bar_section_button(strtoupper(str_replace('_', ' ', $item)), '/default_app_data/' . $item . "/home.php");
                        }
                    }

                } else {
                    $folder_path_changed = str_replace(dirname($_SERVER['REQUEST_URI']), "" . dirname($_SERVER['REQUEST_URI']), $folder_path);
                    $path = $_SERVER["DOCUMENT_ROOT"] . '' . $folder_path_changed . '/';
                    if (dirname($_SERVER['REQUEST_URI']) == 'default_app_data') {
                        $path = $path . dirname($_SERVER['REQUEST_URI']) . '/';
                        // echo $path . "<br>";
                        $path = str_replace('/' . dirname($_SERVER['REQUEST_URI']), '', $path);
                        $path = $path . dirname($_SERVER['REQUEST_URI']) . '/';
                    } else {
                        $path = $_SERVER["DOCUMENT_ROOT"] . '/' . dirname($_SERVER['REQUEST_URI']);
                    }
                    foreach (new DirectoryIterator($path) as $fileInfo) {
                        if ($fileInfo->isFile()) {

                            if ($fileInfo->getFilename() === "." || $fileInfo->getFilename() === "..")
                                continue;

                            // check db if file path is there 
                            $file_exclude_res = $db->query("excluded_file_identifiers", "SELECT * FROM excluded_file_identifiers WHERE 1");
                            while ($file_exclude_row = $file_exclude_res->fetch_assoc()) {
                                if (strpos($fileInfo->getFilename(), $file_exclude_row['text']) !== false) {
                                    continue 2; // skip this file entirely
                                }
                            }

                            if ($fileInfo->getFilename() == basename($_SERVER['PHP_SELF']))
                                continue;

                            $button_name = strtoupper((ucfirst(str_replace("_", " ", str_replace(".php", "", $fileInfo->getFilename())))));
                            $button_name = str_replace(strtoupper(str_replace('_', ' ', basename(dirname($_SERVER['REQUEST_URI'])))), "", $button_name);

                            self::quick_bar_button($button_name, '' . $folder_path_changed . '/' . $fileInfo->getFilename());
                        }
                    }
                    self::search_button();
                    if (strpos(dirname($_SERVER['REQUEST_URI']), 'default_app_data') !== false) {
                        $path = $path . dirname($_SERVER['REQUEST_URI']) . '/';
                        echo $path . "<br>";
                        $path = str_replace('/' . dirname($_SERVER['REQUEST_URI']), '', $path);
                        $path = $path . dirname($_SERVER['REQUEST_URI']) . '/';
                        echo $path . "<br>";
                    } else {

                    }
                    foreach (scandir($path) as $item) {
                        if ($item === '.' || $item === '..')
                            continue;
                        // check db if file path is there 
                        $file_exclude_res = $db->query("excluded_file_identifiers", "SELECT * FROM excluded_file_identifiers WHERE 1");
                        while ($file_exclude_row = $file_exclude_res->fetch_assoc()) {
                            if (strpos($item, $file_exclude_row['text']) !== false) {
                                continue 2; // skip this file entirely
                            }
                        }
                        if (is_dir($path . DIRECTORY_SEPARATOR . $item)) {
                            if ($item == basename(dirname($_SERVER['REQUEST_URI']))) {
                                continue;
                            }
                            self::quick_bar_section_button(strtoupper(str_replace('_', ' ', $item)), '' . $folder_path . '/' . $item . "/home.php");
                        }
                    }
                }

                ?>
            </div>
            <?php
    }

    public function app_start()
    {
        ?>
            <div class="app">
                <div id="search_bar"
                    style="    display: none; position: relative; top: -1vh; left: 0px; /* transform: translateX(-50%); */ width: 100vw; column-gap: 1em; padding: 1em; background-color: rgba(0, 0, 0, 0.94); z-index: 9999; justify-content: center;">
                    <button id="close_search_btn">CLOSE</button>
                    <input type="text" id="search_input" placeholder="Search...">
                    <button id="search_btn">SEARCH</button>
                </div>
                <?php

    }

    public function __destruct()
    {

        ?>
            </div>
        </div>

        <?php
    }
}

class app_features
{

    function get_unpaid_invoices_list()
    {
        $db = new db();
        $res = $db->query("invoices", "SELECT * FROM invoices WHERE 1");
        while ($row = $res->fetch_assoc()) {
            // invoice items 
            $invoice_list_res = $db->query("invoice_list", "SELECT price,qty FROM invoice_list WHERE invoice_id = $row[record_id]");
            $total = 0;
            while ($invoice_list_row = $invoice_list_res->fetch_assoc()) {
                $invoice_amount = $invoice_list_row['price'];
                $total += (float) preg_replace('/[^0-9\.,]/', '', str_replace(['R', '�', 'Â', ','], '', utf8_decode($invoice_amount))) * (float) $invoice_list_row['qty'] * 1.15;
            }
            // echo "SELECT SUM(amount) as total FROM payments WHERE invoice_id = $row[record_id]";
            $payments_res = $db->query("payments", "SELECT SUM(amount) as total FROM payments WHERE invoice_id = $row[record_id]");
            $payments_row = $payments_res->fetch_assoc();
            $payments = $payments_row['total'];
            if ($payments == null) {
                echo "<option>$row[invoice_number]</option>";
            } else if ($payments == 0) {
                echo "<option>$row[invoice_number]</option>";
            } else if ((round((float) $payments, 2) / round($total * 1.15, 2)) != 1) {
                echo "<option>$row[invoice_number]</option>";
            }

        }
    }

    function get_stock_datalist($list_id)
    {
        $db = new db();
        $res = $db->query("stock", "SELECT * FROM stock WHERE 1");
        echo "<datalist id='$list_id'>";
        while ($row = $res->fetch_assoc()) {
            echo "<option>$row[code]~$row[name]~$row[unit_of_measure]~$row[retail]</option>";
        }
        echo "</datalist>";
    }

    function explainSQL($query)
    {
        $query = trim($query);
        $lower = strtolower($query);
        $response = "Could not interpret query.";

        // --- INSERT ---
        if (strpos($lower, "insert into") === 0) {
            if (preg_match("/insert into\s+`?(\w+)`?\s*\((.*?)\)\s*values\s*\((.*?)\)/i", $query, $matches)) {
                $table = $matches[1];
                $columns = explode(",", $matches[2]);
                $values = explode(",", $matches[3]);

                $changes = [];
                foreach ($columns as $i => $col) {
                    $col = trim(str_replace("`", "", $col));
                    $val = trim($values[$i] ?? '', " '\"");
                    $changes[] = "$col = '$val'";
                }

                $response = "Inserted into '$table' with values: " . implode(", ", $changes);
            }
        }

        // --- UPDATE ---
        elseif (strpos($lower, "update") === 0) {
            preg_match("/update\s+`?(\w+)`?\s+set\s+(.*?)\s+where\s+(.*)$/i", $query, $matches);
            if ($matches) {
                $table = $matches[1];
                $setString = $matches[2];
                $where = $matches[3];

                $assignments = explode(",", $setString);
                $changes = [];
                foreach ($assignments as $assignment) {
                    if (preg_match("/`?(\w+)`?\s*=\s*'?([^']*)'?$/", trim($assignment), $m)) {
                        $changes[] = "{$m[1]} = '{$m[2]}'";
                    }
                }

                $response = "Updated '$table' set " . implode(", ", $changes) . " ";
            }
        }

        // --- DELETE ---
        elseif (strpos($lower, "delete from") === 0) {
            preg_match("/delete from\s+`?(\w+)`?\s*(where\s+.*)?/i", $query, $matches);
            if ($matches) {
                $table = $matches[1];
                $where = $matches[2] ?? "";
                $response = "Deleted from '$table'" . ($where ? " $where" : "");
            }
        }

        // --- SELECT ---
        elseif (strpos($lower, "select") === 0) {
            preg_match("/select\s+(.*?)\s+from\s+`?(\w+)`?\s*(where\s+.*)?/i", $query, $matches);
            if ($matches) {
                $columns = $matches[1];
                $table = $matches[2];
                $where = $matches[3] ?? "";
                $response = "Selected $columns from '$table'" . ($where ? " $where" : "");
            }
        }

        return $response;
    }
    public function get_users_list($status = 1)
    {
        $db = new db();
        $res = $db->query("users", "SELECT * FROM users WHERE `status` = $status ORDER BY `username` ASC");
        while ($row = $res->fetch_assoc()) {
            $user_id = $row["record_id"];
            $username = $row["username"];
            echo "<option value='$user_id'>$username</option>";
        }

    }

    function get_status()
    {
        $db = new db();
        $res = $db->query("status", "SELECT * FROM status WHERE 1 ORDER BY `name` ASC");
        while ($row = $res->fetch_assoc()) {
            $id = $row["record_id"];
            $name = $row["name"];
            echo "<option value='$id'>$name</option>";
        }
    }

    function get_stock()
    {

        $db = new db();
        $res = $db->query("stock", "SELECT * FROM stock WHERE 1 ORDER BY `name` ASC");
        echo "<option ></option>";

        while ($row = $res->fetch_assoc()) {

            $record_id = $row["record_id"];
            $name = $row["name"];
            echo "<option value='$record_id'>$name</option>";
        }





    }
    function number_to_save($number)
    {
        // Remove currency symbols and commas first
        $num = str_replace(['R', ',', ' '], '', $number); // note: the ' ' is a non-breaking space
        // Then remove any kind of whitespace (including invisible ones)
        $num = preg_replace('/\s+/u', '', $num);
        // Finally, trim remaining spaces (normal or non-breaking)
        return trim($num, " \t\n\r\0\x0B\xC2\xA0");
    }

    function get_invoices()
    {
        $db = new db();
        $res = $db->query("invoices", "SELECT * FROM invoices WHERE 1 ORDER BY `record_id` ASC");
        while ($row = $res->fetch_assoc()) {

            $name = $row["invoice_number"];
            echo "<option>$name</option>";
        }
    }

    function get_users()
    {
        $db = new db();
        $res = $db->query("users", "SELECT * FROM users WHERE 1 ORDER BY `username` ASC");
        while ($row = $res->fetch_assoc()) {

            $record_id = $row["record_id"];
            $username = $row["username"];
            echo "<option value='$record_id'>$username</option>";
        }
    }
    function get_clients()
    {
        $db = new db();
        $res = $db->query("clients", "SELECT * FROM clients WHERE 1 ORDER BY `name` ASC");
        echo "<option></option>";
        while ($row = $res->fetch_assoc()) {

            $record_id = $row["record_id"];
            $name = $row["name"];
            echo "<option value='$record_id'>$name</option>";
        }
    }

    function get_clients_datalist($list_id)
    {
        $db = new db();
        $res = $db->query("clients", "SELECT * FROM clients WHERE 1 ORDER BY `name` ASC");
        echo "<datalist id='$list_id'>";
        while ($row = $res->fetch_assoc()) {

            $record_id = $row["record_id"];
            $name = $row["name"];
            echo "<option>$name : $record_id</option>";
        }
        echo "</datalist>";
    }
    public function get_user_count()
    {
        $db = new db();
        $res = $db->query("users", "SELECT * FROM users WHERE 1 ORDER BY `username` ASC");
        return $res->num_rows;
    }

    public function get_user_types()
    {
        $db = new db();
        $res = $db->query("user_types", "SELECT * FROM user_types WHERE 1 ORDER BY `name` ASC");
        while ($row = $res->fetch_assoc()) {
            $record_id = $row["record_id"];
            $name = $row["name"];
            echo "<option value='$record_id'>$name</option>";
        }

    }

    function get_supplier_name($supplier_id)
    {
        $db = new db();
        $res = $db->query("suppliers", "SELECT * FROM suppliers WHERE record_id = $supplier_id");
        $row = $res->fetch_assoc();
        return $row["name"];
    }
    public function get_suppliers()
    {
        $db = new db();
        $res = $db->query("suppliers", "SELECT * FROM suppliers WHERE 1 ORDER BY `name` ASC");
        while ($row = $res->fetch_assoc()) {
            $record_id = $row["record_id"];
            $name = $row["name"];
            echo "<option value='$record_id'>$name</option>";
        }
    }

    public function get_username($user_id)
    {
        $db = new db();
        $res = $db->query("users", "SELECT * FROM users WHERE record_id = $user_id");
        $row = $res->fetch_assoc();
        return $row["username"];

    }

    public function get_initials($user_id)
    {
        $db = new db();
        $res = $db->query("users", "SELECT * FROM users WHERE record_id = $user_id");
        $row = $res->fetch_assoc();
        return $row["initials"];

    }

    public function get_next_job_card_no()
    {
        $db = new db();
        $res = $db->query("job_cards", "SELECT * FROM job_cards ORDER BY record_id DESC LIMIT 1");
        $row = $res->fetch_assoc();
        $job_card_no = $row["job_card_no"];
        $job_card_no = substr($job_card_no, 4);
        $job_card_no = (int) $job_card_no + 1;
        $job_card_no = "JC" . date("y") . $job_card_no;
        return $job_card_no;
    }
}

class iframe_popup
{
    public function __construct($iframe_class = "popup_iframe", $iframe_close_class = "iframe_close", $iframe_bg_class = "iframe_background")
    {
        ?>
        <div class="<?php echo $iframe_bg_class; ?>" style="display: none;"></div>
        <iframe class="<?php echo $iframe_class; ?>" src="job_card_attachments.php" style="display: none;"></iframe>
        <i class="fa fa-times-circle <?php echo $iframe_close_class; ?>" style="display: none;" onclick="close_iframe()"></i>
        <script>
            function open_iframe(url) {
                document.querySelector(".<?php echo $iframe_class; ?>").style.display = "block";
                document.querySelector(".<?php echo $iframe_close_class; ?>").style.display = "block";
                document.querySelector(".<?php echo $iframe_bg_class; ?>").style.display = "block";
                document.querySelector(".<?php echo $iframe_class; ?>").src = url;
            }
            function close_iframe() {
                document.querySelector(".<?php echo $iframe_class; ?>").style.display = "none";
                document.querySelector(".<?php echo $iframe_close_class; ?>").style.display = "none";
                document.querySelector(".<?php echo $iframe_bg_class; ?>").style.display = "none";


            }
        </script>
        <?php

    }
}