<?php
// Database connection
$host = "localhost";
$username = "root";
$password = "";
$database = "epaper";

$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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']);
    
    // Handle file upload
    if (isset($_FILES['p_path']) && $_FILES['p_path']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['p_path'];
        $fileName = $file['name'];
        $fileTmp = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExt = ['pdf'];

        if (!in_array($fileExt, $allowedExt)) {
            echo "Error: Only PDF files are allowed.";
            exit;
        }

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

        $uniqueFileName = uniqid('epaper_', true) . '.' . $fileExt;
        $uploadDir = "uploads/";
        $uploadPath = $uploadDir . $uniqueFileName;

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        if (move_uploaded_file($fileTmp, $uploadPath)) {
            // Insert data into database
            $sql = "INSERT INTO epapers (p_name, p_date, p_type, p_status, p_path) 
                    VALUES ('$p_name', '$p_date', '$p_type', '$p_status', '$uniqueFileName')";
            if ($conn->query($sql) === TRUE) {
                echo "E-Paper record added successfully.";
            } else {
                echo "Error: " . $conn->error;
            }
        } else {
            echo "Error: Failed to upload file.";
        }
    } else {
        echo "Error: File upload failed.";
    }
} else {
    echo "Invalid request method.";
}

$conn->close();
?>
