<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if the user is logged in and is an admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

// Include database connection
require_once '../config/database.php';

// Handle form submission to add a new employee
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_employee'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = md5($_POST['password']); // Hash the password
    $role = $_POST['role'];

    $query = "INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('ssss', $name, $email, $password, $role);

    if ($stmt->execute()) {
        echo "<p style='color: green;'>Employee added successfully!</p>";
    } else {
        echo "<p style='color: red;'>Error: " . $stmt->error . "</p>";
    }
}

// Handle task editing
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_task'])) {
    $task_id = $_POST['task_id'];
    $task_name = $_POST['task_name'];
    $description = $_POST['description'];
    $priority = $_POST['priority'];
    $due_date = $_POST['due_date'];
    $status = $_POST['status'];

    $query = "UPDATE tasks SET task_name = ?, description = ?, priority = ?, due_date = ?, status = ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('sssssi', $task_name, $description, $priority, $due_date, $status, $task_id);

    if ($stmt->execute()) {
        echo "<p style='color: green;'>Task updated successfully!</p>";
    } else {
        echo "<p style='color: red;'>Error: " . $stmt->error . "</p>";
    }
}

// Handle task deletion
if (isset($_GET['delete_task'])) {
    $task_id = $_GET['delete_task'];

    $query = "DELETE FROM tasks WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $task_id);

    if ($stmt->execute()) {
        echo "<p style='color: green;'>Task deleted successfully!</p>";
    } else {
        echo "<p style='color: red;'>Error: " . $stmt->error . "</p>";
    }
}

// Handle employee deletion
if (isset($_GET['delete_employee'])) {
    $employee_id = $_GET['delete_employee'];

    $query = "DELETE FROM users WHERE id = ? AND role != 'admin'"; // Prevent deleting other admins
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $employee_id);

    if ($stmt->execute()) {
        echo "<p style='color: green;'>Employee deleted successfully!</p>";
    } else {
        echo "<p style='color: red;'>Error: " . $stmt->error . "</p>";
    }
}

// Fetch all employees
$query = "SELECT id, username, email, role, created_at FROM users";
$result = $conn->query($query);

// Fetch all tasks
$task_query = "SELECT * FROM tasks ORDER BY created_at DESC";
$tasks = $conn->query($task_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TaskPro - Admin Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f4f4f9;
            padding: 20px;
            display: flex;
        }
        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
        }
        .sidebar .logo {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 20px;
        }
        .sidebar .menu {
            list-style: none;
            padding: 0;
        }
        .sidebar .menu li {
            margin-bottom: 15px;
        }
        .sidebar .menu a {
            color: white;
            text-decoration: none;
            font-weight: 500;
        }
        .sidebar .menu a:hover {
            text-decoration: underline;
        }
        .content {
            margin-left: 270px;
            padding: 20px;
            width: 100%;
        }
        h1 {
            margin-bottom: 20px;
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        .add-employee-form {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .add-employee-form label {
            display: block;
            margin-bottom: 10px;
            font-weight: 500;
        }
        .add-employee-form input, .add-employee-form select {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .add-employee-form button {
            padding: 10px 20px;
            background-color: #0000ff;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-weight: 500;
        }
        .add-employee-form button:hover {
            background-color: #0056b3;
        }
        .delete-link {
            color: red;
            text-decoration: none;
        }
        .delete-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="logo">TaskPro</div>
        <ul class="menu">
            <li><a href="assign_task.php">Assign Task</a></li>
            <li><a href="admin_panel.php">Manage Employees</a></li>
            <li><a href="track_task.php">Track Task</a></li>
            <li><a href="report.php" target="_blank">Reports</a></li>
            <li><a href="settings.php">Settings</a></li>
            <li><a href="logout.php">Logout</a></li>
        </ul>
    </div>

    <div class="content">
        <h1>TaskPro - Admin Panel</h1>

        <h2>Add New Employee</h2>
        <div class="add-employee-form">
            <form method="POST" action="admin_panel.php">
                <label for="name">Name</label>
                <input type="text" id="name" name="name" required>

                <label for="email">Email</label>
                <input type="email" id="email" name="email" required>

                <label for="password">Password</label>
                <input type="password" id="password" name="password" required>

                <label for="role">Role</label>
                <select id="role" name="role" required>
                    <option value="worker">Worker</option>
                    <option value="admin">Admin</option>
                </select>

                <button type="submit" name="add_employee">Add Employee</button>
            </form>
        </div>

        <h2>Employee List</h2>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Created At</th>
                <th>Actions</th>
            </tr>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                    <td><?php echo htmlspecialchars($row['email']); ?></td>
                    <td><?php echo htmlspecialchars($row['role']); ?></td>
                    <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                    <td>
                        <?php if ($row['role'] !== 'admin'): ?>
                            <a href="admin_panel.php?delete_employee=<?php echo $row['id']; ?>" class="delete-link" onclick="return confirm('Are you sure you want to delete this employee?');">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        </table>

        <h2>Task List</h2>
        <table>
            <tr>
                <th>ID</th>
                <th>Task Name</th>
                <th>Description</th>
                <th>Priority</th>
                <th>Due Date</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
            <?php while ($task = $tasks->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $task['id']; ?></td>
                    <td><?php echo htmlspecialchars($task['task_name']); ?></td>
                    <td><?php echo htmlspecialchars($task['description']); ?></td>
                    <td><?php echo htmlspecialchars($task['priority']); ?></td>
                    <td><?php echo htmlspecialchars($task['due_date']); ?></td>
                    <td><?php echo htmlspecialchars($task['status']); ?></td>
                    <td>
                        <a href="edit_task.php?id=<?php echo $task['id']; ?>">Edit</a>
                        <a href="admin_panel.php?delete_task=<?php echo $task['id']; ?>" onclick="return confirm('Are you sure you want to delete this task?');">Delete</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        </table>
    </div>
</body>
</html>
