<?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_wallpaper"])){

                    $wallpaper_id = $_GET["edit_wallpaper"];

                    $pc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'wallpaper' AND data_sl_no = '$wallpaper_id' ");

                    if($pc_row = mysqli_fetch_assoc($pc_sql)){

                    ?>

                <div class="card mt-3">

                    <div class="card-header">

                        <h5 class="m-0">Edit Wallpaper</h5>

                    </div>

                    <div class="card-body">

                        <form action="" method="POST" enctype="multipart/form-data">

                            <div class="row">

                                <div class="col-md-6 mb-2">

                                    <label for="wallpaperName">Edit Wallpaper Title:</label>

                                    <input type="text" class="form-control" name="wallpaperName"

                                        value="<?php echo $pc_row["data_title"];?>">

                                </div>

                                <div class="col-md-6 mb-2">

                                    <label for="logo">Edit Wallpaper : <a target="_blank"

                                            href="../upload/wallpaper/<?php echo $pc_row["data_img"];?>"><img

                                                src="../upload/wallpaper/<?php echo $pc_row["data_img"];?>"

                                                class="img-fluid" style="height:20px;" alt=""></a></label>

                                    <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png">

                                    <input type="hidden" name="oldLogo" value="<?php echo $pc_row["data_img"];?>">

                                </div>

                            </div>

                            <button type="submit" class="btn btn-success btn-user m-2" name="editwallpaper"><i

                                    class="fa fa-pencil"></i> Edit Wallpaper

                            </button>

                        </form>

                    </div>

                </div>

                <?php } } else{

                    ?>

                <div class="card">

                    <div class="card-header d-flex justify-content-between">

                        <h5 class="m-0">Wallpaper List</h5>

                        <button id="toggleButton" class="btn btn-primary btn-sm" onclick="toggleDiv()">Add Wallpaper

                        </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-6 mb-2">

                                        <label for="wallpaperName">Enter Wallpaper Title:</label>

                                        <input type="text" class="form-control" name="wallpaperName">

                                    </div>

                                    <div class="col-md-6 mb-2">

                                        <label for="logo">Enter Wallpaper :</label>

                                        <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png"

                                            required>

                                    </div>

                                </div>

                                <button type="submit" class="btn btn-success btn-user m-2" name="addwallpaper"><i

                                        class="fa fa-plus"></i> Add Wallpaper

                                </button>

                            </form>

                        </div>

                        <div class="mt-2">

                            <?php

                            $dpc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'wallpaper' 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>Wallpaper 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']; ?> &nbsp;

                                                <img src="../upload/wallpaper/<?php echo $dpc_row["data_img"];?>"

                                                    class="img-fluid" style="height:50px;"

                                                    alt="<?php echo $dpc_row['data_title']; ?>">

                                            </td>

                                            <td class='text-center align-middle'>

                                                <a class="btn btn-primary btn-sm" style="margin-left:5px;"

                                                    href="wallpaper.php?college=<?php echo $_GET['college']; ?>&edit_wallpaper=<?php echo $dpc_row['data_sl_no']; ?>">

                                                    Edit

                                                </a>

                                                <a href='wallpaper.php?college=<?php echo $_GET['college']; ?>&del_wallpaper=<?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 Wallpaper 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>

    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 wallpaper';

        }

    }

    </script>





</body>



</html>





<?php

if (isset($_POST["addwallpaper"])) {



    $wallpaperName = mysqli_real_escape_string($con, $_POST["wallpaperName"]);

    $uploadDir = "../upload/wallpaper/";



    // 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("wallpaper_", 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_title, data_up_for, data_up_date, data_recycle, data_img) 

                                               VALUES ('wallpaper', '$wallpaperName', '$college_id', '$currentTime', '1', '$newFileName')");



                if ($ins_sql) {

                    echo "<script>window.location = 'wallpaper.php?college=" . $_GET["college"] . "';</script>";

                } else {

                    echo "<script>alert('Database Error!'); window.location = 'wallpaper.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 {

        echo "<script>alert('Please upload a valid image file.');</script>";

    }

}

?>



<?php

if (isset($_POST["editwallpaper"])) {



    $wallpaperName = mysqli_real_escape_string($con, $_POST["wallpaperName"]);

    $wallpaperId = mysqli_real_escape_string($con, $_GET["edit_wallpaper"]); 

    $uploadDir = "../upload/wallpaper/";



    // Get the old logo

    $oldLogo = $_POST["oldLogo"];

    $newLogo = $_FILES["logo"]["name"];



    // If a new logo is uploaded

    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("wallpaper_", 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 wallpaper details with new logo

                $updateSQL = "UPDATE data SET data_title = '$wallpaperName', data_img = '$newFileName' WHERE data_sl_no = '$wallpaperId'";

            } 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 logo

        $updateSQL = "UPDATE data SET data_title = '$wallpaperName' WHERE data_sl_no = '$wallpaperId'";

    }



    // Execute SQL update

    if (mysqli_query($con, $updateSQL)) {

        echo "<script>window.location = 'wallpaper.php?college=" . $_GET["college"] . "';</script>";

    } else {

        echo "<script>alert('Database Error!');</script>";

    }

}

?>

<?php

if (isset($_GET["del_wallpaper"])) {

    $wallpaperId = mysqli_real_escape_string($con, $_GET["del_wallpaper"]);

    $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 = '$wallpaperId'");

    $row = mysqli_fetch_assoc($query);



    if ($row) {

        $logoFile = $row["data_img"];

        $uploadDir = "../upload/wallpaper/";



        // Delete logo file if it exists

        if (!empty($logoFile) && file_exists($uploadDir . $logoFile)) {

            unlink($uploadDir . $logoFile);

        }



        // Delete the wallpaper record from the database

        $deleteSQL = mysqli_query($con, "DELETE FROM data WHERE data_sl_no = '$wallpaperId'");



        if ($deleteSQL) {

            echo "<script>window.location = 'wallpaper.php?college=$collegeId';</script>";

        } else {

            echo "<script>alert('Database Deletion Failed!');</script>";

        }

    } else {

        echo "<script>alert('wallpaper Not Found!');</script>";

    }

} 

?>