<?php
include_once __DIR__ . "/../../global.php";

class crm_Functions extends object_class
{
    public $webClass;
    public $productClass;
    
    function __construct()
    {
        parent::__construct('3');

        $this->functions->require_once_custom('webProduct_functions');
        $this->productClass = new webProduct_functions();
        $this->webClass = $GLOBALS['webClass'];
    }

    public function usersView()
    {
        $sql = "SELECT * FROM `accounts_user` WHERE `status` = ? AND `acc_type` NOT IN (?, ?, ?) ORDER BY `acc_id` DESC";
        $users = $this->dbF->getRows($sql, [1, 1, 3, 4]);

        echo '<table id="usersTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Age</th>
                <th>Country</th>
                <th>Account Type</th>
                <th class="noExport">Photo</th>
                <th>Date Created</th>
                <th class="noExport">Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($users as $user) {
            $userId = $user["acc_id"];
            $name = $user["acc_name"];
            $email = $user["acc_email"];
            $image = empty($user["acc_image"]) ? WEB_URL . '/webImages/avatars/default.png' : WEB_URL . '/images/' . $user["acc_image"];
            $phone = $user['acc_phone'];
            $date = date('d-M-Y H:i A', strtotime($user["acc_created"]));

            $type = match ($user["acc_type"]) {
                2 => 'Manager',
                5 => 'Employee',
                default => 'Unknown',
            };

            $userDetail = $this->productClass->getUserDetailsById($userId);
            $country = $this->webClass->webUserInfoArray($userDetail, 'country');
            $dob = $this->webClass->webUserInfoArray($userDetail, 'dob');

            $birthDate = new DateTime($dob);
            $today = new DateTime();
            $age = $today->diff($birthDate)->y;
            $encodedId = $this->functions->encode($userId);
            echo '<tr>';
            echo "<td>$name</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$age</td>";
            echo "<td>$country</td>";
            echo "<td>$type</td>";
            echo "<td><a href='$image' target='_blank'><img src='$image' alt='$name' loading='lazy' width='45' height='45'></a></td>";
            echo "<td>$date</td>";
            echo "<td>
                    <div class='btn-group'>
                        <a href='useredit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function clientsView()
    {
        $sql = "SELECT * FROM `accounts_user` WHERE `status` = ? AND `acc_type` = ? ORDER BY `acc_id` DESC";
        $clients = $this->dbF->getRows($sql, [1, 4]);

        echo '<table id="clientsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th class="noExport">Actions</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Country</th>
                <th>Status</th>
                <th class="noExport">Photo</th>
                <th>Date Created</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($clients as $client) {
            $userId = $client["acc_id"];
            $name = $client["acc_name"];
            $email = $client["acc_email"];
            $image = empty($client["acc_image"]) ? WEB_URL . '/webImages/avatars/default.png' : WEB_URL . '/images/' . $client["acc_image"];
            $phone = $client['acc_phone'];
            $date = date('d-M-Y H:i A', strtotime($client["acc_created"]));

            $userDetail = $this->productClass->getUserDetailsById($userId);

            $country = $this->webClass->webUserInfoArray($userDetail, 'country');
            $clientStatus = $this->webClass->webUserInfoArray($userDetail, 'clientStatus');

            $encodedId = $this->functions->encode($userId);
            echo '<tr>';
            echo "<td>
                    <div class='btn-group'>
                        <a href='clientedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                        <button type='button' data-id='$userId' onclick=\"addNote(this, 'client');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>note_add</i></button>
                        <button type='button' data-id='$userId' onclick=\"viewNotes(this, 'client');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>message</i></button>
                    </div>
                </td>";
            echo "<td>$name</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$country</td>";
            echo "<td>$clientStatus</td>";
            echo "<td><a href='$image' target='_blank'><img src='$image' alt='$name' loading='lazy' width='45' height='45'></a></td>";
            echo "<td>$date</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function leadsView()
    {
        $sql = "SELECT * FROM `accounts_user` WHERE `status` = ? AND `acc_type` = ? ORDER BY `acc_id` DESC";
        $leads = $this->dbF->getRows($sql, [1, 3]);

        echo '<table id="leadsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th class="noExport">Actions</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Country</th>
                <th>Chase Up Date</th>
                <th>Chase Up By</th>
                <th>Assigned To</th>
                <th>Status</th>
                <th class="noExport">Photo</th>
                <th>Date Created</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($leads as $lead) {
            $userId = $lead["acc_id"];
            $name = $lead["acc_name"];
            $email = $lead["acc_email"];
            $image = empty($lead["acc_image"]) ? WEB_URL . '/webImages/avatars/default.png' : WEB_URL . '/images/' . $lead["acc_image"];
            $phone = $lead['acc_phone'];
            $date = date('d-M-Y H:i A', strtotime($lead["acc_created"]));

            $userDetail = $this->productClass->getUserDetailsById($userId);

            $country = $this->webClass->webUserInfoArray($userDetail, 'country');
            $leadStatus = $this->webClass->webUserInfoArray($userDetail, 'leadStatus');
            $chaseupdate = date('d-M-Y', strtotime($this->webClass->webUserInfoArray($userDetail, 'chaseupdate')));
            $chaseupby = $this->functions->webUserName($this->webClass->webUserInfoArray($userDetail, 'chaseupby'), 'acc_name');
            $assignto = $this->functions->webUserName($this->webClass->webUserInfoArray($userDetail, 'assignto'), 'acc_name');

            $encodedId = $this->functions->encode($userId);

            echo '<tr>';
            echo "<td>
                    <div class='btn-group'>
                        <a href='leadedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                        <button type='button' data-id='$userId' onclick=\"addNote(this, 'lead');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>note_add</i></button>
                        <button type='button' data-id='$userId' onclick=\"viewNotes(this, 'lead');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>message</i></button>
                    </div>
                </td>";
            echo "<td>$name</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$country</td>";
            echo "<td>$chaseupdate</td>";
            echo "<td>$chaseupby</td>";
            echo "<td>$assignto</td>";
            echo "<td>$leadStatus</td>";
            echo "<td><a href='$image' target='_blank'><img src='$image' alt='$name' loading='lazy' width='45' height='45'></a></td>";
            echo "<td>$date</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    } 
    public function listExplorerView()
    {
        $sql = "SELECT * FROM `pfa_records`ORDER BY id ASC";
        $list = $this->dbF->getRows($sql);

        echo '<table id="leadsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>External ID</th>
                <th>First Name</th>
                <th>Surname</th>
                <th>DOB</th>
                <th>Nationality</th>
                <th>Status</th>
                <th>Decrease</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($list as $lists) {
            $listId = $lists["id"];
            $first_name = $lists["first_name"];
            $surname = $lists["surname"];
            $middle_name = $lists["middle_name"];
            $dob = $lists["date_of_birth"];
            $status = $lists["active_status"];
            $nationality = $lists["nationality"];
            $deceased = $lists["deceased"];

            echo '<tr>';
            echo "<td>$listId</td>";
            echo "<td>$first_name</td>";
            echo "<td>$surname</td>";
            echo "<td>$dob</td>";
            echo "<td>$nationality</td>";
            echo "<td>$status</td>";
            echo "<td>$deceased</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }
    
    public function getTotalRecords()
    {
        $sql = "SELECT COUNT(*) as total FROM pfa_records";
        $row = $this->dbF->getRow($sql);
    
        return isset($row['total']) ? (int)$row['total'] : 0;
    }
    
    public function getActiveRecords()
    {
        $sql = "SELECT COUNT(*) as total FROM pfa_records WHERE active_status = 'Active'";
        $row = $this->dbF->getRow($sql);
    
        return isset($row['total']) ? (int)$row['total'] : 0;
    }
    
    public function getHighRiskRecords()
    {
    $sql = "SELECT COUNT(*) as total 
            FROM pfa_records 
            WHERE LOWER(zone) LIKE '%highrisk%'";
    $row = $this->dbF->getRow($sql);
    return isset($row['total']) ? (int)$row['total'] : 0;
    }
    
    
    public function detectionView()
    {
    $sql = "
        SELECT d.*
        FROM pfa_match_detections d
        INNER JOIN (
            SELECT matched_record_id, MIN(id) AS min_id
            FROM pfa_match_detections
            GROUP BY matched_record_id
        ) x ON x.matched_record_id = d.matched_record_id AND x.min_id = d.id
        ORDER BY d.matched_record_id ASC
    ";

    $list = $this->dbF->getRows($sql);

    echo '<table id="leadsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
    echo '<thead>
        <tr>
            <th>Matched Record ID</th>
            <th>External ID</th>
            <th>Query</th>
            <th>Matched Entity</th>
            <th>Score</th>
            <th>Risk</th>
            <th>Status</th>
            <th>Score</th>
            <th>Created</th>
            <th>Notes</th>
            <th>Status</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>';

    foreach ($list as $row) {

        $matched_record_id = (int)($row['matched_record_id'] ?? 0);
        $external_id  = htmlspecialchars($row['matched_external_id'] ?? '');
        $first_name   = htmlspecialchars($row['matched_first_name'] ?? '');
        $matched_middle_name      = htmlspecialchars($row['matched_middle_name'] ?? '');
        $match_score          = htmlspecialchars($row['match_score'] ?? '');
        $risk_level  = htmlspecialchars($row['risk_level'] ?? '');
        $confidence   = htmlspecialchars($row['match_confidence'] ?? '');
        $score        = htmlspecialchars($row['match_score'] ?? '');
        $statusdetection       = htmlspecialchars($row['detection_status'] ?? '');
        $detected_at        = htmlspecialchars($row['detected_at'] ?? '');
        $review_notes = htmlspecialchars($row['review_notes'] ?? '');
        $status = htmlspecialchars($row['status'] ?? '');
        


        echo '<tr>';
        echo '<td>' . $matched_record_id . '</td>';
        echo '<td>' . $external_id . '</td>';
        echo '<td class="js-view-detection text-primary" style="cursor:pointer;"
          data-matched-id="'.$matched_record_id.'">'
          . $first_name .
        '</td>';
        echo '<td>' . $matched_middle_name . '</td>';
        echo '<td>' . $match_score . '</td>';
        echo '<td>' . $risk_level . '</td>';
        echo '<td>' . $statusdetection . '</td>';
        echo '<td>' . $score . '</td>';
        echo '<td>' . $detected_at . '</td>';
        echo '<td>
          <button type="button"
                  class="btn btn-sm btn-dark js-add-note"
                  data-matched-id="'.$matched_record_id.'"
                  data-note="'.$review_notes.'">
              <i class="material-icons-outlined">note_add</i>
          </button>
        </td>';
        echo '<td class="js-status-cell" id="status_'.$matched_record_id.'">'.$status.'</td>';
        echo '<td id="action_'.$matched_record_id.'">
          <div class="d-flex gap-2 flex-nowrap">
            <button type="button"
                    class="btn btn-success btn-sm js-status"
                    data-status="Accept"
                    data-matched-id="'.$matched_record_id.'">Accept</button>
        
            <button type="button"
                    class="btn btn-danger btn-sm js-status"
                    data-status="Reject"
                    data-matched-id="'.$matched_record_id.'">Reject</button>
          </div>
        </td>';




        echo '</tr>';
        echo '
        <div class="modal fade" id="noteModal" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Add / Update Note</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <input type="hidden" id="note_matched_id" value="">
                <div class="mb-3">
                  <label class="form-label">Review Notes</label>
                  <textarea id="review_notes" class="form-control" rows="6" placeholder="Write notes..."></textarea>
                </div>
                <div id="noteMsg"></div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveNoteBtn">Save Note</button>
              </div>
            </div>
          </div>
        </div>';

    }

    echo '</tbody></table>';

    // Modal markup (print once under table)
    // $this->detectionModalHtml();
}

    public function searchHistoryView()
    {
    $sql = "SELECT * FROM `pfa_search_history` ORDER BY `pfa_search_history`.`id` DESC";
    $list = $this->dbF->getRows($sql);

    echo '<table id="leadsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
    echo '<thead>
        <tr>
            <th>Time Searched At</th>
            <th>Search Query</th>
            <th>Search Type</th>
            <th>Results</th>
            <th>Top Score</th>
            <th>User</th>
        </tr>
    </thead>
    <tbody>';

    foreach ($list as $row) {

        $search_term = htmlspecialchars($row['search_term'] ?? 0);
        $search_type  = htmlspecialchars($row['search_type'] ?? '');
        $max_results   = htmlspecialchars($row['max_results'] ?? '');
        $highest_score      = htmlspecialchars($row['highest_score'] ?? '');
        $searched_at         = htmlspecialchars($row['searched_at'] ?? '');
        $user_id         = htmlspecialchars($row['user_id'] ?? '');
        


        echo '<tr>';
        echo '<td>' . $searched_at . '</td>';
        echo '<td>' . $search_term . '</td>';
        echo '<td>' . $search_type . '</td>';
        echo '<td>' . $max_results . '</td>';
        echo '<td>' . $highest_score . '</td>';
        echo '<td>' . $user_id . '</td>';
        echo '</tr>';
    }
    echo '</tbody></table>';
}

    public function getsearchTotalRecords()
    {
        $sql = "SELECT COUNT(*) as total FROM pfa_search_history";
        $row = $this->dbF->getRow($sql);
        return isset($row['total']) ? (int)$row['total'] : 0;
    }
    
    public function search($searchTerm, $searchType = 'name', $options = [])
    {
    $searchTerm = trim((string)$searchTerm);

    if ($searchTerm === '') {
        return ['success' => false, 'error' => 'Search term is required'];
    }

    // defaults
    $options = array_merge([
        'min_score'   => 60,
        'max_results' => 20,
        'pool_limit'  => 500
    ], $options);

    switch ($searchType) {
        case 'name':
            return $this->searchByName($searchTerm, $options);

        case 'full_name':
            return $this->searchByFullName($searchTerm, $options);

        case 'nationality':
            return $this->searchByNationality($searchTerm, $options);

        case 'all':
            return $this->searchAll($searchTerm, $options);

        default:
            return ['success' => false, 'error' => 'Invalid search type'];
    }
}

    private function searchByName($searchTerm, $options)
    {
        $term = $this->sqlLikeSafe($searchTerm);
        $soundex = soundex($searchTerm);
        $limit = (int)$options['pool_limit'];
    
        $sql = "SELECT
                    id, external_id, first_name, middle_name, surname, single_string_name,
                    nationality, date_of_birth, active_status, deceased
                FROM pfa_records
                WHERE
                    first_name LIKE '%$term%' OR
                    surname LIKE '%$term%' OR
                    middle_name LIKE '%$term%' OR
                    single_string_name LIKE '%$term%' OR
                    SOUNDEX(first_name) = '$soundex' OR
                    SOUNDEX(surname) = '$soundex'
                LIMIT $limit";
    
        $candidates = $this->dbF->getRows($sql);
    
        $results = $this->scoreCandidates($searchTerm, $candidates, $options, 'name');
    
        return [
            'success'          => true,
            'search_term'      => $searchTerm,
            'search_type'      => 'name',
            'total_candidates' => count($candidates),
            'matched_results'  => count($results),
            'results'          => $results
        ];
    }

    private function searchByFullName($searchTerm, $options)
    {
        $term = $this->sqlLikeSafe($searchTerm);
        $parts = $this->parseNameParts($searchTerm);
        $limit = (int)$options['pool_limit'];
    
        $sql = "SELECT
                    id, external_id, first_name, middle_name, surname, single_string_name,
                    nationality, date_of_birth, active_status, deceased
                FROM pfa_records
                WHERE single_string_name LIKE '%$term%'";
    
        if (!empty($parts['first'])) {
            $first = $this->sqlLikeSafe($parts['first']);
            $sql .= " OR first_name LIKE '%$first%'";
        }
        if (!empty($parts['last'])) {
            $last = $this->sqlLikeSafe($parts['last']);
            $sql .= " OR surname LIKE '%$last%'";
        }
    
        $sql .= " LIMIT $limit";
    
        $candidates = $this->dbF->getRows($sql);
    
        $results = $this->scoreCandidates($searchTerm, $candidates, $options, 'full_name');
    
        return [
            'success'          => true,
            'search_term'      => $searchTerm,
            'search_type'      => 'full_name',
            'parsed_name'      => $parts,
            'total_candidates' => count($candidates),
            'matched_results'  => count($results),
            'results'          => $results
        ];
    }

    private function searchByNationality($searchTerm, $options)
    {
        $term = $this->sqlLikeSafe($searchTerm);
        $maxResults = (int)$options['max_results'];
    
        $sql = "SELECT
                    id, external_id, first_name, middle_name, surname, single_string_name,
                    nationality, date_of_birth, active_status, deceased
                FROM pfa_records
                WHERE nationality LIKE '%$term%'
                LIMIT $maxResults";
    
        $rows = $this->dbF->getRows($sql);
    
        // Add a simple score field so output format stays same
        $results = [];
        foreach ($rows as $r) {
            $r['match_score'] = 100;
            $r['match_confidence'] = 'Exact Match';
            $r['matched_fields'] = ['Nationality'];
            $results[] = $r;
        }
    
        return [
            'success'         => true,
            'search_term'     => $searchTerm,
            'search_type'     => 'nationality',
            'matched_results' => count($results),
            'results'         => $results
        ];
    }

    private function searchAll($searchTerm, $options)
    {
        $term = $this->sqlLikeSafe($searchTerm);
        $limit = (int)$options['pool_limit'];
    
        $sql = "SELECT
                    id, external_id, first_name, middle_name, surname, single_string_name,
                    nationality, date_of_birth, active_status, deceased, occupation, address
                FROM pfa_records
                WHERE
                    first_name LIKE '%$term%' OR
                    middle_name LIKE '%$term%' OR
                    surname LIKE '%$term%' OR
                    single_string_name LIKE '%$term%' OR
                    nationality LIKE '%$term%' OR
                    occupation LIKE '%$term%' OR
                    address LIKE '%$term%'
                LIMIT $limit";
    
        $candidates = $this->dbF->getRows($sql);
    
        $results = $this->scoreCandidates($searchTerm, $candidates, $options, 'all');
    
        return [
            'success'          => true,
            'search_term'      => $searchTerm,
            'search_type'      => 'all',
            'total_candidates' => count($candidates),
            'matched_results'  => count($results),
            'results'          => $results
        ];
    }

    private function sqlLikeSafe($str)
    {
        $str = (string)$str;
        $str = str_replace(["\\", "%", "_"], ["\\\\", "\\%", "\\_"], $str);
        $str = str_replace(["'"], ["\\'"], $str);
        return $str;
    }

    private function parseNameParts($name)
    {
        $name = trim(preg_replace('/\s+/', ' ', (string)$name));
        $parts = $name === '' ? [] : explode(' ', $name);
    
        return [
            'first' => $parts[0] ?? '',
            'last'  => count($parts) > 1 ? $parts[count($parts) - 1] : ''
        ];
    }
    
    private function scoreCandidates($searchTerm, $candidates, $options, $mode)
    {
        $minScore = (int)$options['min_score'];
        $maxResults = (int)$options['max_results'];
    
        $needle = $this->normalizeText($searchTerm);
    
        $scored = [];
    
        foreach ($candidates as $r) {
            $first = (string)($r['first_name'] ?? '');
            $mid   = (string)($r['middle_name'] ?? '');
            $last  = (string)($r['surname'] ?? '');
            $full  = trim($first . ' ' . $mid . ' ' . $last);
            $single = (string)($r['single_string_name'] ?? '');
            $nat   = (string)($r['nationality'] ?? '');
    
            // Decide what to compare based on mode
            if ($mode === 'name') {
                $hay = $this->normalizeText($first . ' ' . $last . ' ' . $single);
            } elseif ($mode === 'full_name') {
                $hay = $this->normalizeText($full . ' ' . $single);
            } elseif ($mode === 'all') {
                $hay = $this->normalizeText($full . ' ' . $single . ' ' . $nat);
            } else {
                $hay = $this->normalizeText($full);
            }
    
            $score = $this->similarityScore($needle, $hay);
    
            if ($score < $minScore) continue;
    
            $matchedFields = [];
            if ($first !== '' && stripos($first, $searchTerm) !== false) $matchedFields[] = 'First Name';
            if ($mid   !== '' && stripos($mid,   $searchTerm) !== false) $matchedFields[] = 'Middle Name';
            if ($last  !== '' && stripos($last,  $searchTerm) !== false) $matchedFields[] = 'Surname';
            if ($single!== '' && stripos($single,$searchTerm) !== false) $matchedFields[] = 'Full Name';
            if ($nat   !== '' && stripos($nat,   $searchTerm) !== false) $matchedFields[] = 'Nationality';
    
            $r['match_score'] = $score;
            $r['match_confidence'] = ($score >= 95 ? 'Exact Match' : ($score >= 75 ? 'Medium' : 'Low'));
            $r['matched_fields'] = $matchedFields;
            $scored[] = $r;
        }
    
        usort($scored, function($a, $b){
            return ($b['match_score'] <=> $a['match_score']);
        });
    
        return array_slice($scored, 0, $maxResults);
    }

    private function normalizeText($s)
    {
        $s = mb_strtolower(trim((string)$s), 'UTF-8');
        $s = preg_replace('/\s+/', ' ', $s);
        return $s;
    }
    
    private function similarityScore($a, $b)
    {
        if ($a === '' || $b === '') return 0;
        if (strpos($b, $a) !== false) return 100;
    
        similar_text($a, $b, $pct);
        return (int)round($pct);
    }






    public function leftClientsView()
    {
        $sql = "SELECT * FROM `accounts_user` WHERE `status` = ? AND `acc_type` = ? ORDER BY `acc_id` DESC";
        $clients = $this->dbF->getRows($sql, [0, 4]);

        echo '<table id="leftClientsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Country</th>
                <th>Status</th>
                <th class="noExport">Photo</th>
                <th>Date Created</th>
                <th class="noExport">Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($clients as $client) {
            $userId = $client["acc_id"];
            $name = $client["acc_name"];
            $email = $client["acc_email"];
            $image = empty($client["acc_image"]) ? WEB_URL . '/webImages/avatars/default.png' : WEB_URL . '/images/' . $client["acc_image"];
            $phone = $client['acc_phone'];
            $date = date('d-M-Y H:i A', strtotime($client["acc_created"]));

            $userDetail = $this->productClass->getUserDetailsById($userId);

            $country = $this->webClass->webUserInfoArray($userDetail, 'country');
            $clientStatus = $this->webClass->webUserInfoArray($userDetail, 'clientStatus');

            $encodedId = $this->functions->encode($userId);

            echo '<tr>';
            echo "<td>$name</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$country</td>";
            echo "<td>$clientStatus</td>";
            echo "<td><a href='$image' target='_blank'><img src='$image' alt='$name' loading='lazy' width='45' height='45'></a></td>";
            echo "<td>$date</td>";
            echo "<td>
                    <div class='btn-group'>
                        <a href='clientedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function designationView()
    {
        $sql = "SELECT * FROM `designations` WHERE `publish` = 1 ORDER BY `id` ASC";
        $designations = $this->dbF->getRows($sql);

        echo '<table id="designationsTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Designations</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($designations as $designation) {
            $designationId = $designation["id"];
            $designationTitle = $designation["designation"];
            $timestamp = date('d-M-Y H:i A', strtotime($designation["timestamp"]));

            echo '<tr>';
            echo "<td>$designationId</td>";
            echo "<td>$designationTitle</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$designationId' onclick='deleteDesignation(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='designationedit?id=$designationId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }
    



    public function designationDraft()
    {
        $sql = "SELECT * FROM `designations` WHERE publish = 0 ORDER BY `id` ASC";
        $designations = $this->dbF->getRows($sql);

        echo '<table id="designationsDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Designations</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($designations as $designation) {
            $designationId = $designation["id"];
            $designationTitle = $designation["designation"];
            $timestamp = date('d-M-Y H:i A', strtotime($designation["timestamp"]));

            echo '<tr>';
            echo "<td>$designationId</td>";
            echo "<td>$designationTitle</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$designationId' onclick='deleteDesignation(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='designationedit?id=$designationId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function staffView()
    {
        $sql = "SELECT s.id, au.acc_name, GROUP_CONCAT(d.designation SEPARATOR ', ') AS designations, s.checkintime, s.checkouttime, s.salary, s.timestamp FROM staffs s JOIN accounts_user au ON au.acc_id = s.userId LEFT JOIN staff_designations sd ON sd.staff_id = s.id LEFT JOIN designations d ON d.id = sd.designation_id GROUP BY s.id ORDER BY s.id DESC";
        $staffs = $this->dbF->getRows($sql);

        echo '<table id="staffsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Name</th>
                <th>Designation(s)</th>
                <th>Check-In Time</th>
                <th>Check-Out Time</th>
                <th>Salary</th>
                <th>Timestamp</th>
                <th class="noExport">Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($staffs as $staff) {
            $staffId = $this->functions->encode($staff["id"]);
            $name = $staff["acc_name"];
            $designations = $staff["designations"] ?? '-';
            $checkInTime = date("h:i A", strtotime($staff["checkintime"]));
            $checkOutTime = date("h:i A", strtotime($staff["checkouttime"]));
            $salary = $staff["salary"];
            $timestamp = date('d-M-Y H:i A', strtotime($staff["timestamp"]));

            echo '<tr>';
            echo "<td>$name</td>";
            echo "<td>$designations</td>";
            echo "<td>$checkInTime</td>";
            echo "<td>$checkOutTime</td>";
            echo "<td>$salary</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$staffId' onclick='deleteStaff(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='staffedit?id=$staffId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectStatusView(): void
    {
        $sql = "SELECT * FROM `project_statuses` WHERE `publish` = 1 ORDER BY `id` ASC";
        $statuses = $this->dbF->getRows($sql);

        echo '<table id="projectStatusTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Status</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($statuses as $status) {
            $statusId = $status["id"];
            $statusName = $status["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($status["timestamp"]));

            echo '<tr>';
            echo "<td>$statusId</td>";
            echo "<td>$statusName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$statusId' onclick='deleteProjectStatus(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projectstatusedit?id=$statusId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectStatusDraft()
    {
        $sql = "SELECT * FROM `project_statuses` WHERE `publish` = 0 ORDER BY `id` ASC";
        $statuses = $this->dbF->getRows($sql);

        echo '<table id="projectStatusDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Status</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($statuses as $status) {
            $statusId = $status["id"];
            $statusName = $status["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($status["timestamp"]));

            echo '<tr>';
            echo "<td>$statusId</td>";
            echo "<td>$statusName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$statusId' onclick='deleteProjectStatus(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projectstatusedit?id=$statusId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectTypeView()
    {
        $sql = "SELECT * FROM `project_types` WHERE `publish` = 1 ORDER BY `id` ASC";
        $types = $this->dbF->getRows($sql);

        echo '<table id="projectTypesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Type</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($types as $type) {
            $typeId = $type["id"];
            $typeName = $type["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($type["timestamp"]));

            echo '<tr>';
            echo "<td>$typeId</td>";
            echo "<td>$typeName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$typeId' onclick='deleteProjectType(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projecttypeedit?id=$typeId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectTypeDraft()
    {
        $sql = "SELECT * FROM `project_types` WHERE `publish` = 0 ORDER BY `id` ASC";
        $types = $this->dbF->getRows($sql);

        echo '<table id="projectTypesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Type</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($types as $type) {
            $typeId = $type["id"];
            $typeName = $type["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($type["timestamp"]));

            echo '<tr>';
            echo "<td>$typeId</td>";
            echo "<td>$typeName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$typeId' onclick='deleteProjectType(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projecttypeedit?id=$typeId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectCategoriesView()
    {
        $sql = "SELECT * FROM `project_categories` WHERE `publish` = 1 ORDER BY `id` ASC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="projectCategoriesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteProjectCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projectcategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectCategoriesDraft()
    {
        $sql = "SELECT * FROM `project_categories` WHERE `publish` = 0 ORDER BY `id` ASC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="projectCategoriesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteProjectCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='projectcategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function attendanceView()
    {
        $employees = $this->productClass->getStaffArray();

        $loggedInEmpId = $_SESSION["webUser"]["id"];

        $startOfWeek = new DateTime();
        $startOfWeek->modify('monday this week');
        $dates = [];
        for ($i = 0; $i < 6; $i++) {
            $dates[] = clone $startOfWeek;
            $startOfWeek->modify('+1 day');
        }

        $startDate = $dates[0]->format('Y-m-d');
        $endDate = end($dates)->format('Y-m-d');

        $sql = "SELECT `emp_id`, `date`, `in_time`, `out_time`, `status`, `msg` FROM `daily_reports` WHERE `date` BETWEEN ? AND ?";
        $rows = $this->dbF->getRows($sql, [$startDate, $endDate]);

        $attendanceData = [];
        foreach ($rows as $row) {
            $attendanceData[$row['emp_id']][$row['date']] = [
                'in' => $row['in_time'],
                'out' => $row['out_time'],
                'status' => $row['status']
            ];
        }

        $currentHour = (int) date('H');

        echo '<table id="attendanceTable" class="table mb-0">';
        echo '<thead><tr><th>Employee</th>';
        foreach ($dates as $date) {
            echo '<th>' . $date->format('D M j') . '</th>';
        }
        echo '</tr></thead><tbody>';

        foreach ($employees as $emp) {
            echo '<tr>';
            echo '<td><b>' . $emp["acc_name"] . '</b></td>';
            $empId = $emp['acc_id'];

            foreach ($dates as $date) {
                $d = $date->format('Y-m-d');

                if (isset($attendanceData[$empId][$d])) {
                    $att = $attendanceData[$empId][$d];
                    if ($att['status'] === 'Absent') {
                        echo '<td><span class="badge bg-danger">Absent</span></td>';
                    } elseif ($d === date('Y-m-d') && !empty($att['in']) && empty($att['out'])) {
                        echo '<td>';
                        echo 'IN: ' . date('h:i A', strtotime($att['in'])) . '<br>';
                        if ($loggedInEmpId == $empId && $currentHour >= 14) {
                            echo '<button type="button" data-bs-toggle="modal" data-bs-target="#checkOutModal" class="btn btn-sm btn-danger checkOutBtn mt-1" data-empid="' . $empId . '" data-date="' . $d . '">Check-Out</button>';
                        }
                        echo '</td>';
                    } elseif ($d === date('Y-m-d') && empty($att['in']) && empty($att['out'])) {
                        echo '<td>';
                        if ($loggedInEmpId == $empId) {
                            if ($currentHour < 14) {
                                echo '<button class="btn btn-sm btn-success checkInBtn" data-empid="' . $empId . '" data-date="' . $d . '">Check-In</button>';
                            } else {
                                echo '<button type="button" data-bs-toggle="modal" data-bs-target="#checkOutModal" class="btn btn-sm btn-danger checkOutBtn mt-1" data-empid="' . $empId . '" data-date="' . $d . '">Check-Out</button>';
                            }
                        }
                        echo '</td>';
                    } else {
                        echo '<td>';
                        echo 'IN: ' . (!empty($att['in']) ? date('h:i A', strtotime($att['in'])) : '-') . '<br>';
                        echo 'OUT: ' . (!empty($att['out']) ? date('h:i A', strtotime($att['out'])) : '-');
                        echo '</td>';
                    }
                } else {
                    if ($d === date('Y-m-d')) {
                        $empToday = isset($attendanceData[$empId][$d]) ? $attendanceData[$empId][$d] : null;

                        echo '<td>';
                        if (!$empToday || empty($empToday['in'])) {
                            if ($loggedInEmpId == $empId) {
                                if ($currentHour < 14) {
                                    echo '<button class="btn btn-sm btn-success checkInBtn" data-empid="' . $empId . '" data-date="' . $d . '">Check-In</button>';
                                } else {
                                    echo '<button type="button" data-bs-toggle="modal" data-bs-target="#checkOutModal" class="btn btn-sm btn-danger checkOutBtn mt-1" data-empid="' . $empId . '" data-date="' . $d . '">Check-Out</button>';
                                }
                            }
                        } elseif (!empty($empToday['in']) && empty($empToday['out'])) {
                            echo 'IN: ' . date('h:i A', strtotime($empToday['in'])) . '<br>';
                            if ($loggedInEmpId == $empId && $currentHour >= 14) {
                                echo '<button type="button" data-bs-toggle="modal" data-bs-target="#checkOutModal" class="btn btn-sm btn-danger checkOutBtn mt-1" data-empid="' . $empId . '" data-date="' . $d . '">Check-Out</button>';
                            }
                        } else {
                            echo 'IN: ' . date('h:i A', strtotime($empToday['in'])) . '<br>';
                            echo 'OUT: ' . date('h:i A', strtotime($empToday['out']));
                        }
                        echo '</td>';
                    } else {
                        echo '<td class="text-muted">-</td>';
                    }
                }
            }

            echo '</tr>';
        }

        echo '</tbody></table>';
    }

    public function openTicketsView()
    {
        $webUserType = $this->webClass->webUserType();
        $userId = $this->webClass->webUserId();

        if ($webUserType === 1 || $webUserType === 2) {
            $sql = "SELECT t.*, tc.category AS category_name FROM tickets t JOIN ticket_categories tc ON tc.id = t.category WHERE t.status = 'Open' ORDER BY t.id DESC";
        } elseif ($webUserType === 4) {
            $sql = "SELECT t.*, tc.category AS category_name FROM tickets t JOIN ticket_categories tc ON tc.id = t.category WHERE t.status = 'Open' AND t.client_id = '$userId' ORDER BY t.id DESC";
        } elseif ($webUserType === 5) {
            $sql = "SELECT t.*, tc.category AS category_name FROM tickets t JOIN ticket_categories tc ON tc.id = t.category WHERE t.status = 'Open' AND t.assigned_to = '$userId' ORDER BY t.id DESC";
        }

        $tickets = $this->dbF->getRows($sql);

        echo '<table id="openTicketsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th class="noExport">Actions</th>
                <th>Deadline</th>
                <th>Status</th>
                <th>Client</th>
                <th>Category</th>
                <th>Priority</th>
                <th>Assigned To</th>
                <th>Timestamp</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($tickets as $ticket) {
            $ticketId = $ticket["id"];
            $status = $ticket["status"];
            $priority = $ticket["priority"];

            $prioritySpan = '';
            if ($priority == "Normal") {
                $prioritySpan = "<span class='badge bg-success'>$priority</span>";
            } elseif ($priority == "Urgent") {
                $prioritySpan = "<span class='badge bg-info'>$priority</span>";
            }

            $category = $ticket["category_name"];
            $description = $ticket["description"];
            $deadline = date('d-M-Y', strtotime($ticket["deadline"]));
            $timestamp = date('d-M-Y H:i A', strtotime($ticket["timestamp"]));

            $clientName = $this->functions->webUserName($ticket["client_id"], 'acc_name');
            $employeeName = $this->functions->webUserName($ticket["assigned_to"], 'acc_name');
            $encodedId = $this->functions->encode($ticketId);

            echo '<tr>';
            echo "<td>
                    <div class='btn-group'>
                        <a href='ticketedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                        <button type='button' data-id='$ticketId' onclick=\"addNote(this, 'ticket');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>note_add</i></button>
                        <button type='button' data-id='$ticketId' data-desc='$description' onclick=\"viewNotes(this, 'ticket');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>message</i></button>
                    </div>
                </td>";
            echo "<td>$deadline</td>";
            echo "<td>$status</td>";
            echo "<td>$clientName</td>";
            echo "<td>$category</td>";
            echo "<td>$prioritySpan</td>";
            echo "<td>$employeeName</td>";
            echo "<td>$timestamp</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function closedTicketsView()
    {
        $webUserType = $this->webClass->webUserType();
        $clientId = $this->webClass->webUserId();

        if ($webUserType === 1) {
            $sql = "SELECT t.*, tc.category AS category_name FROM tickets t JOIN ticket_categories tc ON tc.id = t.category WHERE t.status = 'Closed' ORDER BY t.id DESC";
        } elseif ($webUserType === 4) {
            $sql = "SELECT t.*, tc.category AS category_name FROM tickets t JOIN ticket_categories tc ON tc.id = t.category WHERE t.status = 'Closed' AND t.client_id = '$clientId' ORDER BY t.id DESC";
        }
        $tickets = $this->dbF->getRows($sql);

        echo '<table id="closedTicketsTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th class="noExport">Actions</th>
                <th>Deadline</th>
                <th>Status</th>
                <th>Client</th>
                <th>Category</th>
                <th>Priority</th>
                <th>Assigned To</th>
                <th>Timestamp</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($tickets as $ticket) {
            $ticketId = $ticket["id"];
            $status = $ticket["status"];
            $priority = $ticket["priority"];

            $prioritySpan = '';
            if ($priority == "Normal") {
                $prioritySpan = "<span class='badge bg-success'>$priority</span>";
            } elseif ($priority == "Urgent") {
                $prioritySpan = "<span class='badge bg-info'>$priority</span>";
            }

            $category = $ticket["category_name"];
            $description = $ticket["description"];
            $deadline = date('d-M-Y', strtotime($ticket["deadline"]));
            $timestamp = date('d-M-Y H:i A', strtotime($ticket["timestamp"]));

            $clientName = $this->functions->webUserName($ticket["client_id"], 'acc_name');
            $employeeName = $this->functions->webUserName($ticket["assigned_to"], 'acc_name');
            $encodedId = $this->functions->encode($ticketId);

            echo '<tr>';
            echo "<td>
                    <div class='btn-group'>
                        <a href='ticketedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                        <button type='button' data-id='$ticketId' onclick=\"addNote(this, 'ticket');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>note_add</i></button>
                        <button type='button' data-id='$ticketId' data-desc='$description' onclick=\"viewNotes(this, 'ticket');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>message</i></button>
                    </div>
                </td>";
            echo "<td>$deadline</td>";
            echo "<td>$status</td>";
            echo "<td>$clientName</td>";
            echo "<td>$category</td>";
            echo "<td>$prioritySpan</td>";
            echo "<td>$employeeName</td>";
            echo "<td>$timestamp</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function inquiriesView()
    {
        $webUserType = $this->webClass->webUserType();
        $clientId = $this->webClass->webUserId();
        if ($webUserType === 1) {
            $sql = "SELECT * FROM `inquiries` ORDER BY `id` DESC";
        } elseif ($webUserType === 3) {
            $sql = "SELECT * FROM `inquiries` WHERE `user_id` = '$clientId' ORDER BY `id` DESC";
        }

        $inquiries = $this->dbF->getRows($sql);


        echo '<table id="inquiriesTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Name</th>
                <th>Company Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Services</th>
                <th>Message</th>
                <th>Timestamp</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($inquiries as $inquiry) {
            $name = $inquiry["name"];
            $companyName = $inquiry["company_name"];
            $email = $inquiry["email"];
            $phone = $inquiry["phone"];
            $services = $inquiry["services"];
            $message = $inquiry["message"];
            $timestamp = $inquiry["timestamp"];

            echo '<tr>';
            echo "<td>$name</td>";
            echo "<td>$companyName</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$services</td>";
            echo "<td>$message</td>";
            echo "<td>$timestamp</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function servicesView()
    {
        $sql = "SELECT * FROM `services` WHERE `publish` = 1 ORDER BY `id` ASC";
        $services = $this->dbF->getRows($sql);

        echo '<table id="servicesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Service Name</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($services as $service) {
            $serviceId = $service["id"];
            $name = $service["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($service["timestamp"]));

            echo '<tr>';
            echo "<td>$serviceId</td>";
            echo "<td>$name</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$serviceId' onclick='deleteService(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='serviceedit?id=$serviceId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function servicesDraft()
    {
        $sql = "SELECT * FROM `services` WHERE `publish` = 0 ORDER BY `id` ASC";
        $services = $this->dbF->getRows($sql);

        echo '<table id="servicesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Service Name</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($services as $service) {
            $serviceId = $service["id"];
            $name = $service["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($service["timestamp"]));

            echo '<tr>';
            echo "<td>$serviceId</td>";
            echo "<td>$name</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$serviceId' onclick='deleteService(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='serviceedit?id=$serviceId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function expensesView()
    {
        $sql = "SELECT de.*, ec.category AS category_name  FROM daily_expenses de JOIN expense_categories ec ON ec.id = de.category ORDER BY de.id DESC";
        $expenses = $this->dbF->getRows($sql);

        echo '<table id="expensesTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Title</th>
                <th>Category</th>
                <th>Paid To</th>
                <th>Amount</th>
                <th>Date</th>
                <th>Timestamp</th>
                <th class="noExport">Actions</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($expenses as $expense) {
            $expenseId = $expense["id"];
            $title = $expense["title"];
            $category = $expense["category_name"];
            $paidTo = $expense["paid_to"];
            $amount = $expense["amount"];
            $date = date('d-M-Y', strtotime($expense["date"]));
            $timestamp = date('d-M-Y H:i A', strtotime($expense["timestamp"]));

            echo '<tr>';
            echo "<td>$title</td>";
            echo "<td>$category</td>";
            echo "<td>$paidTo</td>";
            echo "<td>$amount</td>";
            echo "<td>$date</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$expenseId' onclick='deleteDailyExpense(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='expenseedit?id=$expenseId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function ticketCategoriesView()
    {
        $sql = "SELECT * FROM `ticket_categories` WHERE `publish` = 1 ORDER BY `id` ASC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="ticketCategoriesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteTicketCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='ticketcategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function ticketCategoriesDraft()
    {
        $sql = "SELECT * FROM `ticket_categories` WHERE `publish` = 0 ORDER BY `id` DESC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="ticketCategoriesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteTicketCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='ticketcategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function expenseCategoriesView()
    {
        $sql = "SELECT * FROM `expense_categories` WHERE `publish` = 1 ORDER BY `id` ASC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="expenseCategoriesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteExpenseCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='expensecategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function expenseCategoriesDraft()
    {
        $sql = "SELECT * FROM `expense_categories` WHERE `publish` = 0 ORDER BY `id` ASC";
        $categories = $this->dbF->getRows($sql);

        echo '<table id="expenseCategoriesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Category</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($categories as $category) {
            $categoryId = $category["id"];
            $categoryName = $category["category"];
            $timestamp = date('d-M-Y H:i A', strtotime($category["timestamp"]));

            echo '<tr>';
            echo "<td>$categoryId</td>";
            echo "<td>$categoryName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$categoryId' onclick='deleteExpenseCategory(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='expensecategoriesedit?id=$categoryId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function invoiceStatusesView()
    {
        $sql = "SELECT * FROM `invoice_statuses` WHERE `publish` = 1 ORDER BY `id` ASC";
        $statuses = $this->dbF->getRows($sql);

        echo '<table id="invoiceStatusesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Status</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($statuses as $status) {
            $statusId = $status["id"];
            $statusName = $status["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($status["timestamp"]));

            echo '<tr>';
            echo "<td>$statusId</td>";
            echo "<td>$statusName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$statusId' onclick='deleteInvoiceStatus(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='invoicestatusedit?id=$statusId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function invoiceStatusesDraft()
    {
        $sql = "SELECT * FROM `invoice_statuses` WHERE `publish` = 0 ORDER BY `id` DESC";
        $statuses = $this->dbF->getRows($sql);

        echo '<table id="invoiceStatusesDraftTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>Status</th>
                <th>Timestamp</th>
                <th>Actions</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($statuses as $status) {
            $statusId = $status["id"];
            $statusName = $status["name"];
            $timestamp = date('d-M-Y H:i A', strtotime($status["timestamp"]));

            echo '<tr>';
            echo "<td>$statusId</td>";
            echo "<td>$statusName</td>";
            echo "<td>$timestamp</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$statusId' onclick='deleteInvoiceStatus(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                        <a href='invoicestatusedit?id=$statusId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function invoicesView()
    {
        $sql = "SELECT i.*, ac.acc_name, id.pdf_file, id.docs, ins.name AS invoice_status FROM invoices i JOIN accounts_user ac ON ac.acc_id = i.client_id JOIN invoice_statuses ins ON ins.id = i.status LEFT JOIN invoice_docs id ON id.invoice_id = i.id ORDER BY i.id DESC";
        $invoices = $this->dbF->getRows($sql);

        echo '<table id="invoiceTable" class="dataTableInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th class="noExport">Actions</th>
                <th>Invoice No</th>
                <th>Company</th>
                <th>Client Name</th>
                <th>Invoice Date</th>
                <th>Due Date</th>
                <th>Expiry Date</th>
                <th>Invoice For</th>
                <th>Description</th>
                <th>Type</th>
                <th>Amount</th>
                <th>Received</th>
                <th>Status</th>
                <th class="noExport">PDF</th>
                <th class="noExport">Other Docs</th>
                <th>Date Created</th>
                <th>Timestamp</th>
            </tr>
        </thead>                
        <tbody>';

        foreach ($invoices as $invoice) {
            $invId = $invoice["id"];
            $invNo = !empty($invoice["invoice_number"]) ? $invoice["invoice_number"] : '-';
            $company = $invoice["client_company"];
            $clientName = $invoice["acc_name"];
            $invDate = ($invoice['invoice_date'] === '0000-00-00' || empty($invoice['invoice_date'])) ? '-' : date('d-M-Y', strtotime($invoice['invoice_date']));
            $invDueDate = date('d-M-Y', strtotime($invoice["due_date"]));
            $invExpDate = date('d-M-Y', strtotime($invoice["expiry_date"]));
            $invFor = $invoice["invoice_for"];
            $invDesc = !empty($invoice["description"]) ? $invoice["description"] : '-';
            $invTotalBilledAmount = $invoice["total_billed_amount"];
            $invRcvdAmount = $invoice["received_amount"];
            $invStatus = $invoice["invoice_status"];
            $createdAt = date('d-M-Y', strtotime($invoice["created_at"]));
            $timestamp = date('d-M-Y H:i A', strtotime($invoice["timestamp"]));

            $invType = '';
            if (isset($invoice['invoice_type'])) {
                if ($invoice['invoice_type'] == 'sales_tax') {
                    $invType = 'Incl. Tax';
                } else {
                    $invType = 'Excl. Tax';
                }
            }

            if (!empty($invoice["pdf_file"])) {
                $pdfLink = "<a class='btn btn-sm btn-dark d-flex' href='" . WEB_URL . '/images/' . $invoice["pdf_file"] . "'><i class='material-icons-outlined'>cloud_download</i></a>";
            } else {
                $pdfLink = '';
            }

            $docsArray = [];
            if (!empty($invoice["docs"])) {
                $allDocs = json_decode($invoice["docs"]);
                foreach ($allDocs as $doc) {
                    $docsArray[] = "<a class='btn btn-sm btn-dark d-flex' href='" . WEB_URL . '/images/' . $doc . "'><i class='material-icons-outlined'>cloud_download</i></a>";
                }
            }

            $encodedId = $this->functions->encode($invId);

            echo '<tr>';
            echo "<td>
                <div class='btn-group'>
                    <a href='invoiceedit?id=$encodedId' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></a>
                    <a href='invoicePrint?id=$encodedId' target='_blank' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>print</i></a>
                    <button type='button' data-id='$invId' onclick=\"addNote(this, 'invoice');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>note_add</i></button>
                    <button type='button' data-id='$invId' onclick=\"viewNotes(this, 'invoice');\" class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>message</i></button>
                </div>
            </td>";
            echo "<td>$invNo</td>";
            echo "<td>$company</td>";
            echo "<td>$clientName</td>";
            echo "<td>$invDate</td>";
            echo "<td>$invDueDate</td>";
            echo "<td>$invExpDate</td>";
            echo "<td>$invFor</td>";
            echo "<td>$invDesc</td>";
            echo "<td>$invType</td>";
            echo "<td>$invTotalBilledAmount</td>";
            echo "<td>$invRcvdAmount</td>";
            echo "<td>$invStatus</td>";
            echo "<td>$pdfLink</td>";
            echo "<td><div class='btn-group'>";
            foreach ($docsArray as $file) {
                echo $file;
            }
            echo "</div></td>";
            echo "<td>$createdAt</td>";
            echo "<td>$timestamp</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function logsView()
    {
        $sql = "SELECT * FROM `activity_log` ORDER BY `log_id` DESC";
        $logs = $this->dbF->getRows($sql);

        echo '<table id="logsTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Log Title</th>
                <th>Reference Name</th>
                <th>Reference ID</th>
                <th>Reference User</th>
                <th>Description</th>
                <th>IP</th>
                <th>Browser</th>
                <th>Timestamp</th>
            </tr>
        </thead>                
        <tbody>';
        foreach ($logs as $log) {
            $logTitle = $log["log_title"];
            $refName = $log["ref_name"];
            $refId = $log["ref_id"];
            $refUser = $log["ref_user"];
            $refDesc = $log["log_desc"];
            $logIP = $log["log_ip"];
            $logBrowser = $log["log_browser"];
            $timestamp = date('d-M-Y H:i A', strtotime($log["log_time"]));

            echo '<tr>';
            echo "<td>$logTitle</td>";
            echo "<td>$refName</td>";
            echo "<td>$refId</td>";
            echo "<td>$refUser</td>";
            echo "<td>$refDesc</td>";
            echo "<td>$logIP</td>";
            echo "<td>$logBrowser</td>";
            echo "<td>$timestamp</td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function projectsView()
    {
        $sql = "SELECT * FROM `projects` ORDER BY `sort` ASC";
        $projects = $this->dbF->getRows($sql);

        echo '<div id="projectsGrid" class="list-group list-group-flush">';

        if (!empty($projects)) {
            foreach ($projects as $project) {
                $projectId = $project["id"];
                $projTitle = $project["project_title"];
                $country = $project["country"];

                echo "<div class='list-group-item px-0 py-2 bg-transparent' data-id='$projectId'>
                        <div class='d-flex justify-content-between align-items-center'>
                            <div>
                                $projTitle <span class='badge rounded-pill bg-grd-success mx-2'>$country</span>
                            </div>
                            <div class='btn-group'>
                                <button type='button' class='btn bt-sm btn-outline-success'>Full View</button>
                                <button type='button' class='btn bt-sm btn-outline-success'>Status</button>
                                <a href='projectedit?id=$projectId' class='btn bt-sm btn-outline-success'>Edit</a>
                            </div>
                        </div>
                    </div>";
            }
        } else {
            echo "<div class='list-group-item px-0 py-2 bg-transparent'>
                    <div class='d-flex justify-content-center align-items-center'>
                        <h5>No Projects to Show</h5>
                    </div>
            </div>";
        }
        echo '</div>';
    }

    public function closedProjectsView()
    {
        $sql = "SELECT * FROM `projects` WHERE `status_id` = ? ORDER BY `sort` ASC";
        $projects = $this->dbF->getRows($sql, [9]);

        echo '<div id="projectsGrid" class="list-group list-group-flush">';

        if (!empty($projects)) {
            foreach ($projects as $project) {
                $projectId = $project["id"];
                $projTitle = $project["project_title"];
                $country = $project["country"];

                echo "<div class='list-group-item px-0 py-2 bg-transparent' data-id='$projectId'>
                        <div class='d-flex justify-content-between align-items-center'>
                            <div>
                                $projTitle <span class='badge rounded-pill bg-grd-success mx-2'>$country</span>
                            </div>
                            <div class='btn-group'>
                                <button type='button' class='btn bt-sm btn-outline-success'>Full View</button>
                                <button type='button' class='btn bt-sm btn-outline-success'>Status</button>
                                <a href='projectedit?id=$projectId' class='btn bt-sm btn-outline-success'>Edit</a>
                            </div>
                        </div>
                    </div>";
            }
        } else {
            echo "<div class='list-group-item px-0 py-2 bg-transparent'>
                    <div class='d-flex justify-content-center align-items-center'>
                        <h5>No Projects to Show</h5>
                    </div>
            </div>";
        }

        echo '</div>';
    }

    public function calendarEvents(): string
    {
        $sql = "SELECT `id`, `title`, `category`, `status`, `due_date`, `detail` FROM `events`";
        $rows = $this->dbF->getRows($sql);

        $events = [];

        foreach ($rows as $row) {
            $color = match (true) {
                $row['category'] === 'Reminder' => '#FFC107',
                $row['status'] === 'Pending' => '#02C27A',
                $row['status'] === 'Complete' => '#6C757D',
                default => '#6C757D',
            };

            $eventId = $row["id"];

            $events[] = [
                'href' => '#',
                'id' => $row['id'],
                'title' => $row['title'],
                'category' => $row['category'],
                'status' => $row['status'],
                'detail' => $row['detail'],
                'color' => $color,
                'start' => date('Y-m-d', strtotime($row['due_date'])),
                'due_date' => date('Y-m-d', strtotime($row['due_date'])),
                'click' => "editEventForm(this, '{$eventId}')",
            ];
        }

        return json_encode($events, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
    }

    public function renderEvents($events)
    {
        if (!empty($events)) {
            echo "<div class='row g-3'>";
            foreach ($events as $event) {
                $id = $event["id"];
                $title = $event["title"];
                $dueDate = date('d-M-Y', strtotime($event["due_date"]));
                echo "<div class='col-4 px-2 event-box' data-title='" . strtolower($title) . "' data-user='" . $event['user_id'] . "'>";
                echo "<div class='border border-2 px-2 py-1'>";
                echo "<div class='d-flex justify-content-between align-items-center'>";
                echo "<div class='me-4'>$title ($dueDate)</div>";
                echo "<div class='btn-group'>";
                echo "<button type='button' onclick='editEventForm(this, $id)' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>edit_note</i></button>";
                echo "<button type='button' data-id='$id' onclick='deleteEvent(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
            }
            echo "</div>";
        }
    }

    public function saturdaysView()
    {
        $sql = "SELECT * FROM `saturday_off` ORDER BY `date` DESC";
        $saturdays = $this->dbF->getRows($sql);

        echo '<table id="saturdaysTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Date</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($saturdays as $saturday) {
            $dateId = $saturday["id"];
            $date = date('d-M-Y', strtotime($saturday["date"]));

            echo '<tr>';
            echo "<td>$date</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$dateId' onclick='deleteSaturday(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function waTemplatesList()
    {
        $sql = "SELECT `id`, `name`, `body`, `created_at` FROM `wa_templates` ORDER BY `id` DESC";
        $templates = $this->dbF->getRows($sql);

        echo '<table id="templatesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>Name</th>
                <th>Preview</th>
                <th>Created At</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($templates as $template) {
            $tplId = $template["id"];
            $name = $template["name"];
            $body = $template["body"];
            $date = date('d-M-Y H:i A', strtotime($template["created_at"]));

            echo '<tr>';
            echo "<td>$name</td>";
            echo "<td>" . nl2br(htmlspecialchars($body, ENT_QUOTES)) . "</td>";
            echo "<td>$date</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$tplId' onclick='deleteTpl(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function waRuleList()
    {
        $sql = "SELECT r.*, t.name AS template_name FROM wa_rules r LEFT JOIN wa_templates t ON t.id = r.template_id ORDER BY r.priority ASC, r.id DESC";
        $rules = $this->dbF->getRows($sql);

        echo '<table id="rulesTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Match</th>
                <th>Template</th>
                <th>Delay</th>
                <th>Priority</th>
                <th>Active</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($rules as $rule) {
            $ruleId = $rule["id"];
            $name = $rule["name"];
            $matchTxt = $rule["match_type"];
            if ($rule["match_type"] === 'keyword' && trim((string) $rule["match_value"]) !== '') {
                $matchTxt .= ': ' . htmlspecialchars($rule["match_value"]);
            }
            $tplName = $rule["template_name"];
            $sdDayMinutes = $rule["schedule_delay_minutes"];
            $priority = $rule["priority"];
            $active = ($rule["active"] == 1) ? 'Yes' : 'No';

            echo '<tr>';
            echo "<td>$ruleId</td>";
            echo "<td>$name</td>";
            echo "<td>$matchTxt</td>";
            echo "<td>$tplName</td>";
            echo "<td>$sdDayMinutes</td>";
            echo "<td>$priority</td>";
            echo "<td>$active</td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$ruleId' onclick='deleteRule(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }

    public function metaLeadsList()
    {
        $sql = "SELECT id, leadgen_id, page_id, form_id, full_name, email, phone, status, fb_created_time, ingested_at FROM meta_leads ORDER BY id DESC";
        $metaLeads = $this->dbF->getRows($sql);

        echo '<table id="metaLeadsTable" class="dataTableSInit table table-striped table-bordered" style="width:100%">';
        echo '<thead>
            <tr>
                <th>ID</th>
                <th>FB Created</th>
                <th>Full Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Page ID</th>
                <th>Form ID</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>';

        foreach ($metaLeads as $lead) {
            $leadId = $lead['id'];
            $fbCreated = $lead['fb_created_time'] ? : '';
            $fullName = $lead['full_name'];
            $email = $lead['email'];
            $phone = $lead['phone'];
            $pageId = $lead['page_id'];
            $formId = $lead['form_id'];
            $status = $lead['status'];
            
            echo '<tr>';
            echo "<td>$leadId</td>";
            echo "<td>$fbCreated</td>";
            echo "<td>$fullName</td>";
            echo "<td>$email</td>";
            echo "<td>$phone</td>";
            echo "<td>$pageId</td>";
            echo "<td>$formId</td>";
            echo "<td><span class='badge bg-secondary'>$status</span></td>";
            echo "<td>
                    <div class='btn-group'>
                        <button type='button' data-id='$leadId' onclick='viewMetaLead(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>visibility</i></button>
                        <button type='button' data-id='$leadId' onclick='deleteMetaLead(this);' class='btn btn-sm btn-dark d-flex'><i class='material-icons-outlined'>delete</i></button>
                    </div>
                </td>";
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
    }
}
