<?php include("includes/db.php"); ?>
<?php
if ($_SESSION['usertype'] != 'admin') {
    header('location:index.php');
}
?>
<?php

if (isset($_POST['ldel'])) {
    $lid = $_POST['id'];

    $sql = mysqli_query($db, "DELETE FROM link WHERE id=$lid");
    if ($sql) {

        echo " <script> alert('Link Deleted ');</script> ";
    } else {
        echo "<p id='display' style='background-color:red; font-weight:bold;color:white;box-shadow:0 0 5px #eee;padding:0px; border-radius:5px;font-size:16px;text-align:center;'>Something Went Wrong</p>";
    }
}

?>

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['done'])) {
    $idn = $_GET['idn'] ?? null;

    if (!$idn) {
        die('Invalid book id.');
    }

    if (!isset($_FILES['photo'])) {
        die('No file uploaded.');
    }

    $file = $_FILES['photo'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        die('File upload failed.');
    }

    if ($file['size'] <= 0) {
        die('Uploaded file is empty.');
    }

    // 5MB max
    $maxSize = 5 * 1024 * 1024;
    if ($file['size'] > $maxSize) {
        die('File is too large. Maximum allowed size is 5MB.');
    }

    $uploadDir = __DIR__ . '/bookimage/';
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0775, true)) {
            die('Failed to create upload directory.');
        }
    }

    $originalName = $file['name'];
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    $allowedExtensions = ['jpg', 'jpeg', 'png'];
    if (!in_array($extension, $allowedExtensions, true)) {
        die('Invalid file extension. Only JPG, JPEG, and PNG are allowed.');
    }

    // Validate MIME type using finfo
    $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.');
    }

    // Extra validation to ensure it is actually an image
    $imageInfo = getimagesize($file['tmp_name']);
    if ($imageInfo === false) {
        die('Uploaded file is not a valid image.');
    }

    // Generate unique filename
    $newFileName = uniqid('book_', true) . '.' . $extension;
    $destination = $uploadDir . $newFileName;

    // Move file first
    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        die('Failed to save uploaded image.');
    }

    // Update DB only after upload succeeds
    $stmt = mysqli_prepare($db, "UPDATE books SET image = ? WHERE idn = ?");
    if (!$stmt) {
        // remove uploaded file if db preparation fails
        if (file_exists($destination)) {
            unlink($destination);
        }
        die('Database error.');
    }

    mysqli_stmt_bind_param($stmt, "ss", $newFileName, $idn);

    if (!mysqli_stmt_execute($stmt)) {
        // remove uploaded file if db update fails
        if (file_exists($destination)) {
            unlink($destination);
        }
        mysqli_stmt_close($stmt);
        die('Failed to update database.');
    }

    if (mysqli_stmt_affected_rows($stmt) < 0) {
        if (file_exists($destination)) {
            unlink($destination);
        }
        mysqli_stmt_close($stmt);
        die('No record updated.');
    }

    mysqli_stmt_close($stmt);

    echo "<script>alert('Image uploaded successfully');</script>";
}
?>

<?php
if (isset($_POST['addlink'])) {
    $idn = $_GET['idn'];
    $lname = $_POST['lname'];
    $link = $_POST['link'];
    $sqli = mysqli_query($db, "INSERT INTO link(name,link,idn,date) VALUES('$lname','$link','$idn','$date')");
    if ($sqli) {


        echo " <script> alert('Link Added');</script> ";
    } else {
        echo "<script>setTimeout(\"location.href='editbooks.php'\",3000);</script>";
        echo "<p style='background:red;color:white;box-shadow:0 0 5px #eee;padding:30px:border-radius:5px;font-size:18px;text-align:center;'>Something went wrong</p>";
    }
}
?>

<?php

if (isset($_POST['del'])) {
    $idn = $_POST['idn'];

    $image = $_POST['img'];
    unlink("bookimage/" . $image);
    $sql = mysqli_query($db, "DELETE FROM books WHERE idn='$idn' ");

    if ($sql) {
        $sql = mysqli_query($db, "DELETE FROM link WHERE idn='$idn' ");

        echo " <script> alert('Deleted Successfully ');</script> ";
        echo "<script>setTimeout(\"location.href='adminbook.php'\",1000);</script>";

        exit();
    } else {
        echo "<p id='display' style='background-color:red; font-weight:bold;color:white;box-shadow:0 0 5px #eee;padding:0px; border-radius:5px;font-size:16px;text-align:center;'>Something Went Wrong</p>";
    }
}


?>
<?php

if (isset($_POST['update'])) {
    $idn = mysqli_real_escape_string($db, $_POST['idn']);
    $title = mysqli_real_escape_string($db, $_POST['btitle']);
    $author = mysqli_real_escape_string($db, $_POST['author']);
    $pub = mysqli_real_escape_string($db, $_POST['pub']);
    $lang = mysqli_real_escape_string($db, $_POST['lang']);
    $isbn = mysqli_real_escape_string($db, $_POST['isbn']);
    $cat = mysqli_real_escape_string($db, $_POST['cat']);
    $copy = mysqli_real_escape_string($db, $_POST['copy']);
    $about = mysqli_real_escape_string($db, $_POST['about']);


    $sql = mysqli_query($db, "UPDATE books SET btitle='$title',author='$author',pub='$pub',lang='$lang',isbn='$isbn',cat='$cat',copyright='$copy',aboutbook='$about' WHERE idn='$idn'");

    if ($sql) {

        echo " <script> alert(' Updated Successfully ');</script> ";
        // echo "<p id='display' style='background-color:green; font-weight:bold;color:white;box-shadow:0 0 5px #eee;padding:0px; border-radius:5px;font-size:16px;text-align:center;'>Updated Successful</p>";

    } else {
        echo "<p id='display' style='background-color:red; font-weight:bold;color:white;box-shadow:0 0 5px #eee;padding:0px; border-radius:5px;font-size:16px;text-align:center;'>Something Went Wrong</p>";
        echo "<script>setTimeout(\"location.href='editbooks.php'\",3000);</script>";
    }
}

?>



<?php
$idn = $_GET['idn'];
$sql = mysqli_query($db, "SELECT * FROM books WHERE idn='$idn' ");
$result = mysqli_fetch_assoc($sql);
$rows = mysqli_num_rows($sql);
if ($rows == 0) {
    header('location:adminbook.php');
    exit();
}
$id = $result['id'];
$image = $result['image'];
$title = $result['btitle'];
$author = $result['author'];
$pub = $result['pub'];
$lang = $result['lang'];
$isbn = $result['isbn'];
$cat = $result['cat'];
$copy = $result['copyright'];
$about = $result['aboutbook'];

?>
<?php
if ($_SESSION['usertype'] != 'admin') {
    header('location:index.php');
}
?>


<!-- header starts here -->
<?php include('includes/header.php') ?>
<!-- header ends here -->


<section class="hero-wrap hero-wrap-2" style="background-image: url('images/bg_5.jpg');" data-stellar-background-ratio="0.5">
    <div class="overlay"></div>
    <div class="container">
        <div class="row no-gutters slider-text align-items-center justify-content-center">
            <div class="col-md-9 ftco-animate mb-0 text-center">
                <p class="breadcrumbs mb-0"><span class="mr-2"><a href="index.html">Home <i class="fa fa-chevron-right"></i></a></span> <span>Book Store <i class="fa fa-chevron-right"></i></span></p>
                <h1 class="mb-0 bread">Edit Book</h1>
            </div>
        </div>
    </div>
</section>
<style>
    #subbox {
        display: none;
    }
</style>
<script>
    function show() {
        var box = document.getElementById('subbox');
        box.style.display = "block";
    }
</script>

<section class="ftco-section">
    <div class="container">
        <center class="p-4">
            <input type="submit" name="add" value="ADD PURCHASE LINK" class="btn btn-danger " onClick="show()">

        </center>
        <div class="bg-danger text-white p-4 " id="subbox">
            <h4 class="mb-0 bread text-white text-center">Add Puchase Link</h4>

            <form action="" method="POST" id="ajax_form" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="">NAME OF LINK</label>
                    <input type="text" class="form-control" name="lname" id="" aria-describedby="helpId">
                </div>

                <div class="form-group">
                    <label for="">LINK</label>
                    <input type="text" class="form-control" name="link" id="" aria-describedby="helpId">
                </div>

                <center>
                    <input name="addlink" id="" class="btn btn-white" type="submit" value="ADD">

                </center>
            </form>
        </div>
    </div>
</section>



<section class="">
    <div class="container">
        <div class="row justify-content-center mb-5">
            <div class="col-md-7 heading-section text-center ftco-animate">
                <span class="subheading">Books</span>
                <h4><?php echo $title ?></h4>
            </div>
        </div>
        <div class="row d-flex">
            <div class="col-md-6 d-flex ftco-animate">
                <div class="blog-entry justify-content-end">
                    <form action="" method="POST" enctype="multipart/form-data">
                        <div class="text text-center">
                            <img src="bookimage/<?php echo $image ?>" class="img-fluid" alt="" id="pic">
                            <div class="form-group bg-danger">
                                <label for="uploadfile" class="text-white text-center"><i class="fa fa-camera" aria-hidden="true"></i> Select Photo</label>
                                <input style="display:none" accept="bookimage/*" oninput="pic.src=window.URL.createObjectURL(this.files[0]);pic.style.display='block';err.innerHTML='' " type="file" class="form-control" name="photo" id="uploadfile" aria-describedby="helpId" placeholder="" required>
                            </div>
                            <button type="submit" name="done" class="btn btn-success btn-md">Done</button>


                    </form>
                </div>
            </div>

        </div>

        <div class="col-md-6 d-flex ftco-animate">
            <div class="blog-entry justify-content-end">
                <div class="text text-center">
                    <p class="heading mb-3">
                    <form action="" method="POST" id="ajax_form" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="">Title Of Book</label>
                            <input type="text" class="form-control" name="btitle" value="<?php echo $title ?>">
                        </div>
                        </p>
                        <div id="accordianId" role="tablist" aria-multiselectable="true">
                            <div class="card">
                                <div class="card-header" role="tab" id="section1HeaderId">
                                    <h5 class="mb-0">
                                        <a data-toggle="collapse" data-parent="#accordianId" href="#section1ContentId" aria-expanded="true" aria-controls="section1ContentId">
                                            Book Details
                                        </a>
                                    </h5>
                                </div>
                                <div id="section1ContentId" class="collapse in" role="tabpanel" aria-labelledby="section1HeaderId">
                                    <div class="card-body">
                                        <p>
                                        <div class="form-group">
                                            <label for="">Author Of Book</label>
                                            <input type="text" class="form-control" name="author" value="<?php echo $author ?>">
                                        </div>
                                        </p>
                                        <p>
                                        <div class="form-group">
                                            <label for="">Publication Date</label>
                                            <input type="text" class="form-control" name="pub" value="<?php echo $pub ?>">
                                        </div>
                                        </p>
                                        <p>
                                        <div class="form-group">
                                            <label for="">ISBN atollment</label>
                                            <input type="text" class="form-control" name="isbn" value="<?php echo $isbn ?>">
                                        </div>
                                        </p>
                                        <p>
                                        <div class="form-group">
                                            <label for="">Category</label>
                                            <input type="text" class="form-control" name="cat" value="<?php echo $cat ?>">
                                        </div>
                                        </p>
                                        <p>
                                        <div class="form-group">
                                            <label for="">Language</label>
                                            <input type="text" class="form-control" name="lang" value="<?php echo $lang ?>">
                                        </div>
                                        </p>
                                        <p>
                                        <div class="form-group">
                                            <label for="">Copyright</label>
                                            <input type="text" class="form-control" name="copy" value="<?php echo $copy ?>">
                                        </div>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <div class="card">
                                <div class="card-header" role="tab" id="section2HeaderId">
                                    <h5 class="mb-0">
                                        <a data-toggle="collapse" data-parent="#accordianId" href="#section2ContentId" aria-expanded="true" aria-controls="section2ContentId">
                                            Read About Book
                                        </a>
                                    </h5>
                                </div>
                                <div id="section2ContentId" class="collapse in" role="tabpanel" aria-labelledby="section2HeaderId">
                                    <div class="card-body">
                                        <p>
                                        <div class="form-group">
                                            <label for="">About Book</label>
                                            <textarea class="form-control" name="about" rows="3"><?php echo $about ?></textarea>
                                        </div>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group d-flex justify-content-center ">
                            <input type="submit" class="btn btn-success m-1" name="update" value="Update">
                            <input type="submit" class="btn btn-danger m-1" name="del" value="Delete">

                        </div>
                        <input type="hidden" name="idn" value="<?php echo $idn ?>">
                        <input type="hidden" name="img" value="<?php echo $image ?>">

                    </form>
                    <!-- PUCHASE BUTTON STARTS -->
                    <div class="pt-3 p-2 purchase">
                        <h4 class="text-danger text-center"> PUCHARSE NOW</h4>
                        <div class="list-group text-center ">
                            <?php
                            $lidn = $_GET['idn'];
                            $sql = mysqli_query($db, "SELECT * FROM link WHERE idn ='$lidn'");
                            while ($row = mysqli_fetch_assoc($sql)) {
                                $lname = $row['name'];
                                $link = $row['link'];
                                $lid = $row['id'];

                            ?>
                                <form action="" method="POST" id="ajax_form" enctype="multipart/form-data">
                                    <P><a href="<?php echo $link ?>" class="list-group-item list-group-item-action badge badge-danger"><?php echo $lname ?> </a> <input type="submit" class="btn btn-danger btn-sm mt-1 center" name="ldel" value="Delete"> </p>

                                    <input type="hidden" name="id" value="<?php echo $lid ?>">
                                </form>

                            <?php } ?>

                        </div>
                    </div>
                </div>
            </div>
            <!-- PUCHARSE BUTTON ENSS -->

        </div>
    </div>

    </div>

    </div>
</section>



<!-- BOOKS STARTS HERE -->

<section class="ftco-section testimony-section ftco-no-pb mt-4">
    <div class="img img-bg border"></div>
    <div class="overlay"></div>
    <div class="container">
        <div class="row justify-content-center mb-5">
            <div class="col-md-7 text-center heading-section heading-section-white ftco-animate">
                <span class="subheading" id="testi">Books</span>
                <h2 class="mb-3">Edit Other Book</h2>
            </div>
        </div>
        <div class="row ftco-animate">
            <div class="col-md-12">
                <div class="carousel-testimony owl-carousel ftco-owl">
                    <?php
                    $sql = mysqli_query($db, "SELECT * FROM books WHERE idn !='$idn'");
                    while ($row = mysqli_fetch_assoc($sql)) {
                        $image = $row['image'];
                        $idn = $row['idn'];

                    ?>

                        <div class="item">
                            <div class="testimony-wrap py-4">
                                <div class="icon d-flex align-items-center justify-content-center"><span class="fa fa-quote-left"></div>
                                <div class="img">
                                    <a class="btn btn-danger btn-sm" href="editbooks.php?idn=<?php echo $idn ?>">
                                        <img src="bookimage/<?php echo $image ?>" alt="">
                                    </a>
                                    <div class="d-flex align-items-center">
                                        <div class="pl-3">
                                            <p class="name"></p>


                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    <?php } ?>

                </div>
            </div>
        </div>
    </div>
</section>

<!-- BOOKS ENDS HERE -->







<!-- footer starts here -->
<?php include('includes/footer.php') ?>
<!-- footer ends here -->