<?php
/***
Auth: Vastvikta Nishad
Modified on : 28-10-2025 {Farhan Akhtar}
Description: Display and Delete spam email + Mark Agent Leave
*/
?>
<div class="style2-table">
    <div class="style-title">
        <div class="row">
            <div class="col-sm-10">
                <h3>Email <?=$Assignment?> Rules</h3>
            </div>
        </div>    
    </div>

    <!-- Mark Agent Leave Section -->
    <div class="table mt-4">
        <form id="leaveForm" method="post">
             <input type="hidden" name="id" id="leave_id"> <!-- Hidden field for edit mode -->
            <table class="tableview tableview-2 main-form">
                <thead>
                    <tr class="background">
                        <td colspan="4"><span style="font-size:16px;font-weight:600">Mark Agent Leave</span></h2></td></td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><label for="agent" class="form-label">Agent Name:</label></td>
                        <td>
                            <select class="form-select input-style1" id="agent" name="agent_id" required>
                                <option value="">Select Agent</option>
                                <?php
                                $agents = getActiveAgents($link);
                                foreach ($agents as $agent) {
                                    echo "<option value='{$agent['AtxUserID']}'>{$agent['AtxUserName']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                        <td><label for="start_date" class="form-label">Start Date:</label></td>
                        <td><input type="text" class="input-style1 date_class" name="start_date" id="start_date" autocomplete="off" required></td>
                    </tr>

                    <tr>
                        <td><label for="end_date" class="form-label">End Date:</label></td>
                        <td><input type="text" class="input-style1 date_class" name="end_date" id="end_date" autocomplete="off" required></td>
                        

                        <td><label for="reassign_to" class="form-label">Assign Mails To:</label></td>
                        <td>
                            <select class="form-select input-style1" id="reassign_to" name="reassign_to_agent" required>
                                <option value="">Select Agent</option>
                                <?php
                                $agents = getActiveAgents($link);
                                foreach ($agents as $agent) {
                                    echo "<option value='{$agent['AtxUserID']}'>{$agent['AtxUserName']}</option>";
                                }
                                ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4" style="text-align: center;">
                            <button type="submit" id="saveBtn" class="button-8" style="float: none;">Add new leave</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>
    </div>
    <div class="my-4">
        <table class="tableview tableview-2" id="leaveTable" style="width:100%; text-align:center;">
            <thead>
                <tr class="background">
                    <td>ID</td>
                    <td>Agent</td>
                    <td>Start Date</td>
                    <td>End Date</td>
                    <td>Reassign To</td>
                    <td>Created By</td>
                    <td>Created At</td>
                    <td>Action</td>
                </tr>
            </thead>
            <tbody>
                <!-- Data from loadLeaves() will appear here -->
            </tbody>
        </table>
    </div>


    <!-- Email Rule Settings -->
    <div class="style2-table">
        <div class="table">
            <form id="emailRuleForm">
                <table class="tableview tableview-2 main-form">
                    <tbody>
                        <tr>
                            <td><label for="stickyAgent">Sticky Agent:</label></td>
                            <td>
                                <select name="stickyAgent" id="stickyAgent" required class="input-style1">
                                    <option value="1">Yes</option>
                                    <option value="0">No</option>
                                </select>
                            </td>

                            <td><label for="microsoftDynamics">Microsoft Dynamics:</label></td>
                            <td>
                                <select name="microsoftDynamics" id="microsoftDynamics" required class="input-style1">
                                    <option value="1">Enabled</option>
                                    <option value="0">Disabled</option>
                                </select>
                            </td>
                        </tr>

                        <tr>
                            <td><label for="priorityEscalationHour">Priority Escalation Hours:</label></td>
                            <td><input type="text" name="priorityEscalationHour" id="priorityEscalationHour" class="input-style1" maxlength="3"></td>

                            <td><label for="nonpriorityEscalationHour">Non-Priority Hours:</label></td>
                            <td><input type="text" name="nonpriorityEscalationHour" id="nonpriorityEscalationHour" class="input-style1" maxlength="3"></td>
                        </tr>

                        <tr>
                            <td><label for="escalationTime">Escalation Time (HH:MM):</label></td>
                            <td><input type="text" name="escalationTime" id="escalationTime" class="input-style1" maxlength="5"></td>

                            <td><label for="enableLogging">Enable Logging:</label></td>
                            <td>
                                <select name="enableLogging" id="enableLogging" required class="input-style1">
                                    <option value="1">Yes</option>
                                    <option value="0">No</option>
                                </select>
                            </td>
                        </tr>

                        <tr>
                            <td><label for="escalationEmailIDs">Escalation Emails:</label></td>
                            <td>
                                <textarea name="escalationEmailIDs" id="escalationEmailIDs" rows="3" class="input-style1" style="width: 100%;"></textarea>
                            </td>

                            <td><label for="blockedMails">Blocked Emails:</label></td>
                            <td>
                                <textarea name="blockedMails" id="blockedMails" rows="3" class="input-style1" style="width: 100%;"></textarea>
                            </td>
                        </tr>

                        <tr>
                            <td colspan="4" style="text-align: center;">
                                <button type="submit" class="button-orange1" style="float: none;">Save Settings</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
            <!-- Existing Rules Table -->
            <form name="frmService" action="" method="post">
                <div class="table" id="SRallview"> 
                    <div class="div2" id="rulesContainer">
                        <table class="tableview tableview-2" id="rulesTable">
                            <thead>
                                <tr class="background">
                                    <td>ID</td>
                                    <td>Sticky Agent</td>
                                    <td>Priority Hour</td>
                                    <td>Non-Priority Hour</td>
                                    <td>Time</td>
                                    <td>Escalation Emails</td>
                                    <td>Blocked Emails</td>
                                    <td>Dynamics</td>
                                    <td>Logging</td>
                                    <td>Last Updated</td>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </form>
        </div>
    </div>

    
</div>

<script>
    // Initialize jQuery DateTimePicker
    $(".date_class").datetimepicker({
        format: 'Y-m-d H:i:s',   // set format for backend
        step: 1                  // allow seconds
    });

   document.addEventListener('DOMContentLoaded', function () {
    function formatDateToYMDHIS(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    ['start_date', 'end_date'].forEach(id => {
        const input = document.getElementById(id);
        input.addEventListener('change', function () {
            const formatted = formatDateToYMDHIS(this.value);
            this.setAttribute('value', formatted);
            this.dataset.datetime = formatted; // optional: useful if you want to use both
        });
    });
});
</script>
<script>
$(document).ready(function () {

    // Convert date to Y-m-d H:i:s format
    function formatDateTime(dateString) {
        const date = new Date(dateString);
        return date.getFullYear() + "-" +
            ("0" + (date.getMonth() + 1)).slice(-2) + "-" +
            ("0" + date.getDate()).slice(-2) + " " +
            ("0" + date.getHours()).slice(-2) + ":" +
            ("0" + date.getMinutes()).slice(-2) + ":" +
            ("0" + date.getSeconds()).slice(-2);
    }

    let editMode = false;
    let editId = null;

    // CREATE or UPDATE
    $("#leaveForm").on("submit", function (e) {
        e.preventDefault();

        const formData = $(this).serializeArray();
        formData.push({ name: "action", value: editMode ? "update" : "create" });

        if (editMode) {
            formData.push({ name: "id", value: editId });
        }

        $.post("admin/agent_leave_actions.php", formData, function (res) {
            if (res.status === "success") {
                alert(res.message);
                loadLeaves();
                $("#leaveForm")[0].reset();
                $("#saveBtn").text("Add new leave");
                editMode = false;
                editId = null;
            } else {
                alert("Error: " + res.message);
            }
        }, "json");
    });

    // READ (Load Leaves)
    function loadLeaves() {
        $.post("admin/agent_leave_actions.php", { action: "read" }, function (res) {
            if (res.status === "success") {
                let rows = "";
                if (res.data.length === 0) {
                    rows = `<tr><td colspan="9">No leave records found</td></tr>`;
                } else {
                    res.data.forEach((r) => {
                        rows += `
                            <tr>
                                <td>${r.id}</td>
                                <td>${r.agent_name}</td>
                                <td>${r.start_date}</td>
                                <td>${r.end_date}</td>
                                <td>${r.reassign_to}</td>
                                <td>${r.created_by}</td>
                                <td>${r.created_at}</td>
                                <td>
                                    <a class="edit-btn pointer" data-id="${r.id}">
                                        <i class="fa fa-edit text-success"></i>
                                    </a>
                                    <a class="delete-btn pointer" data-id="${r.id}">
                                        <i class="fa fa-trash text-danger"></i>
                                    </a>
                                </td>
                            </tr>
                        `;
                    });
                }
                $("#leaveTable tbody").html(rows);
            } else {
                alert("Failed to load leaves: " + res.message);
            }
        }, "json");
    }
    loadLeaves();

    // DELETE (Soft Delete)
    $(document).on("click", ".delete-btn", function () {
        if (!confirm("Are you sure?")) return;
        const id = $(this).data("id");

        $.post("admin/agent_leave_actions.php", { action: "delete", id }, function (res) {
            alert(res.message);
            loadLeaves();
        }, "json");
    });

    // EDIT - Populate form inline
    $(document).on("click", ".edit-btn", function () {
        const id = $(this).data("id");

        $.post("admin/agent_leave_actions.php", { action: "read" }, function (res) {
            if (res.status === "success") {
                const record = res.data.find(r => r.id == id);
                if (record) {
                    // Populate form
                    $("#agent").val(record.agent_id);
                    $("#start_date").val(record.start_date);
                    $("#end_date").val(record.end_date);
                    $("#reassign_to").val(record.reassign_to_agent);
                    $("#assign_type").val(record.assign_type);

                    // Update button and flags
                    $("#saveBtn").text("Update Leave");
                    editMode = true;
                    editId = id;
                }
            } else {
                alert("Failed to fetch record: " + res.message);
            }
        }, "json");
    });
});
</script>

