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

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');
error_reporting(E_ALL);

date_default_timezone_set('Asia/Kolkata');

// === AUTH ===
if (!isset($_SESSION['username'], $_SESSION['role'], $_SESSION['user_id'])) {
    $_SESSION['error_message'] = 'Please log in.';
    header("Location: login.php"); 
    exit();
}
$role = strtolower(trim($_SESSION['role']));
if (!in_array($role, ['admin', 'superadmin', 'md'])) {
    $_SESSION['error_message'] = 'Unauthorized.';
    header("Location: login.php"); 
    exit();
}

/* === COMPLETED: READ OR ACKNOWLEDGED (latest row per employee/document) === */
$completed_sql = "
    SELECT 
        d.id AS document_id, 
        d.title, 
        u.username, 
        u.email, 
        u.id AS user_id,
        latest.status,
        latest.acknowledged_at
    FROM users u
    CROSS JOIN documents d
    INNER JOIN (
        SELECT ds.employee_id, ds.document_id, ds.status, ds.acknowledged_at
        FROM document_status ds
        INNER JOIN (
            SELECT employee_id, document_id, MAX(id) AS max_id
            FROM document_status
            GROUP BY employee_id, document_id
        ) max_ds ON ds.employee_id = max_ds.employee_id 
                AND ds.document_id = max_ds.document_id 
                AND ds.id = max_ds.max_id
        WHERE ds.status IN ('Read', 'Acknowledged')
    ) latest ON latest.employee_id = u.id AND latest.document_id = d.id
    WHERE LOWER(u.role) = 'employee'
    ORDER BY u.username, d.title
";

$completed_data = [];
$result = $conn->query($completed_sql);
if ($result) {
    while ($row = $result->fetch_assoc()) $completed_data[] = $row;
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Acknowledged Policies</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #1abc9c;
            --accent-color: #3498db;
            --light-bg: #f8f9fa;
            --dark-text: #2c3e50;
            --light-text: #7f8c8d;
            --border-color: #e0e0e0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--light-bg);
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
            color: var(--dark-text);
        }
        
        .sidebar {
            width: 250px;
            background: var(--primary-color);
            color: #fff;
            padding: 15px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        
        .sidebar.active {
            transform: translateX(0);
        }
        
        .sidebar h2 {
            font-size: 1.2rem;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: center;
        }
        
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px 15px;
            display: block;
            border-radius: 6px;
            margin-bottom: 5px;
            font-size: 0.9rem;
            transition: all 0.2s ease;
        }
        
        .sidebar a:hover {
            background: var(--secondary-color);
            transform: translateX(5px);
        }
        
        .sidebar a.active {
            background: var(--secondary-color);
        }
        
        .sidebar .dropdown-menu {
            background: #34495e;
            border: none;
            padding: 0;
            margin-left: 10px;
            border-radius: 6px;
        }
        
        .sidebar .dropdown-menu a {
            color: #fff;
            padding: 8px 20px;
            font-size: 0.85rem;
        }
        
        .sidebar .dropdown-menu a:hover {
            background: var(--secondary-color);
        }
        
        .hamburger {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: var(--primary-color);
            color: #fff;
            border: none;
            padding: 10px 12px;
            border-radius: 6px;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        }
        
        .hamburger:hover {
            background: var(--secondary-color);
        }
        
        .content {
            flex: 1;
            padding: 20px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        
        .content.active {
            margin-left: 250px;
        }
        
        .dashboard-header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 25px;
        }
        
        h1 {
            font-size: 1.8rem;
            margin-bottom: 10px;
            color: var(--primary-color);
            font-weight: 700;
        }
        
        .page-description {
            color: var(--light-text);
            font-size: 1rem;
            margin-bottom: 20px;
        }
        
        h2 {
            font-size: 1.4rem;
            color: var(--primary-color);
            margin-top: 30px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--secondary-color);
            font-weight: 600;
        }
        
        .table-container {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .table th, .table td {
            padding: 14px 12px;
            border-bottom: 1px solid var(--border-color);
            text-align: left;
            font-size: 0.9rem;
        }
        
        .table th {
            background: var(--primary-color);
            color: white;
            font-weight: 600;
            position: sticky;
            top: 0;
        }
        
        .table tr:nth-child(even) {
            background: #f9f9f9;
        }
        
        .table tr:hover {
            background: #e8f4f8;
        }
        
        .badge {
            font-size: 0.75rem;
            padding: 0.35em 0.65em;
            border-radius: 6px;
        }
        
        .badge.bg-acknowledged {
            background: var(--secondary-color) !important;
            color: white;
        }
        
        .btn-sm {
            font-size: 0.8rem;
            padding: 6px 12px;
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: var(--light-text);
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            background: var(--primary-color);
            color: white;
            border-radius: 6px;
        }

        @media (max-width: 768px) {
            .content { padding: 15px; }
            h1 { font-size: 1.5rem; }
            h2 { font-size: 1.2rem; }
            .table { min-width: 900px; }
            .table-container { overflow-x: auto; }
        }
        
        @media (max-width: 576px) {
            .sidebar { width: 220px; transform: translateX(-220px); }
            .content.active { margin-left: 220px; }
        }
    </style>
</head>
<body>

<!-- Hamburger Menu -->
<button class="hamburger" onclick="toggleSidebar()">
    <i class="fas fa-bars"></i>
</button>

<!-- Sidebar -->
<div class="sidebar" id="sidebar">
    <h2>Mypeopleconnect</h2>
    
    <a href="<?= strtolower($_SESSION['role']) === 'md' ? 'dashboard_md.php' : 'dashboard_admin.php' ?>">
        <i class="fas fa-home"></i> Organisation Chart
    </a>

    <div class="dropdown">
        <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            <i class="fas fa-clipboard-check"></i> DAP
        </a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="manage_users.php">Employee Details</a></li>
            <li><a class="dropdown-item" href="manage_documents.php">Policies Rolled Out</a></li>
            <li><a class="dropdown-item" href="digital.php">Acceptance Confirmed</a></li>
        </ul>
    </div>

    <div class="dropdown">
        <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            <i class="fas fa-users"></i> CAB
        </a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="attendanceexcel.php">Attendance Excel</a></li>
            <li><a class="dropdown-item" href="attendance.php">Attendance</a></li>
            <li><a class="dropdown-item" href="manage_mappings.php">Manage Mappings</a></li>
            <li><a class="dropdown-item" href="attendance_sync.php">Sync Attendance</a></li>
            <li><a class="dropdown-item" href="payroll_excel.php">Payroll Excel</a></li>
            <li><a class="dropdown-item" href="payroll_dashboard.php">Payroll</a></li>
            <li><a class="dropdown-item" href="expense_dashboard.php">Expenses Dashboard</a></li>
            <li><a class="dropdown-item" href="leave_dashboard.php">Leave Portal</a></li>
            <li><a class="dropdown-item" href="grievance_dashboard.php">Grievance Portal</a></li>
        </ul>
    </div>

    <div class="dropdown">
        <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            <i class="fas fa-user"></i> PEP
        </a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="individual_rr.php">Individual R & R</a></li>
            <li><a class="dropdown-item" href="individual_kpi.php">Individual KPI</a></li>
            <li><a class="dropdown-item" href="login_credentials.php">Login Credentials</a></li>
        </ul>
    </div>

    <div class="dropdown">
        <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            <i class="fas fa-book"></i> L&D
        </a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="incident_employee.php">Incident Portal</a></li>
            <li><a class="dropdown-item" href="training_dashboard.php">Training Portal</a></li>
            <li><a class="dropdown-item" href="rr.php">Rewards and Recognition</a></li>
        </ul>
    </div>

    <div class="dropdown">
        <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            <i class="fas fa-star"></i> AAA
        </a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="employee_tiy.php">Employee TIY</a></li>
            <li><a class="dropdown-item" href="login_credentials.php">Login Credentials</a></li>
        </ul>
    </div>

    <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
</div>

<!-- Main Content -->
<div class="content" id="content">
    <div class="container-fluid mt-4">
        <div class="dashboard-header">
            <h1>Acknowledged Policies</h1>
            <p class="page-description">List of all employees who have read and acknowledged policies.</p>
        </div>

        <!-- Tabs -->
        <ul class="nav nav-tabs mb-4">
            <li class="nav-item">
                <a class="nav-link" href="digital.php">Pending</a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="acknowledged.php">Acknowledged</a>
            </li>
        </ul>

        <!-- Acknowledged Table -->
        <div class="table-container">
            <div class="p-3">
                <h2>Completed Acknowledgments (<?= count($completed_data) ?>)</h2>
            </div>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Document</th>
                            <th>User</th>
                            <th>Status</th>
                            <th>Ack</th>
                            <th>Acknowledged At</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($completed_data)): ?>
                            <tr>
                                <td colspan="6">No acknowledged records found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($completed_data as $row): 
                                $status = $row['status'];
                                $ackDisplay = '-';
                                if (!empty($row['acknowledged_at']) && $row['acknowledged_at'] !== '0000-00-00 00:00:00') {
                                    $dt = new DateTime($row['acknowledged_at']);
                                    $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
                                    $ackDisplay = $dt->format('d-m-Y H:i:s');
                                }
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars($row['title']) ?></td>
                                    <td><?= htmlspecialchars($row['username']) ?></td>
                                    <td><span class="badge bg-acknowledged"><?= htmlspecialchars($status) ?></span></td>
                                    <td><span class="badge bg-acknowledged">Acknowledged</span></td>
                                    <td><?= htmlspecialchars($ackDisplay) ?></td>
                                    <td>
                                        <a href="generate_pdf.php?document_id=<?= (int)$row['document_id'] ?>&user_id=<?= (int)$row['user_id'] ?>" 
                                           class="btn btn-success btn-sm">
                                            <i class="fas fa-download"></i> Download
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?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() {
        document.getElementById('sidebar').classList.toggle('active');
        document.getElementById('content').classList.toggle('active');
    }
</script>
</body>
</html>
