<?php
include '../koneksi.php';
$judul_buku = $_POST['judul_buku']; 
$penulis = $_POST['penulis'];
$tahun_terbit = $_POST['tahun_terbit'];

if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
    $rand = rand();
    $ekstensi_diperbolehkan = array('png', 'jpg', 'jpeg', 'gif');
    $filename = $_FILES['foto']['name'];
    $filesize = $_FILES['foto']['size'];
    $file_tmp = $_FILES['foto']['tmp_name'];
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    if (!in_array(strtolower($ext), $ekstensi_diperbolehkan)) {
        header('Location: index.php?alert=gagal_ekstensi');
        exit();
    } 

    if ($filesize > 1044070) {
        header('Location: index.php?alert=gagal_ukuran');
        exit();
    }

    $target_dir = "../img/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    $foto = $rand . '_' . $filename;
    $target_file = $target_dir . $foto;

    if (move_uploaded_file($file_tmp, $target_file)) {
        $query = "INSERT INTO buku (judul_buku, penulis, tahun_terbit, foto) 
                 VALUES ('$judul_buku', '$penulis', '$tahun_terbit', '$foto')";
        
        if (mysqli_query($koneksi, $query)) {
            header('Location: ../index.php?alert=berhasil');
            exit();
        } else {
            header('Location: index.php?alert=gagal_insert');
            exit();
        }
    } else {
        header('Location: index.php?alert=gagal_upload');
        exit();
    }
} else {
    header('Location: index.php?alert=tanpa_file');
    exit();
}