<?php
include 'db.php';
session_start(); // Must be the first thing in the script

// Safely get session value
$user_id = $_SESSION['user_id'] ?? null;

if (!$user_id) {
    header("Location: /ems/index.php");
    exit();
}

// Fetch current user
$query = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

// Check if user exists and has proper permissions
// Uncomment and adjust based on your role requirements
// if (!$user || $user['role'] !== 'manager') {
//     header("Location: unauthorized.php");
//     exit();
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CRM | rutzo Admin Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="A fully featured admin theme which can be used to build CRM, CMS, etc." name="description">
    <meta content="Coderthemes" name="author">

    <!-- App favicon -->
    <link rel="shortcut icon" href="images/favicon.ico">

    <!-- Theme Config Js -->
    <script src="js/hyper-config.js"></script>

    <!-- Vendor css -->
    <link href="css/vendor.min.css" rel="stylesheet" type="text/css">

    <!-- App css -->
    <link href="css/app.min.css" rel="stylesheet" type="text/css" id="app-style">

    <!-- Icons css -->
    <link href="css/unicons.css" rel="stylesheet" type="text/css">
    <link href="css/remixicon.css" rel="stylesheet" type="text/css">
    <link href="css/materialdesignicons.min.css" rel="stylesheet" type="text/css">

    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
</head>
<body>
    <!-- Begin page -->
    <div class="wrapper">
        <!-- Topbar -->
        <?php include('includes/nav.php'); ?>

        <!-- Left Sidebar -->
        <?php include('includes/sidebar.php'); ?>
        
        <!-- Content -->
        <div class="content-page">
            <div class="content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box">
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="javascript: void(0);"></a></li>
                                        <li class="breadcrumb-item"><a href="javascript: void(0);">CRM</a></li>
                                        <li class="breadcrumb-item active">CRM</li>
                                    </ol>
                                </div>
                                <h4 class="page-title">Manager Dashboard</h4>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <h5 class="text-muted fw-normal mt-0">Total Employees</h5>
                                    <h3 class="mt-3 mb-3">
                                        <?php
                                        $emp_query = "SELECT COUNT(*) as total FROM users";
                                        $stmt = $conn->prepare($emp_query);
                                        $stmt->execute();
                                        $emp_result = $stmt->get_result();
                                        if ($emp_result) {
                                            echo htmlspecialchars($emp_result->fetch_assoc()['total']);
                                            $stmt->close();
                                        } else {
                                            echo "<span class='text-danger'>Error: " . $conn->error . "</span>";
                                        }
                                        ?>
                                    </h3>
                                    <p class="mb-0 text-primary">Active Staff</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <h5 class="text-muted fw-normal mt-0">Online Now</h5>
                                    <h3 class="mt-3 mb-3">
                                        <?php
                                        $on_query = "SELECT COUNT(*) as total FROM chat_status WHERE status = 'online'";
                                        $stmt = $conn->prepare($on_query);
                                        $stmt->execute();
                                        $on_result = $stmt->get_result();
                                        if ($on_result) {
                                            echo htmlspecialchars($on_result->fetch_assoc()['total']);
                                            $stmt->close();
                                        } else {
                                            echo "<span class='text-danger'>Error: " . $conn->error . "</span>";
                                        }
                                        ?>
                                    </h3>
                                    <p class="mb-0 text-success">Live Status</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <h5 class="text-muted fw-normal mt-0">Pending Tasks</h5>
                                    <h3 class="mt-3 mb-3">
                                        <?php
                                        $task_query = "SELECT COUNT(*) as total FROM project_tasks WHERE status = 'todo'";
                                        $stmt = $conn->prepare($task_query);
                                        $stmt->execute();
                                        $task_result = $stmt->get_result();
                                        if ($task_result) {
                                            echo htmlspecialchars($task_result->fetch_assoc()['total']);
                                            $stmt->close();
                                        } else {
                                            echo "<span class='text-danger'>Error: " . $conn->error . "</span>";
                                        }
                                        ?>
                                    </h3>
                                    <p class="mb-0 text-warning">Task Queue</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <h5 class="text-muted fw-normal mt-0">Leave Requests</h5>
                                    <h3 class="mt-3 mb-3">
                                        <?php
                                        $leave_query = "SELECT COUNT(*) as total FROM leave_requests WHERE status = 'pending'";
                                        $stmt = $conn->prepare($leave_query);
                                        $stmt->execute();
                                        $leave_result = $stmt->get_result();
                                        if ($leave_result) {
                                            echo htmlspecialchars($leave_result->fetch_assoc()['total']);
                                            $stmt->close();
                                        } else {
                                            echo "<span class='text-danger'>Error: " . $conn->error . "</span>";
                                        }
                                        ?>
                                    </h3>
                                    <p class="mb-0 text-danger">Needs Approval</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Employee Overview -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="text-muted fw-normal mt-0">Employee Overview</h5>
                                    <table class="table table-striped table-hover" id="employeeTable">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>Email</th>
                                                <th>Role</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $emp_query = "SELECT name, email, role, status FROM users";
                                            $stmt = $conn->prepare($emp_query);
                                            $stmt->execute();
                                            $emp_result = $stmt->get_result();
                                            if ($emp_result && $emp_result->num_rows > 0) {
                                                while ($row = $emp_result->fetch_assoc()) {
                                                    echo "<tr>";
                                                    echo "<td>" . htmlspecialchars($row['name'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['email'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['role'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['status'] ?? 'N/A') . "</td>";
                                                    echo "</tr>";
                                                }
                                            } else {
                                                echo "<tr><td colspan='4'>No employees found</td></tr>";
                                            }
                                            $stmt->close();
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Online Staff -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="text-muted fw-normal mt-0">Online Staff</h5>
                                    <table class="table table-striped table-hover" id="onlineTable">
                                        <thead>
                                            <tr>
                                                <th>User ID</th>
                                                <th>Status</th>
                                                <th>Last Active</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $on_query = "SELECT user_id, status, last_seen FROM chat_status WHERE status = 'online'";
                                            $stmt = $conn->prepare($on_query);
                                            $stmt->execute();
                                            $on_result = $stmt->get_result();
                                            if ($on_result && $on_result->num_rows > 0) {
                                                while ($row = $on_result->fetch_assoc()) {
                                                    echo "<tr>";
                                                    echo "<td>" . htmlspecialchars($row['user_id'] ?? 'N/A') . "</td>";
                                                    echo "<td><span class='badge bg-success'>" . htmlspecialchars($row['status'] ?? 'N/A') . "</span></td>";
                                                    echo "<td>" . htmlspecialchars($row['last_seen'] ?? 'N/A') . "</td>";
                                                    echo "</tr>";
                                                }
                                            } else {
                                                echo "<tr><td colspan='3'>No online staff</td></tr>";
                                            }
                                            $stmt->close();
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Pending Tasks -->
                        <div class="col-md-6">
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="text-muted fw-normal mt-0">Pending Tasks</h5>
                                    <table class="table table-striped table-hover" id="taskTable">
                                        <thead>
                                            <tr>
                                                <th>Task Name</th>
                                                <th>Assigned To</th>
                                                <th>Due Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $task_query = "SELECT task_name, assigned_to, due_date FROM project_tasks WHERE status = 'todo'";
                                            $stmt = $conn->prepare($task_query);
                                            $stmt->execute();
                                            $task_result = $stmt->get_result();
                                            if ($task_result && $task_result->num_rows > 0) {
                                                while ($row = $task_result->fetch_assoc()) {
                                                    echo "<tr>";
                                                    echo "<td>" . htmlspecialchars($row['task_name'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['assigned_to'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['due_date'] ?? 'N/A') . "</td>";
                                                    echo "</tr>";
                                                }
                                            } else {
                                                echo "<tr><td colspan='3'>No pending tasks</td></tr>";
                                            }
                                            $stmt->close();
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Leave Requests -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="text-muted fw-normal mt-0">Leave Requests</h5>
                                    <table class="table table-striped table-hover" id="leaveTable">
                                        <thead>
                                            <tr>
                                                <th>Employee Name</th>
                                                <th>Reason</th>
                                                <th>Start Date</th>
                                                <th>End Date</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $leave_query = "SELECT u.name, lr.reason, lr.start_date, lr.end_date, lr.status 
                                                            FROM leave_requests lr 
                                                            LEFT JOIN users u ON lr.employee_id = u.id 
                                                            WHERE lr.status = 'pending'";
                                            $stmt = $conn->prepare($leave_query);
                                            $stmt->execute();
                                            $leave_result = $stmt->get_result();
                                            if ($leave_result && $leave_result->num_rows > 0) {
                                                while ($row = $leave_result->fetch_assoc()) {
                                                    echo "<tr>";
                                                    echo "<td>" . htmlspecialchars($row['name'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['reason'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['start_date'] ?? 'N/A') . "</td>";
                                                    echo "<td>" . htmlspecialchars($row['end_date'] ?? 'N/A') . "</td>";
                                                    echo "<td><span class='badge bg-warning'>" . htmlspecialchars($row['status'] ?? 'N/A') . "</span></td>";
                                                    echo "</tr>";
                                                }
                                            } else {
                                                echo "<tr><td colspan='5'>No pending leave requests</td></tr>";
                                            }
                                            $stmt->close();
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> <!-- container -->
            </div> <!-- content -->

            <!-- Footer -->
            <?php include('includes/footer.php'); ?>
        </div>
        <!-- End Page content -->
    </div>
    <!-- END wrapper -->

    <!-- Theme Settings -->
    <?php include('includes/theme.php'); ?>

    <!-- Vendor js -->
    <script src="js/vendor.min.js"></script>

    <!-- App js -->
    <script src="js/app.js"></script>

    <!-- DataTables JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    <!-- Initialize DataTables -->
   <!-- Initialize DataTables -->
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Sidebar functionality (unchanged)
    const sidebar = document.querySelector('.left-side-menu');
    const menuButton = document.querySelector('.button-menu-mobile');

    if (menuButton && sidebar) {
        menuButton.addEventListener('click', function() {
            sidebar.classList.toggle('menu-open');
            document.body.classList.toggle('sidebar-enable');
        });

        document.addEventListener('click', function(event) {
            const isClickInside = sidebar.contains(event.target) || menuButton.contains(event.target);
            if (!isClickInside && window.innerWidth <= 767) {
                sidebar.classList.remove('menu-open');
                document.body.classList.remove('sidebar-enable');
            }
        });
    }

    window.addEventListener('resize', function() {
        if (window.innerWidth > 767) {
            sidebar.classList.remove('menu-open');
            document.body.classList.remove('sidebar-enable');
        }
    });

    // DataTables initialization for all tables
    // Ensure jQuery and DataTables libraries are included in your HTML
    // Example: <script src="https://code.jquery.com/jquery-3.6.0.min.js">
    // Example: <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    // Example: <link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet">
</script>
    </script>
</body>
</html>