<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth.php';
require_once 'classes/Employee.php';
require_once 'classes/Task.php';
require_once 'classes/TaskCategory.php';

// requireRole(['rm', 'admin']);

$emp_id = $_SESSION['emp_id'];

$empObj = new Employee($conn);
$taskObj = new Task($conn);
$taskCategoryObj = new TaskCategory($conn);

$employee = $empObj->getEmployeeById($emp_id);
$teamEmployees = $empObj->getEmployeesByRMId($emp_id);
$tasks = $taskObj->getEmployeeTasks($emp_id);
$taskCategories = $taskCategoryObj->getCategoriesByDept($employee['dept_id']);

?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <link rel="stylesheet" href="assets/css/index2.css">
    <link rel="stylesheet" href="assets/css/team.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="assets/css/style.css">
</head>

<body>
    <!-- Header Dblist-->
    <header>
        <a href="dashboard.php">
            <div class="logo">
                <img src="assets/images/wnet-image.png" alt="WildNet logo">
            </div>
        </a>
    </header>
    <?php
    include_once 'includes/sidebar-rm.php';
    ?>
    <main>
        <div class="top-row">
            <div class="left">
                <h3>My Team</h3>
            </div>
        </div>
        <div class="content-area">
            <div class="team-container">
                <?php
                if ($teamEmployees) {
                    foreach ($teamEmployees as $teamEmployee) {
                ?>
                <a href="timesheet.php?emp_id=<?=$teamEmployee['emp_id']?>">
                    <div class="card">
                        <div class="left"><img src="<?=$teamEmployee['profile_photo']?>" onerror="this.onerror=null; this.src='assets/images/profile-picture.png';" alt="Profile Photo"></div>
                        <div class="right">
                            <h5 class="head1">Emp Id : <?=$teamEmployee['emp_id']?></h5>
                            <h4 class="head2"><?=$teamEmployee['name']?></h4>
                            <h5 class="head3"><?=$teamEmployee['dept_name']?></h5>
                            <h5 class="head4"><?=$teamEmployee['email']?></h5>
                        </div>
                    </div>
                </a>

                <?php
                    }
                }
                ?>
                <!-- <a href="sdkf.php">
                    <div class="card">
                        <div class="left"><img src="assets/images/profile-img-3.jpg" alt=""></div>
                        <div class="right">
                            <h5 class="head1">Emp Id : 1912</h5>
                            <h4 class="head2">Alice Johnson</h4>
                            <h5 class="head3">Design & Developemnt</h5>
                            <h5 class="head4">EmailId: alice@outlook.com</h5>
                        </div>
                    </div>
                </a>
                <div class="card">
                    <div class="left"><img src="assets/images/profile-img-2.jpg" alt=""></div>
                    <div class="right">
                        <h5 class="head1">Emp Id : 1912</h5>
                        <h4 class="head2">Greta Thumberg</h4>
                        <h5 class="head3">CSR Dept</h5>
                        <h5 class="head4">EmailId: greta@outlook.com</h5>
                    </div>
                </div>
                <div class="card">
                    <div class="left"><img src="assets/images/profile-img.jpg" alt=""></div>
                    <div class="right">
                        <h5 class="head1">Emp Id : 1912</h5>
                        <h4 class="head2">Richard Peterson</h4>
                        <h5 class="head3">Design & Developemnt</h5>
                        <h5 class="head4">EmailId: richard@outlook.com</h5>
                    </div>
                </div>
                <div class="card">
                    <div class="left"><img src="assets/images/profile-img-2.jpg" alt=""></div>
                    <div class="right">
                        <h5 class="head1">Emp Id : 1912</h5>
                        <h4 class="head2">Adeline Bowman</h4>
                        <h5 class="head3">Marketing & Research</h5>
                        <h5 class="head4">EmailId: adeline@outlook.com</h5>
                    </div>
                </div>
                <div class="card">
                    <div class="left"><img src="assets/images/profile-img-3.jpg" alt=""></div>
                    <div class="right">
                        <h5 class="head1">Emp Id : 1912</h5>
                        <h4 class="head2">Stephen Dawson</h4>
                        <h5 class="head3">Finance</h5>
                        <h5 class="head4">EmailId: stephen@outlook.com</h5>
                    </div>
                </div>
                <div class="card">
                    <div class="left"><img src="assets/images/profile-img-4.jpg" alt=""></div>
                    <div class="right">
                        <h5 class="head1">Emp Id : 1912</h5>
                        <h4 class="head2">Mike Powell</h4>
                        <h5 class="head3">Human Resouce</h5>
                        <h5 class="head4">EmailId: mike@outlook.com</h5>
                    </div>
                </div> -->
            </div>
        </div>
    </main>
    <!-- <footer></footer> -->
    <?php
    // Add task entry modal
    include_once 'task-modal.php';
    // Edit Profile Photo Modal 
    include_once 'photo-modal.php';
    ?>
    <!-- Task Modal Script -->
    <script>
        const addModal = document.getElementById('modal-dialog-common');
        // const addButton = document.getElementById('add-btn');
        const openButton = document.getElementById('open-modal-btn');
        const closeButton = document.getElementById('close-btn');

        openButton.addEventListener('click', function (e) {
            addModal.classList.add('show');
        });

        // Close modal
        closeButton.addEventListener('click', () => {
            addModal.classList.remove('show');
        });

        window.addEventListener('click', (e) => {
            if (addModal === e.target) addModal.classList.remove('show');
        })
    </script>

    <script src="assets/js/filters.js"></script>
    <!-- Graphs Script -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script src="assets/js/graph.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const filterInputs = document.querySelectorAll('.filter-option, .timeline-filter, .custom-from-date, .custom-to-date');

            filterInputs.forEach(input => {
                input.addEventListener('change', applyFilters);
            });

            function applyFilters() {
                // Get selected employee names
                const selectedEmployees = Array.from(document.querySelectorAll('.employee-filter:checked')).map(el => el.value);
                // Get selected departments
                const selectedDepartments = Array.from(document.querySelectorAll('.department-filter:checked')).map(el => el.value);

                // Timeline Logic
                const customCheckbox = document.querySelector('.custom-range-checkbox');
                let timeline = '';
                let customFrom = '';
                let customTo = '';

                if (customCheckbox.checked) {
                    customFrom = document.querySelector('.custom-from-date').value;
                    customTo = document.querySelector('.custom-to-date').value;
                    timeline = 'custom'; // Mark it as custom in the request
                } else {
                    const selectedTimelines = Array.from(document.querySelectorAll('.timeline-filter:checked')).map(el => el.value);
                    if (selectedTimelines.length > 0) {
                        timeline = selectedTimelines[0]; // Only one allowed at a time
                    }
                }
                console.log({ timeline, customFrom, customTo });
                fetch('api/filter-tasks.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        employees: selectedEmployees,
                        departments: selectedDepartments,
                        timeline: timeline,
                        customFrom: customFrom,
                        customTo: customTo
                    })
                })
                    .then(response => response.json())
                    .then(data => updateTaskTable(data.tasks))
                    .catch(error => console.error('Error:', error));
            }

            function updateTaskTable(tasks) {
                const tableBody = document.querySelector('#tasktablebody');
                tableBody.innerHTML = '';

                tasks.forEach(task => {
                    let row = `
                <tr>
                    <td>${task.date}</td>
                    <td>Working</td>
                    <td>${task.category}</td>
                    <td>${task.description}</td>
                    <td>${task.duration}</td>
                    <td>${task.status == 1 ? 'Approved' : 'Not Approved'}</td>
                    <td>-</td>
                </tr>
            `;
                    tableBody.innerHTML += row;
                });
            }

            // applyFilters();
        });

    </script>

    <script src="assets/js/profile.js"></script>
    <script>
        window.onload = function () {
            document.querySelectorAll('.task-date').forEach(cell => {
                cell.textContent = formatDate(cell.textContent);
            });
        }

        // Date formatting function
        function formatDate(dateString) {
            const parts = dateString.split('-'); // ["YYYY", "MM", "DD"]
            return `${parts[2]}-${parts[1]}-${parts[0]}`; // "DD-MM-YYYY"
        }



    </script>
    <script>
        const taskCategories = <?php echo json_encode($taskCategories) ?>;
    </script>
    <script src="assets/js/add.js"></script>


</body>

</html>