<?php
include("includes/db.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $title  = trim($_POST['btitle'] ?? '');
    $author = trim($_POST['author'] ?? '');
    $pub    = trim($_POST['pub'] ?? '');
    $lan    = trim($_POST['lan'] ?? '');
    $isbn   = trim($_POST['isbn'] ?? '');
    $cat    = trim($_POST['cat'] ?? '');
    $copy   = trim($_POST['copy'] ?? '');
    $about  = trim($_POST['about'] ?? '');

    if (
        $title === '' ||
        $author === '' ||
        $pub === '' ||
        $lan === '' ||
        $isbn === '' ||
        $cat === '' ||
        $copy === '' ||
        $about === ''
    ) {
        die('All fields are required.');
    }

    if (!isset($_FILES['photo'])) {
        die('Book image is required.');
    }

    $file = $_FILES['photo'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        die('Image upload failed.');
    }

    if ($file['size'] <= 0) {
        die('Uploaded image is empty.');
    }

    $maxSize = 5 * 1024 * 1024; // 5MB
    if ($file['size'] > $maxSize) {
        die('Image is too large. Maximum allowed size is 5MB.');
    }

    $originalName = $file['name'];
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    $allowedExtensions = ['jpg', 'jpeg', 'png'];
    if (!in_array($extension, $allowedExtensions, true)) {
        die('Invalid image type. Only JPG, JPEG, and PNG are allowed.');
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $allowedMimeTypes = [
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png' => 'image/png',
    ];

    if (!isset($allowedMimeTypes[$extension]) || $mimeType !== $allowedMimeTypes[$extension]) {
        die('Invalid image file.');
    }

    if (getimagesize($file['tmp_name']) === false) {
        die('Uploaded file is not a valid image.');
    }

    $uploadDir = __DIR__ . '/bookimage/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0775, true)) {
            die('Failed to create upload directory.');
        }
    }

    $newImageName = uniqid('book_', true) . '.' . $extension;
    $destination = $uploadDir . $newImageName;

    // Generate book ID
    $idn = uniqid('', true) . time();

    // Set date properly
    $date = date('Y-m-d H:i:s');

    // Upload image first
    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        die('Failed to save uploaded image.');
    }

    // Prepare insert query
    $stmt = mysqli_prepare(
        $db,
        "INSERT INTO books (image, btitle, author, pub, lang, isbn, cat, copyright, aboutbook, idn, date)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );

    if (!$stmt) {
        if (file_exists($destination)) {
            unlink($destination);
        }
        die('Failed to prepare database query.');
    }

    mysqli_stmt_bind_param(
        $stmt,
        "sssssssssss",
        $newImageName,
        $title,
        $author,
        $pub,
        $lan,
        $isbn,
        $cat,
        $copy,
        $about,
        $idn,
        $date
    );

    if (!mysqli_stmt_execute($stmt)) {
        if (file_exists($destination)) {
            unlink($destination);
        }
        mysqli_stmt_close($stmt);
        die('Failed to save book to database.');
    }

    mysqli_stmt_close($stmt);

    echo "<script>alert('Book uploaded successfully');</script>";
    echo "<script>setTimeout(function(){ location.href='addbooks.php'; }, 2000);</script>";
}
