<?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_company"])){
                    $company_id = $_GET["edit_company"];
                    $pc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'placementCompany' AND data_sl_no = '$company_id' ");
                    if($pc_row = mysqli_fetch_assoc($pc_sql)){
                    ?>
                <div class="card mt-3">
                    <div class="card-header">
                        <h5 class="m-0">Edit Placement Company Details</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="companyName">Edit Company Name:</label>
                                    <input type="text" class="form-control" name="companyName"
                                        value="<?php echo $pc_row["data_title"];?>">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="logo">Edit Company Logo: <a target="_blank"
                                            href="../upload/company/<?php echo $pc_row["data_img"];?>"><img
                                                src="../upload/company/<?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="editCompany"><i
                                    class="fa fa-pencil"></i> Edit Company
                            </button>
                        </form>
                    </div>
                </div>
                <?php } } else{
                    ?>
                <div class="card mt-3">
                    <div class="card-header">
                        <h5 class="m-0">Placement For <?php echo $college_name;?></h5>
                    </div>
                    <div class="card-body">
                        <?php
                        $Placement_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'Placement' AND data_up_for = '$college_id' ");
                        if(mysqli_num_rows($Placement_sql)>0){
                            $Placement_row = mysqli_fetch_assoc($Placement_sql);
                            ?>
                        <form action="" method="POST">
                            <label for="Placement">Edit College Placement:</label>
                            <textarea class="form-control ckeditor" name="Placement" id="content"
                                rows="3"><?php echo $Placement_row["data_long_des"];?></textarea>
                            <button type="submit" class="btn btn-success btn-user m-2" name="edit"><i
                                    class="fa fa-edit"></i> UPDATE DETAILS
                            </button>
                        </form>
                        <?php
                        } else{
                            ?>
                        <form action="" method="POST">
                            <label for="Placement">Enter College Placement:</label>
                            <textarea class="form-control ckeditor" name="Placement" id="content"
                                placeholder="Enter Placement Details.." rows="3"></textarea>
                            <button type="submit" class="btn btn-success btn-user m-2" name="submit"><i
                                    class="fa fa-edit"></i> Submit DETAILS
                            </button>
                        </form>
                        <?php
                        }
                        ?>
                    </div>
                    <div class="card-header mt-3 d-flex justify-content-between">
                        <h5 class="m-0">Company List</h5>
                        <button id="toggleButton" class="btn btn-primary btn-sm" onclick="toggleDiv()">Add Company
                        </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="companyName">Enter Company Name:</label>
                                        <input type="text" class="form-control" name="companyName">
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label for="logo">Enter Company Logo:</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="addCompany"><i
                                        class="fa fa-plus"></i> Add Company
                                </button>
                            </form>
                        </div>
                        <div class="mt-2">
                            <?php
                            $dpc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'placementCompany' 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>Company Name</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/company/<?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="placement.php?college=<?php echo $_GET['college']; ?>&edit_company=<?php echo $dpc_row['data_sl_no']; ?>">
                                                    Edit
                                                </a>
                                                <a href='placement.php?college=<?php echo $_GET['college']; ?>&del_company=<?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 Placement Details 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 Company';
        }
    }
    </script>


</body>

</html>

<?php 
if(isset($_POST["submit"])){
    $Placement = $_POST["Placement"];

    $ins_sql = mysqli_query($con, "INSERT INTO data (data_catagory, data_long_des, data_up_for, data_up_date, data_recycle) VALUES ('Placement', '$Placement', '$college_id', '$currentTime', '1')");
    if($ins_sql){
        echo "<script>window.location = 'placement.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('OOPS !!!!'); setTimeout(() => { window.location = 'placement.php?college=" . $_GET["college"] . "'; }, 1200);</script>";
    }
}
?>
<?php
if(isset($_POST["edit"])){
    $Placement = $_POST["Placement"];

    $up_sql = mysqli_query($con, "UPDATE data SET data_long_des = '$Placement' WHERE data_catagory = 'Placement' AND data_up_for = '$college_id' ");
    if($up_sql){
        echo "<script>window.location = 'placement.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('OOPS !!!!'); setTimeout(() => { window.location = 'placement.php?college=" . $_GET["college"] . "'; }, 1200);</script>";
    }
}
?>

<?php
if (isset($_POST["addCompany"])) {

    $companyName = mysqli_real_escape_string($con, $_POST["companyName"]);
    $uploadDir = "../upload/company/";

    // 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("company_", 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 ('placementCompany', '$companyName', '$college_id', '$currentTime', '1', '$newFileName')");

                if ($ins_sql) {
                    echo "<script>window.location = 'placement.php?college=" . $_GET["college"] . "';</script>";
                } else {
                    echo "<script>alert('Database Error!'); window.location = 'placement.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["editCompany"])) {

    $companyName = mysqli_real_escape_string($con, $_POST["companyName"]);
    $companyId = mysqli_real_escape_string($con, $_GET["edit_company"]); 
    $uploadDir = "../upload/company/";

    // 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("company_", 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 company details with new logo
                $updateSQL = "UPDATE data SET data_title = '$companyName', data_img = '$newFileName' WHERE data_sl_no = '$companyId'";
            } 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 = '$companyName' WHERE data_sl_no = '$companyId'";
    }

    // Execute SQL update
    if (mysqli_query($con, $updateSQL)) {
        echo "<script>window.location = 'placement.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('Database Error!');</script>";
    }
}
?>
<?php
if (isset($_GET["del_company"])) {
    $companyId = mysqli_real_escape_string($con, $_GET["del_company"]);
    $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 = '$companyId'");
    $row = mysqli_fetch_assoc($query);

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

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

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

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