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

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <?php if(isset($_GET["college"])){
                $college_id = $_GET["college"];
                $college_sql = mysqli_query($con, "SELECT * FROM users where utype = 'College' AND uid = '$college_id'");
                if($college_row = mysqli_fetch_assoc($college_sql)){
                    $college_name = $college_row["uname"];
                }
                ?>
            <div class="container-fluid">
                <?php
                if(isset($_GET["edit_gallery"])){
                    $gallery_id = $_GET["edit_gallery"];
                    $pc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'gallery' AND data_sl_no = '$gallery_id' ");
                    if($pc_row = mysqli_fetch_assoc($pc_sql)){
                    ?>
                <div class="card mt-3">
                    <div class="card-header">
                        <h5 class="m-0">Edit gallery</h5>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <label for="galleryType">Select Gallery Type</label>
                                    <select name="galleryType" class="form-control" id="galleryType"
                                        onchange="toggleGalleryFields()">
                                        <option value="<?php echo $pc_row["data_subCategory"];?>">
                                            <?php echo $pc_row["data_subCategory"];?></option>
                                        <option value="Image">Image</option>
                                        <option value="Video">Video</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="galleryName">Edit Gallery Title:</label>
                                    <input type="text" class="form-control" name="galleryName"
                                        value="<?php echo $pc_row["data_title"];?>">
                                </div>
                                <div class="col-md-4 mb-2" id="galleryImage" style="display: none;">
                                    <label for="logo">Enter Gallery Image:</label>
                                    <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png">
                                </div>
                                <div class="col-md-4 mb-2" id="galleryVideo" style="display: none;">
                                    <label for="video">Enter Gallery Video Link:</label>
                                    <input type="text" class="form-control" name="video">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <?php if($pc_row["data_subCategory"] == "Image"){
                                        ?>
                                    <img src="../upload/gallery/<?php echo $pc_row["data_img"];?>" class="img-fluid"
                                        alt="<?php echo $pc_row["data_title"];?>">
                                    <?php } if($pc_row["data_subCategory"] == "Video"){
                                        $videoUrl = $pc_row["data_img"];
                                        if (strpos($videoUrl, "youtu.be") !== false) {
                                            $videoID = explode("/", parse_url($videoUrl, PHP_URL_PATH))[1];
                                        } elseif (strpos($videoUrl, "youtube.com/watch") !== false) {
                                            parse_str(parse_url($videoUrl, PHP_URL_QUERY), $queryParams);
                                            $videoID = $queryParams["v"] ?? "";
                                        } else {
                                            $videoID = ""; // Invalid URL fallback
                                        }

                                        if (!empty($videoID)) { ?>
                                    <iframe height="200" src="https://www.youtube.com/embed/<?php echo $videoID; ?>"
                                        frameborder="0" allowfullscreen>
                                    </iframe>
                                    <?php } }?>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success btn-user m-2" name="editgallery"><i
                                    class="fa fa-pencil"></i> Edit gallery
                            </button>
                        </form>
                    </div>
                </div>
                <?php } } else{
                    ?>
                <div class="card">
                    <div class="card-header d-flex justify-content-between">
                        <h5 class="m-0">Gallery Image/Video List</h5>
                        <button id="toggleButton" class="btn btn-primary btn-sm" onclick="toggleDiv()">Add Gallery
                            Image/Video
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="toggleDiv"
                            style="display: none; padding: 10px; border: 1px solid #ddd; margin-top: 10px;">
                            <form action="" method="POST" enctype="multipart/form-data">
                                <div class="row">
                                    <div class="col-md-4 mb-2">
                                        <label for="galleryType">Select Gallery Type</label>
                                        <select name="galleryType" class="form-control" id="galleryType"
                                            onchange="toggleGalleryFields()">
                                            <option value="">Select From List</option>
                                            <option value="Image">Image</option>
                                            <option value="Video">Video</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-2">
                                        <label for="galleryName">Enter Gallery Title:</label>
                                        <input type="text" class="form-control" name="galleryName">
                                    </div>
                                    <div class="col-md-4 mb-2" id="galleryImage" style="display: none;">
                                        <label for="logo">Enter Gallery Image:</label>
                                        <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png">
                                    </div>
                                    <div class="col-md-4 mb-2" id="galleryVideo" style="display: none;">
                                        <label for="video">Enter Gallery Video Link:</label>
                                        <input type="text" class="form-control" name="video">
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-success btn-user m-2" name="addgallery">
                                    <i class="fa fa-plus"></i> Add Gallery
                                </button>
                            </form>
                        </div>
                        <div class="mt-2">
                            <?php
                            $dpc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'gallery' AND data_up_for = '$college_id' ");
                            if(mysqli_num_rows($dpc_sql)>0){
                            ?>
                            <div class="table-responsive">
                                <table class="table table-hover table-bordered table-sm" id="thisismytable">
                                    <thead>
                                        <tr>
                                            <th>No.</th>
                                            <th>Gallery Title</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $c = 1;
                                        while($dpc_row = mysqli_fetch_assoc($dpc_sql)){
                                            ?>
                                        <tr id='<?php echo $dpc_row["data_sl_no"]; ?>'>
                                            <td>
                                                <span class='text_dark'><?php echo $c; ?></span>
                                            </td>
                                            <td>
                                                <?php echo $dpc_row['data_title']; ?>
                                                (<?php echo $dpc_row["data_subCategory"];?>)&nbsp;
                                                <?php if ($dpc_row["data_subCategory"] == "Image") { ?>
                                                <img src="../upload/gallery/<?php echo $dpc_row["data_img"]; ?>"
                                                    class="img-fluid" style="height:50px;"
                                                    alt="<?php echo $dpc_row['data_title']; ?>">
                                                <?php } elseif ($dpc_row["data_subCategory"] == "Video") { 
                                                    // Convert YouTube short URL to an embeddable format
                                                    $videoUrl = $dpc_row["data_img"];
                                                    if (strpos($videoUrl, "youtu.be") !== false) {
                                                        $videoID = explode("/", parse_url($videoUrl, PHP_URL_PATH))[1];
                                                    } elseif (strpos($videoUrl, "youtube.com/watch") !== false) {
                                                        parse_str(parse_url($videoUrl, PHP_URL_QUERY), $queryParams);
                                                        $videoID = $queryParams["v"] ?? "";
                                                    } else {
                                                        $videoID = ""; // Invalid URL fallback
                                                    }

                                                    if (!empty($videoID)) { ?>
                                                <iframe width="200" height="100"
                                                    src="https://www.youtube.com/embed/<?php echo $videoID; ?>"
                                                    frameborder="0" allowfullscreen>
                                                </iframe>
                                                <?php } } ?>
                                            </td>
                                            <td class='text-center align-middle'>
                                                <a class="btn btn-primary btn-sm" style="margin-left:5px;"
                                                    href="gallery.php?college=<?php echo $_GET['college']; ?>&edit_gallery=<?php echo $dpc_row['data_sl_no']; ?>">
                                                    Edit
                                                </a>
                                                <a href='gallery.php?college=<?php echo $_GET['college']; ?>&del_gallery=<?php echo $dpc_row["data_sl_no"]; ?>'
                                                    class='delete m-2 btn btn-danger btn-sm rounded-circle'
                                                    title='Click to Delete'>
                                                    <i class="fa fa-trash" aria-hidden="true"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php $c++; } ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php 
                        } else{echo "No Gallery Image/Video yet.";}
                        ?>
                        </div>
                    </div>
                </div>
                <?php } ?>
            </div>
            <?php } else {echo "Enter a valid college.";}?>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>
    <script>
    function toggleGalleryFields() {
        var galleryType = document.getElementById("galleryType").value;
        document.getElementById("galleryImage").style.display = (galleryType === "Image") ? "block" : "none";
        document.getElementById("galleryVideo").style.display = (galleryType === "Video") ? "block" : "none";
    }
    </script>
    <script>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });

    function toggleDiv() {
        const div = document.getElementById('toggleDiv');
        const button = document.getElementById('toggleButton');

        if (div.style.display === 'none' || div.style.display === '') {
            div.style.display = 'block';
            button.textContent = 'Hide';
        } else {
            div.style.display = 'none';
            button.textContent = 'Add gallery';
        }
    }
    </script>


</body>

</html>


<?php
if (isset($_POST["addgallery"])) {
    $galleryType = mysqli_real_escape_string($con, $_POST["galleryType"]);
    $galleryName = mysqli_real_escape_string($con, $_POST["galleryName"]);
    $video = mysqli_real_escape_string($con, $_POST["video"]);
    $uploadDir = "../upload/gallery/";

    // Ensure the upload directory exists
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // File upload handling
    if (isset($_FILES["logo"]) && $_FILES["logo"]["error"] == 0) {
        $fileName = $_FILES["logo"]["name"];
        $fileTmpName = $_FILES["logo"]["tmp_name"];
        $fileSize = $_FILES["logo"]["size"];
        $fileType = $_FILES["logo"]["type"];
        
        // Allowed file types
        $allowedExtensions = ["jpg", "jpeg", "png"];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (in_array($fileExt, $allowedExtensions)) {
            // Rename file to prevent overwriting
            $newFileName = uniqid("gallery_", true) . "." . $fileExt;
            $targetFilePath = $uploadDir . $newFileName;

            // Move file to upload directory
            if (move_uploaded_file($fileTmpName, $targetFilePath)) {
                // Insert into database
                $ins_sql = mysqli_query($con, "INSERT INTO data (data_catagory, data_subCategory, data_title, data_up_for, data_up_date, data_recycle, data_img) 
                                               VALUES ('gallery', '$galleryType', '$galleryName', '$college_id', '$currentTime', '1', '$newFileName')");

                if ($ins_sql) {
                    echo "<script>window.location = 'gallery.php?college=" . $_GET["college"] . "';</script>";
                } else {
                    echo "<script>alert('Database Error!'); window.location = 'gallery.php?college=" . $_GET["college"] . "';</script>";
                }
            } else {
                echo "<script>alert('File upload failed!');</script>";
            }
        } else {
            echo "<script>alert('Invalid file type! Only JPG, JPEG, and PNG allowed.');</script>";
        }
    } else {
        // Insert into database
        $ins_sql = mysqli_query($con, "INSERT INTO data (data_catagory, data_subCategory, data_title, data_up_for, data_up_date, data_recycle, data_img) 
        VALUES ('gallery', '$galleryType', '$galleryName', '$college_id', '$currentTime', '1', '$video')");

        if ($ins_sql) {
        echo "<script>window.location = 'gallery.php?college=" . $_GET["college"] . "';</script>";
        } else {
        echo "<script>alert('Database Error!'); window.location = 'gallery.php?college=" . $_GET["college"] . "';</script>";
        }
    }
}
?>

<?php
if (isset($_POST["editgallery"])) {
    $galleryType = mysqli_real_escape_string($con, $_POST["galleryType"]);
    $galleryName = mysqli_real_escape_string($con, $_POST["galleryName"]);
    $galleryId = mysqli_real_escape_string($con, $_GET["edit_gallery"]); 
    $video = mysqli_real_escape_string($con, $_POST["video"]);
    $uploadDir = "../upload/gallery/";

    // Get the old logo
    $oldLogo = $_POST["oldLogo"];
    $newLogo = $_FILES["logo"]["name"];

    // If gallery type is "Image"
    if ($galleryType == "Image") {
        if (!empty($newLogo)) {
            $fileTmpName = $_FILES["logo"]["tmp_name"];
            $fileExt = strtolower(pathinfo($newLogo, PATHINFO_EXTENSION));
            $allowedExtensions = ["jpg", "jpeg", "png"];

            if (in_array($fileExt, $allowedExtensions)) {
                // Rename new file to prevent overwriting
                $newFileName = uniqid("gallery_", true) . "." . $fileExt;
                $targetFilePath = $uploadDir . $newFileName;

                // Move new logo to the upload directory
                if (move_uploaded_file($fileTmpName, $targetFilePath)) {
                    // Delete old logo if it exists
                    if (!empty($oldLogo) && file_exists($uploadDir . $oldLogo)) {
                        unlink($uploadDir . $oldLogo);
                    }

                    // Update gallery details with new logo
                    $updateSQL = "UPDATE data SET data_subCategory = '$galleryType', data_title = '$galleryName', data_img = '$newFileName' WHERE data_sl_no = '$galleryId'";
                } else {
                    echo "<script>alert('File upload failed!');</script>";
                    exit;
                }
            } else {
                echo "<script>alert('Invalid file type! Only JPG, JPEG, and PNG allowed.');</script>";
                exit;
            }
        } else {
            // If no new logo, keep the old one
            $updateSQL = "UPDATE data SET data_title = '$galleryName' WHERE data_sl_no = '$galleryId'";
        }
    } 
    // If gallery type is "Video"
    elseif ($galleryType == "Video") {
        if (!empty($video)) {
            // Delete old logo if it exists (since we are switching to video)
            if (!empty($oldLogo) && file_exists($uploadDir . $oldLogo)) {
                unlink($uploadDir . $oldLogo);
            }

            // Update with video link
            $updateSQL = "UPDATE data SET data_subCategory = '$galleryType', data_title = '$galleryName', data_img = '$video' WHERE data_sl_no = '$galleryId'";
        } else {
            echo "<script>alert('Please enter a video link!');</script>";
            exit;
        }
    }

    // Execute SQL update
    if (mysqli_query($con, $updateSQL)) {
        echo "<script>window.location = 'gallery.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('Database Error!');</script>";
    }
}

?>
<?php
if (isset($_GET["del_gallery"])) {
    $galleryId = mysqli_real_escape_string($con, $_GET["del_gallery"]);
    $collegeId = mysqli_real_escape_string($con, $_GET["college"]);

    // Fetch the logo filename from the database
    $query = mysqli_query($con, "SELECT data_img FROM data WHERE data_sl_no = '$galleryId'");
    $row = mysqli_fetch_assoc($query);

    if ($row) {
        $logoFile = $row["data_img"];
        $uploadDir = "../upload/gallery/";

        // Delete logo file if it exists
        if (!empty($logoFile) && file_exists($uploadDir . $logoFile)) {
            unlink($uploadDir . $logoFile);
        }

        // Delete the gallery record from the database
        $deleteSQL = mysqli_query($con, "DELETE FROM data WHERE data_sl_no = '$galleryId'");

        if ($deleteSQL) {
            echo "<script>window.location = 'gallery.php?college=$collegeId';</script>";
        } else {
            echo "<script>alert('Database Deletion Failed!');</script>";
        }
    } else {
        echo "<script>alert('gallery Not Found!');</script>";
    }
} 
?>