<?php
session_start();
include "../db.php";
date_default_timezone_set('Asia/Kolkata');
$currentTime = date('M j, Y g:i a');

if (!isset($_SESSION['uid']) || !isset($_SESSION['uref']) || !isset($_SESSION['utype']) || !isset($_SESSION['uname'])) {
    header("Location: logout.php");
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "includes/meta.php"; ?>
    <?php include "includes/css.php"; ?>
</head>

<body id="page-top" class="mt-55">
    <?php 
    if (!isset($_GET['n_id']) || empty($_GET['n_id'])) {
        header("Location: notes-upload.php");
    }

    $n_id = $_GET['n_id'];
    $sql = mysqli_query($con, "SELECT * FROM notes WHERE n_id = '$n_id'");
    if ($row = mysqli_fetch_assoc($sql)) {
        $note_title = $row["n_title"];
        $n_class = $row["n_class"];
    }
    ?>
    <div style="margin-top: 130px;"></div>
    <?php include "includes/header2.php"; ?>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow mt-3">
                    <h5 class="card-header text-dark text-center font-weight-bold">Study Note -
                        <?php echo $note_title; ?> Images</h5>
                    <div class="card-body">
                        <form method="POST" action="" enctype="multipart/form-data">
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <div class="upload__box">
                                        <div class="upload__img-wrap"></div>
                                        <div class="upload__btn-box">
                                            <p class="m-0"><span style="color:red;">Note*:</span>Maximum number of
                                                selected Image is 20.</p>
                                            <label class="upload__btn">
                                                <p class="m-0">Select Images</p>
                                                <input type="file" multiple="" name="upload[]" data-max_length="20"
                                                    class="upload__inputfile">
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row justify-content-center">
                                <input type="hidden" value="<?php echo $n_id; ?>" name="note_id">
                                <input type="hidden" value="<?php echo $note_title; ?>" name="note_title">
                                <button type="submit" name="img_submit"
                                    class="btn btn-success text-sm-center mt-4">Upload Images</button>
                                &nbsp;&nbsp;&nbsp;
                                <a href="view-notes.php?cid=<?php echo $n_class;?>"
                                    class="btn btn-warning text-sm-center mt-4">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div style="margin-top: 120px;"></div>
    <?php include "includes/ft.php"; ?>
    <?php include "includes/js.php"; ?>
</body>

</html>

<?php
if(isset($_POST['img_submit']) && !empty($_FILES['upload']['name'][0])) {
    $note_id = $_POST["note_id"];
    $note_title = $_POST["note_title"];
    $upload_dir = '../upload/notes/';
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $max_files = 20;

    // Variable to track successful uploads
    $success_count = 0;

    // Loop through each file
    foreach($_FILES['upload']['name'] as $i => $file_name) {
        // Check if file is uploaded
        if($_FILES['upload']['error'][$i] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['upload']['tmp_name'][$i];
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            // Check file type
            if(in_array($file_ext, $allowed_types)) {
                // Generate new file name
                $new_file_name = $note_title . '_' . date('Y-m-d') . '_' . $i . '.' . $file_ext;
                $new_file_path = $upload_dir . $new_file_name;

                // Move file to upload folder
                if (move_uploaded_file($file_tmp, $new_file_path)) {
                    // Compress image
                    $compressed_image = imagecreatefromstring(file_get_contents($new_file_path));
                    imagejpeg($compressed_image, $new_file_path, 50); // Compressing to 50% quality, you can adjust as needed

                    // Update database
                    $insert_query = "INSERT INTO notes_img (ni_name, ni_type, ni_ref) VALUES ('$new_file_name', 'image', '$note_id')";
                    mysqli_query($con, $insert_query); // Execute the insert query

                    // Increment successful upload count
                    $success_count++;
                }
            }
        }
    }

    $n_id = $note_id;
    $sql = mysqli_query($con, "SELECT * FROM notes WHERE n_id = '$n_id'");
    if ($row = mysqli_fetch_assoc($sql)) {
        $n_class = $row["n_class"];
    }
    // If at least one file was successfully uploaded
    if($success_count > 0) {
        // Show success alert and redirect
        echo '<script>alert("' . $success_count . ' Images Upload successful!");</script>';
        echo '<script>window.location = "view-notes.php?cid=' . $n_class . '";</script>';
        exit; // Stop further execution
    }
}
?>