<!DOCTYPE html>
<html>

<head>
    <meta name='robots' content='noindex, nofollow' />
    <meta charset="UTF-8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="HandheldFriendly" content="true">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Referral Thank You | Niagara Dental Implant & Oral Surgery</title>
    <meta property="og:title" content="Referral Thank You">
    <link rel="icon" href="/lp-asset/lp-images/favicon-1icon.png">
    <link rel="stylesheet preload" as="style" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.css">
    <link rel="stylesheet preload" as="style" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/lp-asset/referral-thank-you.css">
    <!-- Google Tag Manager -->
		<script>(function (w, d, s, l, i) {
				w[l] = w[l] || []; w[l].push({
					'gtm.start':
						new Date().getTime(), event: 'gtm.js'
				}); var f = d.getElementsByTagName(s)[0],
					j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
						'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
			})(window, document, 'script', 'dataLayer', 'GTM-MMTZMMF');</script>
		<!-- End Google Tag Manager -->
		
</head>

<body>
		<!-- Google Tag Manager (noscript) -->
		<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MMTZMMF" height="0" width="0"
				style="display:none;visibility:hidden"></iframe></noscript>
		<!-- End Google Tag Manager (noscript) -->
<?php
include('code/db.php');
$referral_id = isset($_REQUEST['referral_id']) ? $_REQUEST['referral_id'] : '';
$max_uploads = 10;

// --- START: Initial Attachment Check ---
$has_existing_attachments = false;
$initial_attachments_count = 0;

if (!empty($referral_id)) {
    $decoded_id = base64_decode($referral_id);
    // Use prepared statements in production code for security! (Here using query for consistency)
    $query = $db->query("SELECT attachment FROM wp_referral_form WHERE id = '" . $decoded_id . "' ");
    $data = $query->fetch();
    
    if ($data && !empty($data['attachment'])) {
        $existing_attachments_array = array_filter(explode(',', $data['attachment']));
        $initial_attachments_count = count($existing_attachments_array);
        if ($initial_attachments_count > 0) {
            $has_existing_attachments = true;
        }
    }
}
// --- END: Initial Attachment Check ---
?>
    <section class="referral-thankyou-main">
        <div class="referral-thankyou-section">
            <div class="banner-contant">
                <div class="container">
                    <div class="row">
                        <div class="col-12">
                            <div class="thank-you-logo">
                                <img src="/lp-asset/lp-images/logo-new.svg" alt="header-logo">
                            </div>
                            <div class="wording-text"></div>
                            <div class="thank-you-content" style="text-align: center;"> <h1>Thank you for your referral.</h1>
    <span>We will get in contact with the patient shortly</span>

    <div id="xray-upload-section" style="display: <?php echo ($has_existing_attachments ? 'none' : 'block'); ?>;">
        <form method="POST" action="" class="upload-x-ray-form" enctype="multipart/form-data">
            
            <div id="xray-group-container" style="display: flex; justify-content: center; flex-wrap: wrap; margin-bottom: 20px; padding-top: 20px;">
                <div id="xray-upload-container" style="display: contents;">
                    </div>

                <div class="form-group add-more-container" id="add-more-container" style="margin: 0 10px; padding: 10px 0px;">
                    <button type="button" class="btn btn-primary" id="add-more-upload-btn" style="
                        padding: 12px 24px;
                        border: 1px solid #3b598a;
                        border-radius: 6px;
                        background-color: transparent;
                        color: #3b598a;
                        font-size: 18px;
                        cursor: pointer;
                        /* Design alignment */
                        height: 120px; 
                        width: 150px;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        margin-top: 0; /* Removed margin-top */
                    ">
                        <span style="font-size: 24px; margin-bottom: 5px; line-height: 1;">+</span> Add Another X-Ray
                    </button>
                </div>
            </div> <button type="button" class="btn btn-success" id="submit-all-xrays" style="
               padding: 15px 20px;
                border: none;
                border-radius: 10px;
                background-color: #3b598a;
                color: white;
                font-size: 16px;
                cursor: pointer;
                margin-top: 20px;
                line-height: 1.5;
                box-shadow: rgb(0 0 0 / 24%) 0px 3px 8px;
                text-transform: capitalize;
                display: none; 
            ">
                Upload All X-Rays
            </button>

            <span style="padding: 12px 10px; display: block; margin-top: 10px;">Allowed: Max <?php echo $max_uploads; ?> files. Supported: Images (jpg, jpeg, png, webp, svg, heic, heif), PDF, DOC/DOCX. </span>

            <div class="error-x-ray-div" style="display:none; margin-bottom: 10px; color: #b60000c9; "> Invalid file type or file limit reached! </div>
        </form>
    </div> <div class="uploaded-x-ray-div" style="display: <?php echo ($has_existing_attachments ? 'block' : 'none'); ?>; margin: 0px auto 40px; color: #00b600; font-weight: bold; font-size: 1.1em; width: fit-content;"> 
        <?php echo $initial_attachments_count; ?> X-ray(s) are already uploaded. 
    </div>

</div>


                            <div class="banner-btn">
                                <p><a href="https://www.niagaraoms.com/">GO TO HOME <i class="fa fa-home" aria-hidden="true"></i> </a></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
    
    
    <script>
    var referral_id = '<?php echo $referral_id ?>';
    var max_uploads = <?php echo $max_uploads; ?>;
    var file_counter = 0; 
    var files_to_upload = new DataTransfer(); 
    var has_existing_attachments = <?php echo $has_existing_attachments ? 'true' : 'false'; ?>;

    function getUploadSvg() {
        return '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" x="0" y="0" viewBox="0 0 512.056 512.056" style="enable-background:new 0 0 512 512" xml:space="preserve"><g><path d="M426.635 188.224C402.969 93.946 307.358 36.704 213.08 60.37 139.404 78.865 85.907 142.542 80.395 218.303 28.082 226.93-7.333 276.331 1.294 328.644c7.669 46.507 47.967 80.566 95.101 80.379h80v-32h-80c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64 8.837 0 16-7.163 16-16-.08-79.529 64.327-144.065 143.856-144.144 68.844-.069 128.107 48.601 141.424 116.144a16 16 0 0 0 13.6 12.8c43.742 6.229 74.151 46.738 67.923 90.479-5.593 39.278-39.129 68.523-78.803 68.721h-64v32h64c61.856-.187 111.848-50.483 111.66-112.339-.156-51.49-35.4-96.241-85.42-108.46z" fill="#3b598a" opacity="1" data-original="#3b598a" class=""></path><path d="m245.035 253.664-64 64 22.56 22.56 36.8-36.64v153.44h32v-153.44l36.64 36.64 22.56-22.56-64-64c-6.241-6.204-16.319-6.204-22.56 0z" fill="#3b598a" opacity="1" data-original="#3b598a" class=""></path></g></svg>';
    }

    // Function to generate a new upload box
    function createUploadBox(is_removable) {
        if (file_counter >= max_uploads) {
            jQuery('#add-more-container').hide();
            return;
        }

        var box_id = 'upload-box-' + file_counter;
        var input_id = 'file-input-' + file_counter;
        file_counter++;

        var close_icon = '';
        if (is_removable) {
            // Close icon positioned absolutely for the removable boxes, tucked slightly outside the main upload button
            close_icon = '<button type="button" class="remove-file-btn" data-box-id="' + box_id + '" style="position: absolute; top: 4px; right: 4px ; background: none; border: none; font-size: 26px; color: #b60000c9; outline:none !important; box-shadow:none !important; cursor: pointer; padding: 0; line-height: normal; z-index: 10;">&times;</button>';
        }

        var html = `
            <div class="form-group upload-x-ray-single" id="${box_id}" style="width: 150px; margin: 0 10px; padding: 10px 0; border: none; border-radius: 6px; position: relative;">
                ${close_icon}
                
                <label for="${input_id}" class="input-file" style="
                    padding: 12px 24px; 
                    border: 1px solid #3b598a; 
                    border-radius: 6px; 
                    margin-bottom: 0; 
                    cursor:pointer; 
                    display: block; 
                    width: 100%; 
                    box-sizing: border-box; 
                    text-align: center; /* Center SVG and text inside */
                ">
                    ${getUploadSvg()}
                    <div class="label-content" style="margin-top: 10px;">
                        <p style="margin-bottom: 0; font-size: 18px; color: #3b598a;" class="file-name-display">Upload X-Ray</p>
                    </div>
                </label>
                
                <input type="file" name="xray_files[]" class="form-control file-input-actual" id="${input_id}" data-box-id="${box_id}" style="display: none;">
                
                <span class="file-status" style="display: block; margin-top: 5px; color: #3b598a; font-size: 12px; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-bottom: 15px;">No file selected.</span>
            </div>
        `;

        jQuery('#xray-upload-container').append(html);
        updateAddMoreButtonVisibility();
    }

    // Function to handle file selection
    jQuery(document).on('change', '.file-input-actual', function() {
        jQuery('.error-x-ray-div').hide();
        var file_input = jQuery(this);
        var box_id = file_input.data('box-id');
        var file = file_input[0].files[0];
        
        // Reset or check for file
        if (!file) {
            file_input.val("");
            jQuery(`#${box_id} .file-name-display`).text("Upload X-Ray");
            jQuery(`#${box_id} .file-status`).text("No file selected.");
            updateDataTransferQueue();
            updateSubmitButtonVisibility();
            return; 
        }

        // Allowed extensions 
        var allowedExt = ["jpg", "jpeg", "png", "webp", "svg", "heic", "heif", "pdf", "doc", "docx"];
        var ext = file.name.split('.').pop().toLowerCase();
        
        if (allowedExt.indexOf(ext) === -1) {
            file_input.val("");
            jQuery(`#${box_id} .file-name-display`).text("Upload X-Ray");
            jQuery(`#${box_id} .file-status`).text("Invalid file type!");
            jQuery('.error-x-ray-div').show().text("Invalid file type! Allowed: Images (jpg, jpeg, png, webp, svg, heic, heif), PDF, DOC/DOCX.");
            updateDataTransferQueue();
            updateSubmitButtonVisibility();
            return;
        }

        // Update the display name and status
        jQuery(`#${box_id} .file-name-display`).text("Upload X-Ray"); // Keep the main button text constant
        jQuery(`#${box_id} .file-status`).text(file.name); // Show file name in the status text area

        updateDataTransferQueue();
        updateSubmitButtonVisibility();
    });

    // Function to remove a file input box (Logic remains the same)
    jQuery(document).on('click', '.remove-file-btn', function() {
        var box_id = jQuery(this).data('box-id');
        jQuery('#' + box_id).remove();
        file_counter--;
        updateDataTransferQueue(); 
        updateAddMoreButtonVisibility();
        updateSubmitButtonVisibility();
    });

    // Function to add a new upload box (Logic remains the same)
    jQuery('#add-more-upload-btn').on('click', function() {
        createUploadBox(true); 
        updateAddMoreButtonVisibility();
    });

    // Function to check and update the visibility of the Add More button (Logic remains the same)
    function updateAddMoreButtonVisibility() {
        if (file_counter >= max_uploads) {
            jQuery('#add-more-container').hide();
        } else {
            jQuery('#add-more-container').show();
        }
    }
    
    // Function to check and update the visibility of the Submit button (Logic remains the same)
    function updateSubmitButtonVisibility() {
        if (files_to_upload.files.length > 0) {
            jQuery('#submit-all-xrays').show();
        } else {
            jQuery('#submit-all-xrays').hide();
        }
    }

    // Function to consolidate all selected files into the DataTransfer object (Logic remains the same)
    function updateDataTransferQueue() {
        files_to_upload = new DataTransfer();
        jQuery('.file-input-actual').each(function() {
            if (this.files.length > 0) {
                files_to_upload.items.add(this.files[0]);
            }
        });
    }
    
    // Submit Handler (Logic remains the same)
    jQuery('#submit-all-xrays').on('click', function() {
        if (files_to_upload.files.length === 0) {
            alert("Please select at least one file to upload.");
            return;
        }

        var formData = new FormData();
        var files_count = files_to_upload.files.length;
        
        for (let i = 0; i < files_count; i++) {
            formData.append('xray_files[]', files_to_upload.files[i]);
        }
        
        formData.append('new_files_count', files_count); 
        
        jQuery.ajax({
            url: "code/add_attachment.php?referral_id=" + referral_id + "&action=append", 
            type: "POST",
            contentType: false,
            processData: false,
            data: formData,
            beforeSend: function() {
                jQuery('#submit-all-xrays').prop('disabled', true).text('Processing...');
                jQuery('.error-x-ray-div').hide();
            },
            success: function(data) {
                var response = JSON.parse(data);
                if (response.status == 1) {
                    jQuery('#xray-upload-section').hide();
                    var total_files = response.total_files || files_count; 
                    jQuery('.uploaded-x-ray-div')
                        .text('Success! ' + total_files + ' X-ray(s) uploaded successfully.')
                        .css('display', 'block');
                } else {
                    jQuery('.error-x-ray-div').css('display', 'block').text(response.message || 'Upload failed. Please try again.');
                    jQuery('#submit-all-xrays').prop('disabled', false).text('Upload All X-Rays');
                }
            },
            error: function() {
                jQuery('.error-x-ray-div').css('display', 'block').text('An error occurred during the upload process.');
                jQuery('#submit-all-xrays').prop('disabled', false).text('Upload All X-Rays');
            }
        });
    });

    // Initialize: Only create the first box if no attachments exist
    if (!has_existing_attachments) {
        createUploadBox(false); 
    }
    
    // Initial download link display
    if (referral_id) {
        jQuery(".wording-text").append('<a href="/referral_page_pdf.php?referral_id=' + referral_id + '" target="_blank">Click Here To Download And Print The Referral Form</a>');
    }
</script>
</body>

</html>