<?php

session_start();

if (!isset($_SESSION['user'])) {
    // Redirect to login page if not logged in
    header('Location: ../login');
    exit();
}

$user = $_SESSION['user'];
$email = $user['email_address'];


/*// Define username and password
$username = 'admin';
$password = 'admin';

// Check if user has provided credentials
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
    $_SERVER['PHP_AUTH_USER'] != $username || $_SERVER['PHP_AUTH_PW'] != $password) {
    // If not, ask for credentials
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Unauthorized access';
    exit;
}*/

// Include database connection file
include('../Secure/Cred.php');

$delete_message = ""; // Initialize delete message variable

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Add a new company
    if(isset($_POST["company"]) && isset($_POST["companycode"]) && isset($_POST["groupplan"])) {
        $cmpxname = trim(strtoupper($_POST["company"]));
        $cmpxcode = trim(strtoupper($_POST["companycode"]));
        $grpplan = trim($_POST["groupplan"]);
        $cmpxlink =  time().rand().substr($cmpxname,1,1);

        // Insert new company data into the database
        $m_errs = conn("INSERT INTO `web_app_enrollment_form` (`id`, `company`, `link`, `company_code`, `groupplan`, `status`) VALUES (NULL, '".$cmpxname."', '".$cmpxlink."', '".$cmpxcode."', '".$grpplan."', 'active')");
    }
    
    // Handle company deletion
    if(isset($_POST["delete_company"])) {
        $delete_company = trim(strtoupper($_POST["delete_company"]));
        
        // Execute SQL query to delete the company from the database
        $delete_query = conn("DELETE FROM `web_app_enrollment_form` WHERE `company` = '".$delete_company."'");
        if ($delete_query) {
            // Company deleted successfully
            $delete_message = "Company '$delete_company' has been deleted.";
        } else {
            // Error occurred while deleting company
            $delete_message = "Failed to delete company '$delete_company'. Please try again later.";
        }
    }
    
    // Handle company status update
    if(isset($_POST["update_status"])) {
        $update_company = trim(strtoupper($_POST["update_status"]));
        
        // Get current status of the company
        $current_status_query = conn("SELECT `status` FROM `web_app_enrollment_form` WHERE `company` = '".$update_company."'");
        $current_status = mysqli_fetch_array($current_status_query, MYSQLI_ASSOC)['status'];
        
        // Toggle status
        $new_status = ($current_status == 'active') ? 'inactive' : 'active';
        
        // Update status in the database
        $update_query = conn("UPDATE `web_app_enrollment_form` SET `status` = '".$new_status."' WHERE `company` = '".$update_company."'");
        if ($update_query) {
            // Status updated successfully
            $status_message = "Company status updated successfully.";
        } else {
            // Error occurred while updating status
            $status_message = "Failed to update company status. Please try again later.";
        }
    }
}

// Generate list of companies
$cmplist='';

$m_queues = conn("SELECT * FROM `web_app_enrollment_form`");
while(list($idx,$companyx,$linkx,$company_codex,$groupplan, $statusx) = mysqli_fetch_array($m_queues,MYSQLI_NUM))
{
    // Add delete button next to company name only if company name is not empty
    if (!empty($companyx)) {
        // Add export button to export enrollee data for this company
        $button_text = ($statusx == 'active') ? 'Active' : 'Inactive';
        $button_color = ($statusx == 'active') ? 'blue' : 'gray';
        
        $cmplist.='<li> 
        
        <div class="info"> <h3><a class="third after" href="'.'http://'.$_SERVER['HTTP_HOST'].'/enrollment/index.php?cllocation='.$linkx.'">'.$companyx. '-'.$groupplan.' ('.$company_codex.')</a></h3> 
        
        
        <div class="button-container"> 
        <form action="export_enrollee.php" method="post" style="display: inline;"><input type="hidden" name="company_name" value="'.$companyx.'"><input type="submit" value="Export Enrollee Data" class="export-btn"></form>
        
        <form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post" style="display: inline;"><input type="hidden" name="delete_company" value="'.$companyx.'"><input type="submit" value="Delete" class="delete-btn"></form>
        
        <form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post" style="display: inline;"><input type="hidden" name="update_status" value="'.$companyx.'"><input type="submit" value="'.$button_text.'" class="status-btn" style="background-color:'.$button_color.';"></form>
        </div> 
        
        </div>
        </li>';
        
        // Add status button
        $cmplist.='';
    }
}
?>

<!DOCTYPE html>
<html style="background-image: url(../images/final_20864245705555.5b18e0a95657b9.83368454.png);">
<head>
    <meta charset="UTF-8">
    <title>ADMIN</title>
    <style>
        body {
            font-size: 100%;
            background: url("../images/final_20864245705555.5b18e0a95657b9.83368454.png") no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
            font-family: "Lucida Grande", sans-serif;
        }
        
        .wrapper {
            width: 70%;
            margin: 0 auto;
        }
        
        ul {
            maring: 0;
            padding: 0px;
            list-style: none;
        }
        
        ul li {
            padding: 20px;
            margin-top: 20px;
            background-color: rgba(255, 255, 255, 0.9);
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            -webkit-box-shadow: 0px 0px 2px #888888;
            -moz-box-shadow: 0px 0px 2px #888888;
            box-shadow: 0px 0px 2px #888888;
        }
        
        .export-btn,
        .delete-btn,
        .status-btn{
            background-color: transparent;
            border: none;
            color: white;
            padding: 5px 10px;
            cursor: pointer;
        }
        
        .export-btn {
            background-color: #4CAF50;
            /* Green */
        }
        
        .delete-btn {
            background-color: #d73444;
            /* Red */
        }
        
        .button-container {
            float: right;
        }
        
        .head {
            padding: 20px;
            font-size: 36px;
            text-align: center;
            background-color: rgba(255, 255, 255, 0.9);
            color: #00f;
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
            -webkit-box-shadow: 0px 0px 2px #888888;
            -moz-box-shadow: 0px 0px 2px #888888;
            box-shadow: 0px 0px 2px #888888;
        }
        
        li span {
            font-size: 16px;
            color: #a0a29d;
            margin-right: 40px;
            height: 32px;
            line-height: 32px;
        }
        
        .info {
            width: 95%;
            margin: 0;
            margin-left: 5%;
            margin-right: 5%;
            display: inline-block;
        }
        
        h3 {
            color: #767a7b;
            margin: 0;
            padding-bottom: 0px;
            font-size: 26px;
            font-weight: 100;
        }
        
        #contact input[type="text"],
        select {
            width: 72%;
            border: 1px solid #ccc;
            background: #FFF;
            margin: 0 0 5px;
            padding: 10px;
        }
        
        label {
            font-weight: bold;
            margin-bottom: 8px;
            display: block;
        }
        
        #contact input[type="text"],
        #contact input[type="email"],
        #contact input[type="tel"],
        #contact input[type="url"],
        #contact textarea {
            width: 70%;
            border: 1px solid #ccc;
            background: #FFF;
            margin: 0 0 5px;
            padding: 10px;
        }
        
        #contact input[type="text"]:hover,
        #contact input[type="email"]:hover,
        #contact input[type="tel"]:hover,
        #contact input[type="url"]:hover,
        #contact textarea:hover {
            -webkit-transition: border-color 0.3s ease-in-out;
            -moz-transition: border-color 0.3s ease-in-out;
            transition: border-color 0.3s ease-in-out;
            border: 1px solid #aaa;
        }
        
        fieldset {
            border: medium none !important;
            margin: 0 0 10px;
            min-width: 100%;
            padding: 0;
            width: 100%;
        }
        
        #contact text {
            height: 100px;
            max-width: 100%;
            resize: none;
        }
        
        #contact input[type="submit"] {
            cursor: pointer;
            width: 30%;
            border: none;
            background: #4CAF50;
            color: #FFF;
            margin: 0 0 5px;
            padding: 10px;
            font-size: 15px;
        }
        
        a,
        a:visited,
        a:hover,
        a:active {
            -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
            position: relative;
            transition: 0.5s color ease;
            text-decoration: none;
            font-size: 1.0em;
        }
        
        a:hover {
            color: #d73444;
        }
        
        a.before:before,
        a.after:after {
            content: "";
            transition: 0.5s all ease;
            -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
            position: absolute;
        }
        
        a.after:after {
            bottom: -0.25em;
        }
        
        a.before:before,
        a.after:after {
            height: 5px;
            height: 0.35rem;
            width: 0;
            background: #d73444;
        }
        
        a.third:after,
        a.sixth:before,
        a.sixth:after {
            left: 50%;
            -webkit-transform: translateX(-50%);
            transform: translateX(-50%);
        }
        
        a.before:hover:before,
        a.after:hover:after {
            width: 100%;
        }
    </style>
    
    <script>
        // Function to display delete message as a pop-up
        function showDeleteMessage(message) {
            alert(message);
        }
        
        // Call the function when the page loads to display the delete message
        window.onload = function() {
            <?php
            // Display delete message if it's not empty
            if (!empty($delete_message)) {
                echo "showDeleteMessage('".$delete_message."');";
            }
            ?>
        }
    </script>
</head>
<body>
    <div class="wrapper">
        <div style="text-align:center">
            <img alt="" class="form-image" style="border:0" src="../images/Red-logo.png" height="212px" width="508px" data-component="image">
        </div>
        <div class="container-fluid">
            <div class="mb-3">
                <a href="../data/export.php" class="btn btn-success mb-3">Export to all data to CSV</a>
            </div>
            <ul class="menu">
                <div class="head">
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="contact" method="post" name="contact">
                        <fieldset><input  id="company"  name="company" placeholder="Company Name..." type="text" tabindex="1" required autofocus/></fieldset>
                        <fieldset><input  id="companycode"  name="companycode" placeholder="Company Code" type="text" tabindex="1" required autofocus/></fieldset>
                        <fieldset><select  id="groupplan"  name="groupplan"  tabindex="1" required autofocus />
                            <option value="Individual">Individual</option>
                            <option value="Family">Family</option>
                        </select></fieldset>
                        <fieldset><input type="submit" value="Add Company" /></fieldset>
                    </form>
                </div> 
                <ul>
                    <?php echo $cmplist;?>
                </ul>
            </ul>
        </div>
    </div>
</body>
</html>
