<?php
include '../includes/auth.php';
include '../includes/db.php';
include 'header.php'; 
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Research</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- TinyMCE CDN -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>

<script>
tinymce.init({
  selector: 'textarea',
  height: 400,
  plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table emoticons template paste wordcount',
  toolbar: 'undo redo | formatselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist | link image media | code fullscreen | forecolor backcolor',
  menubar: true,
  branding: false
});
</script>

<style>
body { background: #f3f5f9; font-family: "Segoe UI", sans-serif; }
.admin-container {
    width: 85%; max-width: 900px; margin: 50px auto; background: #fff;
    padding: 30px 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.admin-container h2 {
    text-align: center; margin-bottom: 25px; color: #333;
    font-size: 1.8rem; border-bottom: 2px solid #007bff; display: inline-block;
    padding-bottom: 5px;
}
.research-form { display: flex; flex-direction: column; gap: 15px; }
.research-form label { font-weight: bold; color: #444; }
.research-form input[type="text"],
.research-form input[type="file"],
.research-form select,
.research-form textarea {
    padding: 10px; border: 1px solid #ccc; border-radius: 8px; font-size: 1rem; width: 100%;
}
.research-form input[type="file"] { background: #f9f9f9; }
.btn {
    width: 200px; background: #007bff; color: white; padding: 10px 15px;
    border: none; border-radius: 6px; cursor: pointer; font-weight: bold;
    transition: 0.3s; align-self: center;
}
.btn:hover { background: #0056b3; }
.success, .error {
    padding: 12px; border-radius: 6px; text-align: center; margin-bottom: 15px;
}
.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
</style>
</head>
<body>

<div class="admin-container">
    <h2>Add New Research</h2>

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $title = trim($_POST['title']);
        $category = $_POST['category'];
        $status = $_POST['status'];
        $abstract = trim($_POST['abstract']);
        $content = trim($_POST['content']);
        $link = trim($_POST['external_link']);

        if (!empty($title) && !empty($abstract) && !empty($content)) {
            $stmt = $conn->prepare("INSERT INTO research (title, category, status, abstract, content, external_link) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssss", $title, $category, $status, $abstract, $content, $link);

            if ($stmt->execute()) {
                $research_id = $stmt->insert_id;
                $stmt->close();

                // Handle image uploads
                $targetDir = "../Images/research/";
                if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

                $files = $_FILES['images'];
                for ($i = 0; $i < count($files['name']); $i++) {
                    if (!empty($files['name'][$i])) {
                        $fileName = time() . '_' . $i . '_' . basename($files['name'][$i]);
                        $targetFile = $targetDir . $fileName;

                        if (move_uploaded_file($files['tmp_name'][$i], $targetFile)) {
                            $imagePath = "Images/research/" . $fileName;

                            $imgStmt = $conn->prepare("INSERT INTO research_images (research_id, image_path) VALUES (?, ?)");
                            $imgStmt->bind_param("is", $research_id, $imagePath);
                            $imgStmt->execute();
                            $imgStmt->close();
                        }
                    }
                }

                echo "<p class='success'>✅ Research added successfully!</p>";
            } else {
                echo "<p class='error'>❌ Failed to save research.</p>";
            }
        } else {
            echo "<p class='error'>⚠️ Title, abstract, and content cannot be empty.</p>";
        }
    }
    ?>

    <form action="" method="POST" enctype="multipart/form-data" class="research-form" onsubmit="tinymce.triggerSave();">
        <label for="title">Research Title:</label>
        <input type="text" name="title" id="title" required>

        <label for="category">Category:</label>
        <select name="category" id="category" required>
            <option value="">Select Category</option>
            <option>Clinical Research</option>
            <option>Laboratory Research</option>
            <option>Public Health</option>
            <option>Innovation</option>
        </select>

        <label for="status">Status:</label>
        <select name="status" id="status">
            <option>Published</option>
            <option>Ongoing</option>
            <option>Completed</option>
        </select>

        <label for="abstract">Abstract:</label>
        <textarea name="abstract" id="abstract"></textarea>

        <label for="content">Full Research Content:</label>
        <textarea name="content" id="content"></textarea>

        <label for="images">Upload Images (multiple allowed):</label>
        <input type="file" name="images[]" id="images" accept="image/*" multiple>

        <label for="external_link">External Link (optional):</label>
        <input type="text" name="external_link" id="external_link">

        <button type="submit" class="btn">Add Research</button>
    </form>
</div>

<?php include '../includes/footer.php'; ?>

</body>
</html>
