<?php
session_start();
ob_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

// Check for authorized roles: superadmin, admin, or md
$allowed_roles = ['superadmin', 'admin', 'md'];
if (!isset($_SESSION['role']) || !in_array(strtolower($_SESSION['role']), $allowed_roles)) {
    echo "Access denied.";
    exit();
}

// Generate CSRF token if not set
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf_token = $_SESSION['csrf_token'];

include 'config.php';

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $message = '<div class="alert alert-danger">Invalid CSRF token.</div>';
    } else {
        $title = trim($_POST['title'] ?? '');
        $created_by = $_SESSION['user_id'];

        if ($title === '') {
            $message = '<div class="alert alert-danger">Title is required.</div>';
        } elseif (strlen($title) > 255) {
            $message = '<div class="alert alert-danger">Title must be less than 255 characters.</div>';
        } elseif (!isset($_FILES['pdf_file']) || $_FILES['pdf_file']['error'] === UPLOAD_ERR_NO_FILE) {
            $message = '<div class="alert alert-danger">PDF file is required.</div>';
        } else {
            $target_dir = 'Uploads/';
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0777, true);
            }

            $file_name = basename($_FILES['pdf_file']['name']);
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            if ($file_ext !== 'pdf') {
                $message = '<div class="alert alert-danger">Only PDF files are allowed.</div>';
            } elseif ($_FILES['pdf_file']['size'] > 5 * 1024 * 1024) {
                $message = '<div class="alert alert-danger">File size must be less than 5MB.</div>';
            } else {
                $unique_name = uniqid('doc_', true) . '.' . $file_ext;
                $pdf_file_path = $target_dir . $unique_name;

                if (!move_uploaded_file($_FILES['pdf_file']['tmp_name'], $pdf_file_path)) {
                    $message = '<div class="alert alert-danger">Error uploading PDF file. Check Uploads directory permissions.</div>';
                } else {
                    $stmt = $conn->prepare("INSERT INTO documents (title, created_by, pdf_file) VALUES (?, ?, ?)");
                    if (!$stmt) {
                        $message = '<div class="alert alert-danger">Database error: Unable to prepare statement.</div>';
                    } else {
                        $stmt->bind_param("sis", $title, $created_by, $pdf_file_path);
                        if ($stmt->execute()) {
                            $_SESSION['message'] = "Document created successfully.";
                            header("Location: manage_documents.php");
                            exit();
                        } else {
                            $message = '<div class="alert alert-danger">Database error: ' . htmlspecialchars($stmt->error) . '</div>';
                        }
                        $stmt->close();
                    }
                }
            }
        }
    }
}

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Document - Admin Dashboard</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: #1e3a8a;
            --secondary-color: #22c55e;
            --accent-color: #f97316;
            --sidebar-bg: #1f2937;
            --card-bg: #ffffff;
            --text-color: #111827;
            --hover-bg: #3b82f6;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background-color: #f3f4f6;
            margin: 0;
            display: flex;
            min-height: 100vh;
            color: var(--text-color);
        }

        .sidebar {
            width: 280px;
            background: var(--sidebar-bg);
            color: #ffffff;
            padding: 20px;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-280px);
            transition: transform 0.3s ease;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar.active {
            transform: translateX(0);
        }

        .sidebar h2 {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 20px;
            color: var(--secondary-color);
            text-align: center;
        }

        .sidebar a {
            color: #ffffff;
            text-decoration: none;
            padding: 12px 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-radius: 8px;
            margin-bottom: 8px;
            font-size: 1rem;
            transition: background 0.2s ease;
        }

        .sidebar a:hover, .sidebar a.active {
            background: var(--hover-bg);
        }

        .sidebar .dropdown-menu {
            background: #374151;
            border: none;
            padding: 8px 0;
            width: 100%;
            margin-left: 10px;
            border-radius: 6px;
        }

        .sidebar .dropdown-menu a {
            color: #ffffff;
            padding: 10px 25px;
            font-size: 0.95rem;
        }

        .sidebar .dropdown-menu a:hover {
            background: var(--hover-bg);
        }

        .sidebar .dropdown-toggle::after {
            margin-left: auto;
        }

        .hamburger {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: var(--primary-color);
            color: #ffffff;
            border: none;
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .hamburger:hover {
            background: var(--hover-bg);
        }

        .content {
            flex: 1;
            padding: 30px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }

        .content.active {
            margin-left: 280px;
        }

        h1 {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 20px;
            color: var(--primary-color);
            text-align: center;
        }

        .form-container {
            max-width: 1200px;
            margin: 0 auto 30px;
            background: var(--card-bg);
            padding: 25px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            border-radius: 12px;
        }

        .form-container input[type="text"],
        .form-container input[type="file"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 0.95rem;
        }

        .form-container button {
            background: var(--primary-color);
            color: #ffffff;
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            transition: background 0.2s ease;
        }

        .form-container button:hover {
            background: var(--hover-bg);
        }

        .btn-secondary {
            background: #6c757d;
            border: none;
            border-radius: 8px;
            padding: 12px 20px;
            font-size: 1rem;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .alert {
            border-radius: 8px;
        }

        @media (max-width: 576px) {
            .sidebar {
                width: 240px;
                transform: translateX(-240px);
            }

            .content.active {
                margin-left: 240px;
            }

            h1 {
                font-size: 1.5rem;
            }

            .form-container {
                padding: 15px;
            }

            .form-container input[type="text"],
            .form-container input[type="file"],
            .form-container button {
                font-size: 0.85rem;
            }
        }
    </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 class="dropdown-toggle active" href="<?php echo (strtolower($_SESSION['role']) === 'md') ? 'dashboard_md.php' : 'dashboard_admin.php'; ?>" aria-expanded="false">
            <i class="fas fa-home me-2"></i> <?php echo (strtolower($_SESSION['role']) === 'md') ? 'MD Dashboard' : 'Organisation Chart'; ?>
        </a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-home me-2"></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" aria-expanded="false">
                <i class="fas fa-users me-2"></i> CAB
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="attendance.php">Attendance Dashboard</a></li>
                <li><a class="dropdown-item" href="payroll.php">Payroll Dashboard</a></li>
                <a href="mobileattendance.php" class="menu-item"><i class="fas fa-clock"></i><span>Daily Attendance Report</span></a>
                <a href="daily_reports_dashboard.php" class="menu-item"><i class="fas fa-file-lines"></i><span>Daily Report Dashboard</span></a>
                <li><a class="dropdown-item" href="ot_dashboard.php">OT Dashboard</a></li>
                <li><a class="dropdown-item" href="company_holidays.php">Company Holidays</a></li>
                <li><a class="dropdown-item" href="hr_approval_salary.php">Advance Dashboard</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 Dashboard</a></li>
                <li><a class="dropdown-item" href="grievance_dashboard.php">Grievance Dashboard</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-user me-2"></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" aria-expanded="false">
                <i class="fas fa-book me-2"></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" aria-expanded="false">
                <i class="fas fa-star me-2"></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 me-2"></i> Logout</a>
    </div>
    
    <!-- Main Content -->
    <div class="content" id="content">
        <h1>Create Document</h1>
        <div class="container">
            <?php if ($message) echo $message; ?>
            <div class="card p-4 form-container">
                <h3 class="mb-3">New Document</h3>
                <form action="create_document.php" method="post" enctype="multipart/form-data" onsubmit="return validateForm()">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                    <div class="mb-3">
                        <label for="title" class="form-label">Document Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" id="title" class="form-control" required maxlength="255">
                    </div>
                    <div class="mb-3">
                        <label for="pdf_file" class="form-label">Upload PDF (Max 5MB) <span class="text-danger">*</span></label>
                        <input type="file" name="pdf_file" id="pdf_file" class="form-control" accept="application/pdf" required>
                    </div>
                    <div class="d-flex justify-content-between">
                        <a href="manage_documents.php" class="btn btn-secondary">Back</a>
                        <button type="submit" class="btn btn-primary">Create Document</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <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');
        }

        function validateForm() {
            const title = document.getElementById('title').value.trim();
            const pdfFile = document.getElementById('pdf_file').files[0];

            if (!title) {
                alert('Document title is required.');
                return false;
            }
            if (title.length > 255) {
                alert('Title must be less than 255 characters.');
                return false;
            }
            if (!pdfFile) {
                alert('PDF file is required.');
                return false;
            }
            const fileExt = pdfFile.name.split('.').pop().toLowerCase();
            if (fileExt !== 'pdf') {
                alert('Only PDF files are allowed.');
                return false;
            }
            if (pdfFile.size > 5 * 1024 * 1024) {
                alert('File size must be less than 5MB.');
                return false;
            }
            return true;
        }
    </script>
</body>
</html>