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

if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit();
}

// Check if the document ID is provided in the URL
if (isset($_GET['id'])) {
    $document_id = $_GET['id'];

    // Fetch the document details
    $stmt = $conn->prepare("SELECT * FROM documents WHERE id = ?");
    $stmt->bind_param("i", $document_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $document = $result->fetch_assoc();
    $stmt->close();
}

// Handle form submission for updating the document
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $document_title = mysqli_real_escape_string($conn, $_POST['title']);
    $document_content = mysqli_real_escape_string($conn, $_POST['content']);

    // Check if a new file is uploaded
    if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] == 0) {
        // Handle the uploaded PDF file
        $pdf_file = $_FILES['pdf_file'];
        $pdf_file_name = $pdf_file['name'];
        $pdf_file_tmp = $pdf_file['tmp_name'];
        $pdf_file_path = 'Uploads/' . basename($pdf_file_name);

        // Move the uploaded file to the server directory
        if (move_uploaded_file($pdf_file_tmp, $pdf_file_path)) {
            // Update the document to include the PDF path
            $update_query = "UPDATE documents SET title = ?, content = ?, pdf_file = ? WHERE id = ?";
            $stmt = $conn->prepare($update_query);
            $stmt->bind_param("sssi", $document_title, $document_content, $pdf_file_path, $document_id);
        } else {
            $_SESSION['error'] = "Error uploading the file.";
        }
    } else {
        // If no file is uploaded, update only the text content
        $update_query = "UPDATE documents SET title = ?, content = ? WHERE id = ?";
        $stmt = $conn->prepare($update_query);
        $stmt->bind_param("ssi", $document_title, $document_content, $document_id);
    }

    if ($stmt->execute()) {
        $_SESSION['message'] = "Document updated successfully";
    } else {
        $_SESSION['error'] = "Error: " . $stmt->error;
    }
    $stmt->close();
    header("Location: manage_documents.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit 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>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar Styles */
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 20px 15px;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
            transition: transform 0.3s ease;
        }

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

        .sidebar h2 {
            font-size: 1.25rem;
            margin: 0 0 20px;
            text-align: center;
            font-weight: 600;
        }

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

        .sidebar a:hover {
            background: #1abc9c;
        }

        .sidebar a.active {
            background: #1abc9c;
            font-weight: 500;
        }

        .sidebar .dropdown-menu {
            background: #34495e;
            border: none;
            padding: 0;
            width: 100%;
            margin-left: 10px;
        }

        .sidebar .dropdown-menu a {
            color: #fff;
            padding: 8px 25px;
            font-size: 0.85rem;
        }

        .sidebar .dropdown-menu a:hover {
            background: #1abc9c;
        }

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

        /* Hamburger Button */
        .hamburger {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: #2c3e50;
            color: #fff;
            border: none;
            padding: 10px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .hamburger:hover {
            background: #1abc9c;
        }

        /* Content Area */
        .content {
            flex: 1;
            padding: 20px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }

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

        h1 {
            font-size: 1.5rem;
            margin-bottom: 20px;
            color: #333;
            text-align: center;
        }

        .form-container {
            max-width: 1200px;
            margin: 0 auto 30px;
            background: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

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

        .form-container textarea {
            height: 100px;
            resize: vertical;
        }

        .form-container button {
            background: #1abc9c;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
        }

        .form-container button:hover {
            opacity: 0.9;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

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

        /* Responsive Design */
        @media (max-width: 576px) {
            .sidebar {
                width: 200px;
                padding: 15px 10px;
            }

            .sidebar h2 {
                font-size: 1rem;
            }

            .sidebar a {
                font-size: 0.8rem;
                padding: 8px 10px;
            }

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

            h1 {
                font-size: 1.2rem;
            }

            .form-container input[type="text"],
            .form-container textarea,
            .form-container input[type="file"],
            .form-container button {
                font-size: 0.8rem;
            }
        }
    </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="dashboard_admin.php"><i class="fas fa-home"></i> Organisation Chart</a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                <i class="fas fa-home"></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 active" 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="#" data-bs-toggle="dropdown">
                <i class="fas fa-users"></i> CAB
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="payroll_dashboard.php">Payroll</a></li>
                <li><a class="dropdown-item" href="leave_dashboard.php">Leave</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="#" 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="#" 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="#" 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">
        <h1 class="text-center text-primary">Edit Document</h1>
        <div class="container">
            <?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="card p-4 form-container">
                <h3 class="mb-3">Edit Document</h3>
                <form method="POST" action="edit_document.php?id=<?php echo $document['id']; ?>" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="title" class="form-label">Document Title <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($document['title'], ENT_QUOTES, 'UTF-8'); ?>" required maxlength="255">
                    </div>
                    <div class="mb-3">
                        <label for="content" class="form-label">Document Content <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="content" name="content" rows="10" required><?php echo htmlspecialchars($document['content'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="pdf_file" class="form-label">Upload PDF (Max 5MB, optional)</label>
                        <input type="file" class="form-control" id="pdf_file" name="pdf_file" accept="application/pdf">
                        <?php if (!empty($document['pdf_file'])): ?>
                            <small class="text-muted">Current file: <?php echo basename($document['pdf_file']); ?></small>
                        <?php endif; ?>
                    </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">Update 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');
        }
    </script>
</body>
</html>