<?php
    session_start();
    $title = "Message Template Setup";
    $group = "template";
    $menu = "template";
    include('header.php');

    $status="";
    $subject="";
    $body="Add body";

    // // $sql="select * from template order by id limit 1";
    // $sql="select * from scheduled_mails order by id limit 1";
    // $r=$con->select_query($sql);
    // foreach($r as $value)
    // {
    //     // $status=$value['status'];
    //     $subject=$value['email_subject'];
    //     $body=$value['email_message'];
    // }

    // get the html birthday template file
    $birthdayTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/birthday.html')
    );

    // $religiousTemplate = json_encode(
        
    //     file_get_contents(__DIR__ . '/message-templates/religious_holiday.html')
    // );

    $christmasTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/christmas_holiday.html')
    );

    $easterTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/easter_holiday.html')
    );

    $eidAlFitrTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/eidAlFitr_holiday.html')
    );

    $eidAlAdhaTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/eidAlAdha_holiday.html')
    );

    $generalHolidayTemplate = json_encode(
        file_get_contents(__DIR__ . '/message-templates/general_holiday.html')
    );
?>

<script type="text/javascript" src="../tinymce/tinymce.min.js"></script>
<script type="text/javascript"> 
    // tinymce.init({
    //     selector: "textarea",
    //     theme: "modern",
    //     plugins: [
    //         "advlist autolink lists link image charmap print preview hr anchor pagebreak",
    //         "searchreplace wordcount visualblocks visualchars code fullscreen",
    //         "insertdatetime media nonbreaking save table contextmenu directionality",
    //         "emoticons template paste textcolor colorpicker textpattern imagetools"
    //     ],
    //     toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
    //     toolbar2: "print preview media | forecolor backcolor emoticons",
    //     image_advtab: true,
    //     // templates: [
    //     //     {title: 'Birthday', content: </?php echo $birthdayTemplate; ?>},
    //     //     {title: 'Religious Holiday', content: 'Test 2'},
    //     //     {title: 'General Message', content: 'Test 2'}
    //     // ]
    // });   
    
    tinymce.init({
        selector: "textarea",
        theme: "modern",
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern imagetools"
        ],
        toolbar1: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link image | sectionbg",
        toolbar2: "print preview media | forecolor backcolor emoticons",
        image_advtab: true,

        extended_valid_elements: 'div[class|style|data-section|data-*]',
        valid_children: '+div[h1|p|img|a|span]',
        block_formats: 'Section=div;Paragraph=p;Heading 1=h1;Heading 2=h2',

        valid_styles: {
            '*': 'background-color,color,padding,margin,text-align,font-size,font-weight'
        },

        content_style: `
            div[data-section] { min-height: 20px; }
        `,

        // setup: function (editor) {
        //     editor.ui.registry.addButton('sectionbg', {
        //         text: 'Section BG',
        //         onAction: function () {
        //             const node = editor.selection.getNode();
        //             const section = editor.dom.getParent(node, 'div[data-section]');
        //             if (section) {
        //                 editor.dom.setStyle(section, 'background-color', '#f0f9f5');
        //             } else {
        //                 alert('Click inside a section first');
        //             }
        //         }
        //     });
        // }
    });

</script>
<script>
    function addkey(id){
        var keytext = document.getElementById(id).firstChild.nodeValue;
       tinyMCE.execCommand('mceInsertContent',false,keytext);
       return false;
    }
</script>	

<style>
    .input-daterange input {
        text-align: left;
    }
    .participant-section {
        margin-top: 15px;
        padding: 15px;
        border: 1px solid #e0e0e0;
        border-radius: 5px;
        background-color: #f9f9f9;
    }
    /* .select2-container--default .select2-selection--multiple {
        border: 1px solid #ccc;
    } */

    
    .select2-container--default .select2-selection--multiple {
        border: 1px solid #ddd;
        border-radius: 4px;
        min-height: 38px;
    }
    
    /* DOB Section Styling */
    .dob-selection-container {
        background: #f8fafc;
        padding: 20px;
        border-radius: 8px;
    }
    
    .month-selection {
        background: white;
        padding: 15px;
        border-radius: 8px;
        border: 1px solid #e9ecef;
    }
    
    .month-checkbox {
        position: relative;
        margin-bottom: 5px;
    }
    
    .month-checkbox input[type="checkbox"] {
        display: none;
    }
    
    .month-label {
        display: block;
        padding: 8px 5px;
        text-align: center;
        border: 2px solid #e9ecef;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s ease;
        background: white;
    }
    
    .month-label:hover {
        border-color: #6c757d;
        transform: translateY(-2px);
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .month-checkbox input[type="checkbox"]:checked + .month-label {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-color: #667eea;
        box-shadow: 0 4px 6px rgba(102, 126, 234, 0.2);
    }
    
    .month-abbr {
        display: block;
        font-weight: 600;
        font-size: 14px;
    }
    
    .month-full {
        display: none;
        font-size: 12px;
    }
    
    .dob-options h6 {
        color: #2d3748;
        font-weight: 600;
        border-bottom: 2px solid #667eea;
        padding-bottom: 10px;
        display: inline-block;
    }
    
    @media (min-width: 768px) {
        .month-label {
            padding: 10px 5px;
        }
        .month-abbr {
            font-size: 16px;
        }
        .month-full {
            display: block;
            margin-top: 2px;
        }
    }
    
    /* Age range input styling */
    .input-group-text {
        background-color: #f8f9fa;
        border-color: #dee2e6;
    }
    
    .form-group label {
        font-weight: 600;
        color: #4a5568;
    }
    
    .form-group .small {
        font-size: 12px;
        color: #718096;
        margin-bottom: 5px;
        display: block;
    }
</style>

<div class="content-body">
    <div class="row">
        <div id="recent-transactions" class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Compose Your Message</h4>
                </div>
                <div class="card-content">
                    <form method="post" action="message_template">
                        <div class="row row-pad">
                            <div class="col-lg-12">
                                <?php 
                                // if(isset($_SESSION['isEdit']) && $_SESSION['isEdit']==true){
                                //     include('../include/update.php');
                                // } else {
                                    include('../include/insert.php');
                                // }
                                ?>
                            </div>
                        </div>

                        <div class="row row-pad pb-2">
                            <div class="col-md-2">
                                <label for="nowOrLater">Schedule/Send Now:</label>
                            </div>
                            <div class="col-md-9">
                                <span class="pr-3">
                                    <input type="radio" name="nowOrLater" id="now" value="now" checked> Now
                                </span>
                                <span>
                                    <input type="radio" name="nowOrLater" id="schedule" value="schedule" > Schedule
                                </span>
                            </div>
                        </div>

                        <!-- Select participant -->
                        <div class="row row-pad">
                            <div class="col-md-2">
                                <label for="participantType">Select Participants</label>
                            </div>
                            <div class="col-md-9">
                                <div class="mb-3">
                                    <select id="participantType" name="participantType" class="form-control" onchange="toggleParticipantFields()">
                                        <option value="all">All Staff</option>
                                        <option value="individual">By Individual</option>
                                        <option value="department">By Department</option>
                                        <option value="position">By Position</option>
                                        <option value="dob">By Date of Birth</option>
                                    </select>
                                </div>

                                <!-- Individual Selection -->
                                <div id="individualSection" class="participant-section d-none">
                                    <label>Select Individuals:</label>
                                    <select name="individuals[]" class="form-control select2" multiple style="width: 100%;">

                                        <?php
                                        
                                            // Fetch staff info from database
                                            $sql="select * from staff where email != ?";
                                            $staffInfo=$con->select_query($sql, ['']);

                                            // Populate options
                                            foreach($staffInfo as $staff)
                                            {
                                                echo '<option value="'.$staff['id'].'">' . $staff['firstname'] . ' ' . $staff['lastname'] . '</option>';
                                            }

                                        ?>
                                        
                                    </select>
                                </div>

                                <!-- Department Selection -->
                                <div id="departmentSection" class="participant-section d-none">
                                    <label>Select Department:</label>
                                    <select name="departments[]" class="form-control select2" multiple style="width: 100%;">
                                        
                                        <?php
                                        
                                            // Fetch unique staff departments from database
                                            $sql="select distinct dept from staff";
                                            $staffDeptInfo=$con->select_query($sql);

                                            // Populate options
                                            foreach($staffDeptInfo as $staff)
                                            {
                                                echo '<option value="'.$staff['dept'].'">' . $staff['dept'] . '</option>';
                                            }

                                        ?>
                                        
                                    </select>
                                </div>

                                <!-- Position Selection -->
                                <div id="positionSection" class="participant-section d-none">
                                    <label>Select Position:</label>
                                    <select name="positions[]" class="form-control select2" multiple style="width: 100%;">
                                        
                                        <?php
                                        
                                            // Fetch unique staff positions info from database
                                            $sql="select distinct position from staff";
                                            $staffPositionInfo=$con->select_query($sql);

                                            // Populate options
                                            foreach($staffPositionInfo as $staff)
                                            {
                                                echo '<option value="'.$staff['position'].'">' . $staff['position'] . '</option>';
                                            }

                                        ?>
                                        
                                    </select>
                                </div>

                                <!-- Date of Birth Selection -->
                                <div id="dobSection" class="participant-section d-none">
                                    <div class="dob-selection-container">
                                        <div class="dob-options">
                                            <h6 class="mb-3">Select by Birthday:</h6>
                                            
                                            <!-- Specific Date Range -->
                                            <div class="form-group">
                                                <label class="d-block mb-2">Specific Date Range:</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label class="small">From Date</label>
                                                        <input type="date" name="dob_start" class="form-control">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label class="small">To Date</label>
                                                        <input type="date" name="dob_end" class="form-control">
                                                    </div>
                                                </div>
                                                <small class="text-muted">Select a specific date range (year, month, day)</small>
                                            </div>

                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="row row-pad">
                            <div class="col-md-2">
                                <label for="name">Category</label>
                            </div>
                            <div class="col-md-9">
                                <select id="templateSelector" name="templateSelector" class="form-control">
                                    <option value="">-- Select Category --</option>
                                    <option value="birthday">Birthday Message</option>
                                    <option value="christmas">Christmas Holiday Message</option>
                                    <option value="easter">Easter Holiday Message</option>
                                    <option value="eidAlFitr">EidAlFitr Holiday Message</option>
                                    <option value="eidAlAdha">EidAlAdha Holiday Message</option>
                                    <option value="general">General Message</option>
                                </select>
                            </div>
                        </div>

                        <div class="row row-pad">
                            <div class="col-md-2">
                                <label for="name">Subject</label>
                            </div>
                            <div class="col-md-9">
                                <input type="text" name="subject" class="form-control" value="<?php echo $subject;?>" required/>
                            </div>
                        </div>

                        <div class="row row-pad">
                            <div class="col-md-2">Keys                
                            </div>
                            <div class="col-md-9">
                                <a href="javascript:;" id="fname" onclick="addkey('fname')">%firstname%</a> <a href="javascript:;" id="lname" onclick="addkey('lname')">%lastname%</a> <a href="javascript:;" id="oname" onclick="addkey('oname')">%othername%</a>
                                <br/>  <small style="color:red">*Insert keys to the message body. These keys will be changed to actual value before send.</small>
                            </div>
                        </div>

                        <div class="row row-pad">
                            <div class="col-md-2">
                                <label for="name">Body</label>
                            </div>
                            <div class="col-md-9">
                                <textarea name="body" class="form-control" style="height:250px;" required><?php echo $body;?></textarea>
                            </div>
                        </div>

                        <div class="row row-pad d-none" id="scheduleDateCont">
                            <div class="col-md-2">
                                <label for="name">Schedule Date:</label>
                            </div>
                            <div class="col-md-9">
                                <input type="datetime-local" name="scheduleDate" class="form-control">
                            </div>
                        </div>
                      
                        <div class="row row-pad">
                            <div class="col-md-2">
                                
                            </div>
                            <div class="col-md-9">
                                <!-- <input type="checkbox" name="status" </?php echo ($status==1 ? "checked" : "")?>/> Active -->
                                <!-- <input type="checkbox" name="sendNow"/> Send Now -->
                            </div>
                        </div>
                    
                        <div class="row row-pad">
                            <div class="col-md-2">
                                
                            </div>
                            <div class="col-md-9">
                                <?php 
                                    // if(isset($_SESSION['isEdit']) && $_SESSION['isEdit']==true){
                                    //     echo '
                                    //     <input type="hidden" name="update" value="message_template_setup"/>
                                    //     <input type="submit" name="save" class="btn btn-info" value="Save"/>';
                                    // } else {
                                    //     echo '
                                    //     <input type="hidden" name="insert" value="message_template_setup"/>
                                    //     <input type="submit" name="savecontinue" class="btn btn-info" value="Save and Continue"/>';
                                    // }
                                ?>
                                <!-- <input type="hidden" name="insert" value="message_template_setup"/> -->
                                <input type="hidden" name="insert" id="insertField" value="send_now"/>
                                <input type="submit" name="sendNow" id="nowSubmitBtn" class="btn btn-primary d-block" value="Send Now"/>
                                <input type="submit" name="scheduleForLater" id="scheduleSubmitBtn" class="btn btn-info d-none" value="Schedule for Later"/>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- select2 script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<!-- Optional: Bootstrap Datepicker if not already included -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

<script>
    // script to detect the radio button selected
    document.addEventListener('DOMContentLoaded', function () {
        const radios = document.querySelectorAll('input[name="nowOrLater"]');

        const nowBtn = document.getElementById('nowSubmitBtn');
        const scheduleDate = document.getElementById('scheduleDateCont');
        const scheduleBtn = document.getElementById('scheduleSubmitBtn');
        const insertFIled = document.getElementById('insertField');

        radios.forEach(radio => {
            radio.addEventListener('change', function () {

                if (this.value === 'now') {
                    // console.log('Send now selected');

                    // Show NOW button
                    nowBtn.classList.remove('d-none');
                    nowBtn.classList.add('d-block');
                    insertField.value = "send_now";

                    // Hide schedule fields
                    scheduleDate.classList.remove('d-flex');
                    scheduleDate.classList.add('d-none');
                    scheduleBtn.classList.remove('d-block');
                    scheduleBtn.classList.add('d-none');

                } else if (this.value === 'schedule') {
                    // console.log('Schedule selected');

                    // Hide NOW button
                    nowBtn.classList.remove('d-block');
                    nowBtn.classList.add('d-none');
                    insertField.value = "schedule_for_later";

                    // Show schedule fields
                    scheduleDate.classList.remove('d-none');
                    scheduleDate.classList.add('d-flex');
                    scheduleBtn.classList.remove('d-none');
                    scheduleBtn.classList.add('d-block');
                }
            });
        });
    });


    // Function to toggle participant selection fields
    function toggleParticipantFields() {
        const type = document.getElementById('participantType').value;
        
        // Hide all sections first
        document.querySelectorAll('.participant-section').forEach(section => {
            section.classList.add('d-none');
        });
        
        // Show selected section
        switch(type) {
            case 'individual':

                document.getElementById('individualSection').classList.remove('d-none');

                // hide the others
                document.getElementById('departmentSection').classList.add('d-none');
                document.getElementById('positionSection').classList.add('d-none');
                document.getElementById('dobSection').classList.add('d-none');

                break;

            case 'department':

                document.getElementById('departmentSection').classList.remove('d-none');
                
                // hide the others
                document.getElementById('individualSection').classList.add('d-none');
                document.getElementById('positionSection').classList.add('d-none');
                document.getElementById('dobSection').classList.add('d-none');

                break;

            case 'position':

                document.getElementById('positionSection').classList.remove('d-none');
                
                // hide the others
                document.getElementById('individualSection').classList.add('d-none');
                document.getElementById('departmentSection').classList.add('d-none');
                document.getElementById('dobSection').classList.add('d-none');

                break;

            case 'dob':

                document.getElementById('dobSection').classList.remove('d-none');
                
                // hide the others
                document.getElementById('individualSection').classList.add('d-none');
                document.getElementById('departmentSection').classList.add('d-none');
                document.getElementById('positionSection').classList.add('d-none');

                break;

            default:
                // 'all' selected, hide all sections
                break;
        }
    }

    // Initialize Select2 for multiple select boxes
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Select2 if the library is available
        if (typeof $.fn.select2 !== 'undefined') {
            $('.select2').select2({
                placeholder: "Select options",
                allowClear: true,
                width: '100%'
            });
        }
        
        // // Set default date ranges for convenience
        // setDefaultDateRanges();
    });

    // // Set smart default date ranges
    // function setDefaultDateRanges() {
    //     const today = new Date();
    //     const startDate = document.querySelector('input[name="dob_start"]');
    //     const endDate = document.querySelector('input[name="dob_end"]');
        
    //     if (startDate && !startDate.value) {
    //         // Set to beginning of current month
    //         const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    //         startDate.valueAsDate = firstDay;
    //     }
        
    //     if (endDate && !endDate.value) {
    //         // Set to end of current month
    //         const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    //         endDate.valueAsDate = lastDay;
    //     }
    // }


    // script to automatically load the selected template
    document.getElementById('templateSelector').addEventListener('change', function () {
        let type = this.value;
        if (!type) return;

        fetch('load_template.php?type=' + type)
            .then(res => res.text())
            .then(html => {
                tinymce.get('body').setContent(html);
            });
    });

</script>

<!-- footer section -->
<?php include('footer.php');?>

   
