<?php
ob_start(); // Add output buffering to prevent headers already sent errors

// Initialize variables outside try-catch to ensure they're available in template
$showCardView = false;
$isCardView = false;
$isMobile = false;
$QrTemplates = [];
$single = null;
$param_id = null;

try {
    session_start();
    require 'db.php';
    require_once 'include/auth/auth_functions.php';
    include 'include/helper_functions/data_request.php';
    include 'include/property_builder/qr_code/qr_code_template_functions.php';

    if (!currentUserHasAccess($pdo, 'property_builder', 'read')) {
        if (isset($_SESSION['userid'])) {
            echo "Access denied.";
            if (!headers_sent()) {
                header( "refresh:5;url=/dashboard.php" );
            }
        }else {
            if (!headers_sent()) {
                header("Location: /login.php");
            }
        }
        exit();
    }
    
    $param_id=isset($_GET['template_id']) ? $_GET['template_id'] : null;
    $QrTemplates=[];
    $single = null;
    if(!empty($param_id)){
        $param_id = trim($param_id);
        $single  = fetchDataSingle('qr_code_templates', ['id'=>$param_id]);
    }else {
        $editedQrTemplates = fetchData('qr_code_templates',['is_default' => null,'property_id' => $_SESSION['property']??' ']);
        $defaultQrTemplates = fetchData('qr_code_templates',['is_default' => 1]);
        $editedNames = array_column($editedQrTemplates, 'templateName');
        $FilteredQrTemplates = array_filter($defaultQrTemplates, function ($template) use ($editedNames) {
        return !in_array($template['templateName'], $editedNames);
        });
        $QrTemplates = array_merge($editedQrTemplates, $FilteredQrTemplates);
    }

    // Check user preferences for card/table view
    // Get user preferences from database
    $preferences = fetchData('app_settings', [
        'property_id' => $_SESSION['property'] ?? '',
        'userid' => $_SESSION['userid'] ?? ''
    ]);
    
    // Check if user prefers card view
    if (!empty($preferences) && isset($preferences[0]['is_card_view']) && $preferences[0]['is_card_view'] == 1) {
        $isCardView = true;
    }
    
    // Check if it's a mobile device
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $isMobile = preg_match('/(android|iphone|ipad|mobile|tablet)/i', $userAgent);
    
    $showCardView = $isMobile || $isCardView;
    
    // Debug: Uncomment the line below to see the values
    // echo "Debug: isCardView=" . ($isCardView ? 'true' : 'false') . ", isMobile=" . ($isMobile ? 'true' : 'false') . ", showCardView=" . ($showCardView ? 'true' : 'false') . "<br>";

} catch (\Throwable $th) {
    // throw $th;
}

?>


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Invisible Intercom</title>

    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="/css/all.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="/css/adminlte.min.css">
    <!-- For Modals -->
    <link rel="stylesheet" href="/css/bootstrap-4.min.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="/css/select2-bootstrap4.min.css">
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="/include/images/favicon.ico">
    <!-- jsGrid -->
    <link rel="stylesheet" href="/css/jsgrid.min.css">
    <link rel="stylesheet" href="/css/jsgrid-theme.min.css">

    <!-- Custom -->
    <link rel="stylesheet" href="/css/property-builder/qr_code.css">
    <link rel="stylesheet" href="css/dashboard.css">
    <link rel="stylesheet" href="/css/property-builder/image_editor.css">
    <!-- Qr code -->
    <script src="https://unpkg.com/@bitjson/qr-code@1.0.2/dist/qr-code.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/html-to-image@latest/dist/html-to-image.min.js"></script>

    <!-- image editor -->
    <link rel="stylesheet" href="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.css">
    <link rel="stylesheet" href="https://uicdn.toast.com/tui-color-picker/latest/tui-color-picker.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.6.0/fabric.min.js"></script>
    <script src="https://uicdn.toast.com/tui-color-picker/latest/tui-color-picker.js"></script>
    <script src="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.js"></script>

    <!-- CKEditor 4 CDN -->
    <!-- <script src="https://cdn.ckeditor.com/4.20.2/full/ckeditor.js"></script>
    <link rel="stylesheet" href="https://cdn.ckeditor.com/4.20.2/skins/moono-lisa/editor.css"> -->

    <!-- toast -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.6.0/fabric.min.js"></script>
    <script src="https://uicdn.toast.com/tui-color-picker/latest/tui-color-picker.js"></script>
    <script src="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.js"></script>
    <!-- Purify -->
    <script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>

    <!-- DataTables Library -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">

    <!-- Bootstrap Switch  -->
    <link rel="stylesheet" href="js/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css">

</head>

<body class="hold-transition sidebar-mini" id="body_body">

<style>
    .letter_layout_portrait {
        width: 816px; /* 8.5 inches */
        height: 1056px; /* 11 inches */
        background-color: white;
    }
</style>


    <div class="wrapper">

        <!-- Navbar -->
        <?php include 'shared/header.nav.php'; ?>
        <!-- /.navbar -->

        <!-- Modals Start-->
        <?php include 'shared/modal.php'; ?>
        <!-- End Modals -->

        <!-- Main Sidebar Container -->
        <aside class="main-sidebar" id="sidebar-con">
            <?php
            include 'shared/aside.nav.php'; ?>
            <!-- /.sidebar -->
        </aside>

        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <!-- Main content -->
            <div class="content">
                <div class="container-fluid">
                    <div class="py-3" id="display-div">
                        <div id="list_view">
                            <div class="d-flex justify-content-between align-items-center flex-wrap my-3">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-arrow-left pr-2" style="cursor:pointer" onclick="<?php echo empty($param_id) ? "window.location='/dashboard.php?tab=property_builder&active=6'" : "window.location='/qrCodeTemplates.php'"; ?>"></i>
                                </div>
                            </div>
                            
                            <div class="viewTemplate pt-3" id="viewTemplate" <?php echo empty($param_id) ? 'style="display: block;"' : 'style="display: none;"'; ?>>
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">QR Code Templates</h3>
                                        <!-- Search bar -->
                                        <?php if (!$showCardView): ?><div class="card-tools">
                                            <div class="input-group input-group-sm" style="width: 250px;">
                                                <input type="text" id="searchQrTemplateInput" onkeyup="searchTable('qrCodeTemplateDataTable', 'searchQrTemplateInput')" class="form-control float-right" placeholder="Search Template">
                                                <div class="input-group-append">
                                                    <button type="button" class="btn btn-default">
                                                        <i class="fas fa-search"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-card-toggle">
                                            <?php if ($showCardView): ?>
                                                <div id="QR_template_table_card">
                                                    <?php echo get_template_html_card($QrTemplates); ?>
                                                </div>
                                            <?php else: ?>
                                                <div id="QR_template_table_table">
                                                    <?php echo get_template_table_html($QrTemplates); ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div id="Template_edit_mode " <?php echo !empty($param_id) ? 'style="display: block;"' : 'style="display: none;"'; ?>>
                            <div id="Template_edit_mode_container" class="<?php echo get_page_class($single['templateName']); ?>">
                                <?php echo html_entity_decode(generate_qr_code_template($single['templateName'], $single['templateHtml'])); ?>
                            </div>
                            <div class="pt-4 text-right">
                                <button
                                    class="btn btn-primary"
                                    onclick="saveEditedTemplate(<?php echo (int)$single['id']; ?>, '<?php echo addslashes($single['templateName']); ?>')"
                                >
                                    Save
                                </button>
                            </div>
                        </div>
                        

                        <!-- View template Modal -->
                        <div class="modal fade" id="TemplatePreviewModal" tabindex="-1" role="dialog" aria-labelledby="addEditQrCode" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-area" role="document" style="min-height:90vh">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="addEditQrCode">Template</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <div id="TemplatePreviewContainer">
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Edit Modal -->
                        <div id="editModal" style="display:none; position:fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.4); z-index:9999; align-items:center; justify-content:center;">
                            <div style="background:#fff; padding:30px; border-radius:8px; min-width:340px; max-width:90vw;">
                            <h3 style="margin:0px; margin-bottom: 10px;">Edit Text</h3>
                            <input type="text" id="modalInput" style="width:100%; font-size:18px; margin-bottom:20px;">
                            <div style="text-align:right;">
                                <button class="btn btn-secondary" type="button" onclick="closeModal()">Cancel</button>
                                <button class="btn btn-primary" type="button" onclick="saveEdit()">Save</button>
                            </div>
                            </div>
                        </div>

                        <!-- Image Edit Modal -->
                        <div id="imageEditModal" style="display:none; position:fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.4); z-index:9999; align-items:center; justify-content:center;">
                            <div style="background:#fff; padding:30px; border-radius:8px; min-width:340px; max-width:90vw;">
                            <h3 style="margin:0px; margin-bottom: 10px;">Edit Image</h3>
                            <input type="file" id="imageInput" accept="image/*" style="width:100%; font-size:18px; margin-bottom:20px;">
                            <div style="text-align:right;">
                                <button class="btn btn-secondary" type="button" onclick="closeImageModal()">Cancel</button>
                                <button class="btn btn-primary" type="button" onclick="saveImageEdit()">Save</button>
                            </div>
                            </div>
                        </div>

                        <!-- Edit template Modal -->
                        <script>
                            let currentEditId = null;
                            let currentEditType = null;
                            
                            document.addEventListener('click', function(e) {
                                if (e.target.classList.contains('edit-icon')) {
                                    currentEditId = e.target.getAttribute('data-edit-id');
                                    currentEditType = e.target.getAttribute('data-edit-type');
                                    
                                    if (currentEditType === 'image') {
                                        // Handle image editing
                                        document.getElementById('imageEditModal').style.display = 'flex';
                                    } else {
                                        // Handle text editing
                                        const span = document.getElementById(currentEditId);
                                        let value = '';
                                        
                                        // First try to find the span with specific IDs
                                        let targetSpan = span.querySelector('span[id="welcome_home"], span[id="for_access_please_call"], span[id="phone_number"], span[id="or"], span[id="or_text"], span[id="scan_to_call"]');
                                        
                                        if (targetSpan) {
                                            // Get text from the span with ID
                                            value = targetSpan.textContent.trim();
                                        } else {
                                            // Fallback: look for strong, em, b, i, or span with style
                                            let target = span.querySelector('strong, em, b, i, span[style]');
                                            if (target) {
                                                value = target.textContent.trim();
                                            } else {
                                                // Final fallback: get the first text node
                                                for (let node of span.childNodes) {
                                                    if (node.nodeType === Node.TEXT_NODE) {
                                                        value = node.nodeValue.trim();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        
                                        document.getElementById('modalInput').value = value;
                                        document.getElementById('editModal').style.display = 'flex';
                                    }
                                }
                            });

                            function closeModal() {
                                document.getElementById('editModal').style.display = 'none';
                                currentEditId = null;
                                currentEditType = null;
                            }

                            function closeImageModal() {
                                document.getElementById('imageEditModal').style.display = 'none';
                                document.getElementById('imageInput').value = '';
                                currentEditId = null;
                                currentEditType = null;
                            }

                            function saveEdit() {
                                if (currentEditId) {
                                    const span = document.getElementById(currentEditId);
                                    const newValue = document.getElementById('modalInput').value;
                                    
                                    // First try to find the span with specific IDs
                                    let targetSpan = span.querySelector('span[id="welcome_home"], span[id="for_access_please_call"], span[id="phone_number"], span[id="or"], span[id="or_text"], span[id="scan_to_call"]');
                                    
                                    if (targetSpan) {
                                        // Update text in the span with ID
                                        targetSpan.textContent = newValue;
                                    } else {
                                        // Fallback: look for strong, em, b, i, or span with style
                                        let target = span.querySelector('strong, em, b, i, span[style]');
                                        if (target) {
                                            target.textContent = newValue;
                                        } else {
                                            // Final fallback: update the text node directly
                                            for (let node of span.childNodes) {
                                                if (node.nodeType === Node.TEXT_NODE) {
                                                    node.nodeValue = newValue;
                                                    break;
                                                }
                                            }
                                        }   
                                    }
                                }
                                closeModal();
                            }

                            async function saveImageEdit() {
                                if (currentEditId && currentEditType === 'image') {
                                    const fileInput = document.getElementById('imageInput');
                                    const file = fileInput.files[0];
                                    
                                    if (file) {
                                        const formData = new FormData();

                                        const container = document.getElementById(currentEditId);
                                        const img = container.querySelector('img');
                                        console.log("img", img);
                                        console.log("img src", img.src);
                                        const url = img.src;
                                        const parsedUrl = new URL(url);
                                        let pathValue = parsedUrl.searchParams.get('path');
                                        if (pathValue?.includes("/include")) {
                                            pathValue = '';
                                        }

                                        formData.append("qr_code_template_image", file);
                                        formData.append("previous_image_path",pathValue );
                                        formData.append("save_edited_qr_code_template", true);
                                        formData.append("property_id", sessionStorage.getItem("propertyId"));
                                        const imageUploaded = await uploadQrCodeTemplateImage(formData);
                                        console.log("imageUploaded", imageUploaded);

                                        if (imageUploaded) {
                                            // ✅ Find the <div> by ID and then find the <img> inside it
                                            const complete_image=`/shared/serve_image.php?path=${imageUploaded}&type=all_images`;
                                            const container = document.getElementById(currentEditId);
                                            if (container) {
                                                const img = container.querySelector('img');
                                                if (img) {
                                                    img.src = complete_image; // Use the uploaded URL from the server
                                                }
                                            }
                                            closeImageModal();
                                        }
                                    }
                                }
                                closeImageModal();
                            }


                            function uploadQrCodeTemplateImage(formData){
                                return new Promise((resolve, reject) => {
                                    $.ajax({
                                    url: "/include/property_builder/qr_code/qr_code_requests.php",
                                    type: "post",
                                    data: formData,
                                    processData: false,
                                    contentType: false,
                                    success: function (resp) {
                                        resolve(resp.data);
                                    },
                                    error: function (xhr, status, error) {
                                        if (xhr?.responseJSON?.error) reject(xhr?.responseJSON?.error);
                                        else reject(error);
                                    },
                                    });
                                });
                            }
                        </script>

                    </div>
                </div>
            </div>
            <!-- /.row -->
        </div>
        <!-- /.container-fluid -->
        <!-- Main Footer -->
        <?php include 'shared/footer.php'; ?>
    </div>

    <!-- ./wrapper -->

    <!-- REQUIRED SCRIPTS -->

    <!-- jQuery -->
    <script src="/js/jquery.min.js"></script>
    <!-- Bootstrap 4 -->
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="js/dashboard.js"></script>
    <!-- AdminLTE App -->
    <script src="/js/adminlte.min.js"></script>
    <script src="/js/sessionRedirection.js"></script>
    <!-- Responsive Extension JS -->
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="/js/settings/qrCodeTemplates.js"></script>
    <!-- Bootstrap switch -->
    <script src="js/bootstrap-switch/js/bootstrap-switch.min.js"></script>
    <script src="/js/settings/preferences.js"></script>
</body>

</html>
<?php ob_end_flush(); ?>