<?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; ?> Documents</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 document-upload">
                                        <div class="document-preview"></div>
                                        <div class="upload__btn-box">
                                            <p class="m-0"><span style="color:red;">Note*:</span>Maximum number of
                                                selected Documents is 10.</p>
                                            <label class="upload__btn">
                                                <p class="m-0">Select Documents</p>
                                                <input type="file" multiple="" name="document_upload[]"
                                                    data-max_length="10" class="upload__inputfile document-upload-input"
                                                    accept=".pdf,.doc,.docx,.txt">
                                            </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="doc_submit"
                                    class="btn btn-success text-sm-center mt-4">Upload Documents</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"; ?>
    <script>

    </script>
</body>

</html>

<?php
if(isset($_POST['doc_submit']) && !empty($_FILES['document_upload']['name'][0])) {
    $note_id = $_POST["note_id"];
    $note_title = $_POST["note_title"];
    $upload_dir = '../upload/notes/';
    $allowed_types = array('pdf', 'doc', 'docx', 'txt');
    $max_files = 10;

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

    // Loop through each file
    foreach($_FILES['document_upload']['name'] as $i => $file_name) {
        // Check if file is uploaded
        if($_FILES['document_upload']['error'][$i] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['document_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)) {
                    // Update database
                    $insert_query = "INSERT INTO notes_img (ni_name, ni_type, ni_ref) VALUES ('$new_file_name', 'document', '$note_id')";
                    mysqli_query($con, $insert_query); // Execute the insert query

                    // Increment successful upload count
                    $success_count++;
                } else {
                    echo "Error uploading file: " . $_FILES['document_upload']['error'][$i];
                }
            } else {
                echo "Invalid file type: " . $file_name;
            }
        } else {
            echo "File upload error: " . $_FILES['document_upload']['error'][$i];
        }
    }

    $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 . ' Documents Upload successful!");</script>';
        echo '<script>window.location = "view-notes.php?cid=' . $n_class . '";</script>';
        exit; // Stop further execution
    } else {
        echo '<script>alert("No documents uploaded or all documents failed to upload.");</script>';
    }
}
?>