<?php
session_start();
include 'config.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Debugging: Log session data
error_log("Manage Leaves - Session Data: " . print_r($_SESSION, true), 3, "debug.log");

// Check if user is logged in
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    error_log("Manage Leaves - No user_id in session or empty user_id, redirecting to index.php", 3, "debug.log");
    $_SESSION['error'] = "Please log in to continue.";
    header("Location: index.php");
    exit();
}

// Get the logged-in user's details
$user_sql = "SELECT id, username, role FROM users WHERE id = ?";
$stmt = $conn->prepare($user_sql);
if (!$stmt) {
    error_log("Manage Leaves - User query preparation failed: " . $conn->error, 3, "debug.log");
    $_SESSION['error'] = "Database error. Please try again.";
    header("Location: index.php");
    exit();
}
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$user_result = $stmt->get_result();
if ($user_result->num_rows === 0) {
    error_log("Manage Leaves - No user found for user_id: " . $_SESSION['user_id'], 3, "debug.log");
    $_SESSION['error'] = "User not found.";
    header("Location: index.php");
    exit();
}
$user = $user_result->fetch_assoc();
$employee_id = $user['id']; // Keep as varchar
$user_role = strtolower(trim($user['role']));
$stmt->close();

// Debugging: Log user data
error_log("Manage Leaves - User ID: $employee_id, Role: $user_role, Username: " . $user['username'], 3, "debug.log");
error_log("Manage Leaves - User role check: is_admin=" . ($user_role === 'admin' || $user_role === 'superadmin' ? 'true' : 'false'), 3, "debug.log");

// Redirect employees to leave_dashboard.php
if ($user_role !== 'admin' && $user_role !== 'superadmin') {
    error_log("Manage Leaves - User is not an admin, redirecting to leave_dashboard.php", 3, "debug.log");
    header("Location: leave_dashboard.php");
    exit();
}

// Initialize result variables
$pending_result = $approved_result = $rejected_result = null;

// Fetch all leave requests for admins
$pending_sql = "SELECT lr.id, u.username, lr.leave_type, lr.start_date, lr.end_date, lr.reason, lr.status, lr.applied_on 
                FROM leave_requests lr 
                LEFT JOIN users u ON CAST(lr.employee_id AS CHAR) = u.id
                WHERE lr.status = 'Pending'
                ORDER BY lr.applied_on DESC";
$pending_result = $conn->query($pending_sql);
if (!$pending_result) {
    error_log("Manage Leaves - Pending query failed: " . $conn->error, 3, "debug.log");
} else {
    error_log("Manage Leaves - Admin pending requests: " . $pending_result->num_rows, 3, "debug.log");
}

$approved_sql = "SELECT lr.id, u.username, lr.leave_type, lr.start_date, lr.end_date, lr.reason, lr.status, lr.applied_on 
                 FROM leave_requests lr 
                 LEFT JOIN users u ON CAST(lr.employee_id AS CHAR) = u.id
                 WHERE lr.status = 'Approved'
                 ORDER BY lr.applied_on DESC";
$approved_result = $conn->query($approved_sql);
if (!$approved_result) {
    error_log("Manage Leaves - Approved query failed: " . $conn->error, 3, "debug.log");
} else {
    error_log("Manage Leaves - Admin approved requests: " . $approved_result->num_rows, 3, "debug.log");
}

$rejected_sql = "SELECT lr.id, u.username, lr.leave_type, lr.start_date, lr.end_date, lr.reason, lr.status, lr.applied_on 
                 FROM leave_requests lr 
                 LEFT JOIN users u ON CAST(lr.employee_id AS CHAR) = u.id
                 WHERE lr.status = 'Rejected'
                 ORDER BY lr.applied_on DESC";
$rejected_result = $conn->query($rejected_sql);
if (!$rejected_result) {
    error_log("Manage Leaves - Rejected query failed: " . $conn->error, 3, "debug.log");
} else {
    error_log("Manage Leaves - Admin rejected requests: " . $rejected_result->num_rows, 3, "debug.log");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Manage Leave Requests - Techknow</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 15px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
        }
        .sidebar.active {
            transform: translateX(0);
        }
        .sidebar h2 {
            font-size: 1rem;
            margin-bottom: 15px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 8px 10px;
            display: block;
            border-radius: 4px;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        .sidebar a:hover {
            background: #1abc9c;
        }
        .sidebar a.active {
            background: #1abc9c;
        }
        .hamburger {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1100;
            background: #2c3e50;
            color: #fff;
            border: none;
            padding: 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .content {
            flex: 1;
            padding: 15px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        .content.active {
            margin-left: 250px;
        }
        h1 {
            font-size: 1.5rem;
            margin-bottom: 15px;
            color: #333;
        }
        h3 {
            font-size: 1.2rem;
            color: #2c3e50;
            margin-top: 20px;
            margin-bottom: 15px;
        }
        .table-responsive {
            font-size: 0.85rem;
        }
        .table th, .table td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: middle;
        }
        .table th {
            background: #2c3e50;
            color: white;
        }
        .btn {
            padding: 6px 12px;
            font-size: 0.85rem;
            touch-action: manipulation;
        }
        .btn-spacing {
            margin: 5px;
        }
        .badge {
            padding: 6px 10px;
            font-weight: 500;
            font-size: 0.75rem;
            letter-spacing: 0.5px;
            text-transform: capitalize;
        }
        .badge-pending {
            background-color: #ffc107;
            color: #212529;
        }
        .badge-approved {
            background-color: #28a745;
            color: white;
        }
        .badge-rejected {
            background-color: #dc3545;
            color: white;
        }
        .card {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .status-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #dee2e6;
        }
        .status-tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
            background: #f8f9fa;
            transition: all 0.3s;
        }
        .status-tab.active {
            background: #2c3e50;
            color: white;
            border-color: #dee2e6;
        }
        .status-tab:hover:not(.active) {
            background: #e9ecef;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        @media (max-width: 576px) {
            .table-responsive {
                font-size: 0.75rem;
            }
            .btn {
                padding: 4px 8px;
                font-size: 0.75rem;
            }
            h1 {
                font-size: 1.2rem;
            }
            h3 {
                font-size: 1rem;
            }
            .card {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>
    <div class="sidebar" id="sidebar">
        <h2>Admin Dashboard</h2>
        <a href="dashboard_admin.php">🏠 Dashboard</a>
        <a href="manage_users.php">👥 Manage Users</a>
        <a href="manage_documents.php">📁 Manage Documents</a>
        <a href="grievance_dashboard.php">⚖️ Grievance Portal</a>
        <a href="leave_dashboard.php" class="active">🌴 Leave Portal</a>
        <a href="logout.php" class="text-danger">🚪 Logout</a>
    </div>
    <div class="content" id="content">
        <h1 class="text-primary text-center">Manage Leave Requests</h1>
        
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_SESSION['message'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['message']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_SESSION['error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="status-tabs">
            <div class="status-tab active" onclick="showTab('pending')">Pending Requests</div>
            <div class="status-tab" onclick="showTab('approved')">Approved Requests</div>
            <div class="status-tab" onclick="showTab('rejected')">Rejected Requests</div>
        </div>

        <div id="pending-tab" class="tab-content active">
            <div class="card">
                <h3 class="my-3">Pending Leave Requests</h3>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="text-center">
                                <th>#</th>
                                <th>Employee</th>
                                <th>Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $count = 1;
                            while ($pending_result && $row = $pending_result->fetch_assoc()) {
                            ?>
                                <tr class="text-center">
                                    <td><?php echo $count++; ?></td>
                                    <td><?php echo htmlspecialchars($row['username'] ?? 'Unknown User', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo htmlspecialchars($row['leave_type'], ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo $row['start_date'] ? date('Y-m-d', strtotime($row['start_date'])) : 'N/A'; ?></td>
                                    <td><?php echo $row['end_date'] ? date('Y-m-d', strtotime($row['end_date'])) : 'N/A'; ?></td>
                                    <td><?php echo htmlspecialchars($row['reason'] ?? 'No reason provided', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><span class="badge badge-pending"><?php echo htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                                    <td>
                                        <a href="approve_leaves.php?id=<?php echo $row['id']; ?>&status=Approved&admin_id=<?php echo urlencode($employee_id); ?>" class="btn btn-success btn-sm btn-spacing">
                                            <i class="fas fa-check"></i> Approve
                                        </a>
                                        <a href="approve_leaves.php?id=<?php echo $row['id']; ?>&status=Rejected&admin_id=<?php echo urlencode($employee_id); ?>" class="btn btn-danger btn-sm btn-spacing">
                                            <i class="fas fa-times"></i> Reject
                                        </a>
                                    </td>
                                </tr>
                            <?php } ?>
                            <?php if (!$pending_result || $pending_result->num_rows === 0): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">No pending leave requests found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div id="approved-tab" class="tab-content">
            <div class="card">
                <h3 class="my-3">Approved Leave Requests</h3>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="text-center">
                                <th>#</th>
                                <th>Employee</th>
                                <th>Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $count = 1;
                            while ($approved_result && $row = $approved_result->fetch_assoc()) {
                            ?>
                                <tr class="text-center">
                                    <td><?php echo $count++; ?></td>
                                    <td><?php echo htmlspecialchars($row['username'] ?? 'Unknown User', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo htmlspecialchars($row['leave_type'], ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo $row['start_date'] ? date('Y-m-d', strtotime($row['start_date'])) : 'N/A'; ?></td>
                                    <td><?php echo $row['end_date'] ? date('Y-m-d', strtotime($row['end_date'])) : 'N/A'; ?></td>
                                    <td><?php echo htmlspecialchars($row['reason'] ?? 'No reason provided', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><span class="badge badge-approved"><?php echo htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                                    <td>-</td>
                                </tr>
                            <?php } ?>
                            <?php if (!$approved_result || $approved_result->num_rows === 0): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">No approved leave requests found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div id="rejected-tab" class="tab-content">
            <div class="card">
                <h3 class="my-3">Rejected Leave Requests</h3>
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr class="text-center">
                                <th>#</th>
                                <th>Employee</th>
                                <th>Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $count = 1;
                            while ($rejected_result && $row = $rejected_result->fetch_assoc()) {
                            ?>
                                <tr class="text-center">
                                    <td><?php echo $count++; ?></td>
                                    <td><?php echo htmlspecialchars($row['username'] ?? 'Unknown User', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo htmlspecialchars($row['leave_type'], ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><?php echo $row['start_date'] ? date('Y-m-d', strtotime($row['start_date'])) : 'N/A'; ?></td>
                                    <td><?php echo $row['end_date'] ? date('Y-m-d', strtotime($row['end_date'])) : 'N/A'; ?></td>
                                    <td><?php echo htmlspecialchars($row['reason'] ?? 'No reason provided', ENT_QUOTES, 'UTF-8'); ?></td>
                                    <td><span class="badge badge-rejected"><?php echo htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                                    <td>-</td>
                                </tr>
                            <?php } ?>
                            <?php if (!$rejected_result || $rejected_result->num_rows === 0): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4">No rejected leave requests found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        }

        function showTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.getElementById(tabName + '-tab').classList.add('active');
            document.querySelectorAll('.status-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            event.currentTarget.classList.add('active');
        }
    </script>
</body>
</html>