<?php
include("config.inc.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate inputs
    $p_name = $conn->real_escape_string($_POST['p_name']);
    $p_date = $conn->real_escape_string($_POST['p_date']);
    $p_type = $conn->real_escape_string($_POST['p_type']);
    $p_status = $conn->real_escape_string($_POST['p_status']);

    // Prepare file upload paths
    $uploadDir = "uploads/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $coverDir = "covers/";
    if (!is_dir($coverDir)) {
        mkdir($coverDir, 0777, true);
    }

    // Rename the PDF file
    $pdfFileName = "{$p_date}_{$p_type}.pdf";
    $pdfUploadPath = $uploadDir . $pdfFileName;

    // Validate and upload PDF file
    if (isset($_FILES['p_path']) && $_FILES['p_path']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['p_path'];
        $fileTmp = $file['tmp_name'];
        $fileExt = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

        if ($fileExt !== 'pdf') {
            echo "Error: Only PDF files are allowed.";
            exit;
        }

        if ($file['size'] > 50 * 1024 * 1024) { // 2MB file size limit
            echo "Error: PDF file size exceeds 2MB.";
            exit;
        }

        if (!move_uploaded_file($fileTmp, $pdfUploadPath)) {
            echo "Error: Failed to upload PDF file.";
            exit;
        }
    } else {
        echo "Error: PDF file upload failed.";
        exit;
    }

    // Check if a cover photo is uploaded
    $coverFileName = "{$pdfFileName}.jpg";
    $coverUploadPath = $coverDir . $coverFileName;

    if (isset($_FILES['cover_photo']) && $_FILES['cover_photo']['error'] === UPLOAD_ERR_OK) {
        $coverFile = $_FILES['cover_photo'];
        $coverTmp = $coverFile['tmp_name'];
        $coverExt = strtolower(pathinfo($coverFile['name'], PATHINFO_EXTENSION));
        $allowedImageExt = ['jpg', 'jpeg', 'png'];

        if (!in_array($coverExt, $allowedImageExt)) {
            echo "Error: Only JPG, JPEG, or PNG files are allowed for the cover photo.";
            exit;
        }

        if ($coverFile['size'] > 2 * 1024 * 1024) { // 2MB file size limit
            echo "Error: Cover photo size exceeds 2MB.";
            exit;
        }

        if (!move_uploaded_file($coverTmp, $coverUploadPath)) {
            echo "Error: Failed to upload cover photo.";
            exit;
        }
    } else {
        $coverFileName = null; // No cover uploaded
    }

    // Insert data into the database
    $sql = "INSERT INTO epapers (p_name, p_date, p_type, p_status, p_path) 
            VALUES ('$p_name', '$p_date', '$p_type', '$p_status', '$pdfFileName')";
    if ($conn->query($sql) === TRUE) {
        echo "E-Paper uploaded successfully.";
        if ($coverFileName) {
            echo "<br>Cover photo uploaded successfully.";
        }
    } else {
        echo "Error: " . $conn->error;
    }

    $conn->close();
}
?>
