<?php
include '../includes/db.php';
include 'header.php'; 
// Enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Invalid request method.");
    }

    // Collect and sanitize POST data
    $title = $_POST['title'] ?? '';
    $category = $_POST['category'] ?? '';
    $status = $_POST['status'] ?? '';
    $abstract = $_POST['abstract'] ?? '';
    $content = $_POST['content'] ?? '';
    $link = $_POST['external_link'] ?? '';

    if (empty($title) || empty($category) || empty($status) || empty($abstract) || empty($content)) {
        throw new Exception("Please fill in all required fields.");
    }

    // Prepare statement
    $stmt = $conn->prepare("
        INSERT INTO research (title, category, status, abstract, content, external_link)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

    $stmt->bind_param("ssssss", $title, $category, $status, $abstract, $content, $link);

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    $research_id = $stmt->insert_id;

    /* Upload images */
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp) {
            $originalName = $_FILES['images']['name'][$key];
            $name = time() . '_' . $key . '_' . basename($originalName);

            $uploadDir = "../Images/research/";
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $uploadPath = $uploadDir . $name;
            if (!move_uploaded_file($tmp, $uploadPath)) {
                throw new Exception("Failed to upload image: " . $originalName);
            }

            $dbPath = "Images/research/" . $name;

            if (!$conn->query("INSERT INTO research_images (research_id, image_path) VALUES ($research_id,'$dbPath')")) {
                throw new Exception("Failed to insert image into DB: " . $conn->error);
            }
        }
    }

    echo "<p style='padding:20px; background:#d4edda; color:#155724;'>Research saved successfully! <a href='research-list.php'>Go back to list</a></p>";

} catch (Exception $e) {
    echo "<p style='padding:20px; background:#f8d7da; color:#721c24;'><strong>Error:</strong> " . $e->getMessage() . "</p>";
}
?>
