<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Page - Cart2 Data</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  
    <style>
        
    
    .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

        /* CSS for styling the table and navigation */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #ffcda7;

        }

        h1 {
            text-align: center;
            margin-top: 20px;
        }

        nav ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
            text-align: center;
        }

        nav ul li {
            display: inline;
            margin-right: 20px;
        }

        nav ul li a {
            text-decoration: none;
            color: #333;
            font-weight: bold;
        }

        nav ul li a:hover {
            color: #009688;
        }

        .content-section {
            display: none;
            padding: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #C67336;
        }

        img {
            max-width: 100px;
        }
    </style>
</head>
<body>

<h1>Admin Page</h1>



    <style>
body {margin:0;font-family:Arial}

.topnav {
  overflow: hidden;
  background-color: #b46426;
}

.topnav a {
  float: left;
  display: block;
  color: #ffcda7;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.active {
  background-color: #ffcda7;
  color: white;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 17px;    
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #ffd8bb;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #ffcda7;
  color: white;
}

.dropdown-content a:hover {
  background-color: #ddd;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child), .dropdown .dropbtn {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
  .topnav.responsive .dropdown {float: none;}
  .topnav.responsive .dropdown-content {position: relative;}
  .topnav.responsive .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: left;
  }
}
</style>


<div class="topnav" id="myTopnav">
<a href="#" onclick="showContent('cartData')">Food Collection</a>                    
<a href="#" onclick="showContent('totalSales')">Total Sales</a>                     
<a href="#" onclick="showContent('paymentMethods')"> Payment Method</a>                  
<a href="#" onclick="showContent('foodHandling')">Food Handling</a>                    
<a href="#" onclick="showContent('foodStatus')">Food Status</a>
<a href="#" onclick="showContent('drinkStatus')">Drink Status</a>  

<!--
  <div class="dropdown">
    <button class="dropbtn">Dropdown 
      <i class="fa fa-caret-down"></i>
    </button>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </div> 
!-->

  <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
</div>


<script>
function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
</script>

<!-- Content sections -->
<div id="home" class="content-section">
    <!-- Content for the Home section goes here -->
</div>




<div id="foodStatus" class="content-section">

<?php
    // Include the database configuration file
    include 'config.php';

    // Query to fetch id, name, and image from menu_items table
    $sql = "SELECT id, name, image, available FROM menu_items";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Start the table
        echo '<table class="menu-table">';
        // Output data of each row
        while ($row = $result->fetch_assoc()) {
            // Start a new row
            echo '<tr>';
            // Start a table cell for the menu item image
            echo '<td>';
            echo '<img src="' . $row["image"] . '" alt="' . $row["name"] . '">';
            echo '</td>';
            // Start a table cell for the menu item name
            echo '<td>';
            echo '<p>' . $row["name"] . '</p>';
            echo '</td>';
            // Start a table cell for the switch label with checkbox
            echo '<td>';
            echo '<label class="switch">';
            echo '<input type="checkbox" value="' . $row["id"] . '" id="availability_' . $row["id"] . '"';
            // Check if the item is available and set the checkbox accordingly
            if ($row["available"] == 1) {
                echo 'checked';
            }
            echo ' onchange="updateAvailability(this, \'food\')">'; // Pass 'food' as the type
            echo '<span class="slider round"></span>';
            echo '</label>';
            echo '</td>';
            // Close the row
            echo '</tr>';
        }
        // End the table
        echo '</table>';
    } else {
        echo "No items found in the menu.";
    }

    $conn->close();
?>
</div>


<div id="drinkStatus" class="content-section">

<?php
    // Include the database configuration file
    include 'config.php';

    // Query to fetch id, name, and image from drink_items table
    $sql = "SELECT id, name, image, available FROM drink_items";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Start the table
        echo '<table class="menu-table">';
        // Output data of each row
        while ($row = $result->fetch_assoc()) {
            // Start a new row
            echo '<tr>';
            // Start a table cell for the menu item image
            echo '<td>';
            echo '<img src="' . $row["image"] . '" alt="' . $row["name"] . '">';
            echo '</td>';
            // Start a table cell for the menu item name
            echo '<td>';
            echo '<p>' . $row["name"] . '</p>';
            echo '</td>';
            // Start a table cell for the switch label with checkbox
            echo '<td>';
            echo '<label class="switch">';
            echo '<input type="checkbox" value="' . $row["id"] . '" id="availability_' . $row["id"] . '"';
            // Check if the item is available and set the checkbox accordingly
            if ($row["available"] == 1) {
                echo 'checked';
            }
            echo ' onchange="updateAvailability(this, \'drink\')">'; // Pass 'drink' as the type
            echo '<span class="slider round"></span>';
            echo '</label>';
            echo '</td>';
            // Close the row
            echo '</tr>';
        }
        // End the table
        echo '</table>';
    } else {
        echo "No items found in the menu.";
    }

    $conn->close();
?>
</div>

<script>
    function updateAvailability(checkbox, type) {
        var itemId = checkbox.value;
        var available = checkbox.checked ? 1 : 0;
        var url = '';

        // Determine the URL based on the type of item (food or drink)
        if (type === 'food') {
            url = 'food_update.php';
        } else if (type === 'drink') {
            url = 'drink_update.php';
        } else {
            console.error('Invalid item type');
            return;
        }

        // Send an AJAX request to the appropriate update PHP file
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText); // Log the response
            }
        };
        xhr.send("itemId=" + itemId + "&available=" + available);
    }
</script>



<style>
/* Default styles */
.cart-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

.cart-table th,
.cart-table td {
    padding: 8px;
    border: 1px solid #ddd;
}

.cart-table th {
    background-color: #f2f2f2;
    text-align: left;
}

.cart-table img {
    max-width: 100px;
    height: auto;
}

.total-sales {
    margin-top: 20px;
}

/* Responsive styles */
@media only screen and (max-width: 600px) {
    .cart-table th, .cart-table td {
        padding: 4px;
    }
    
    .cart-table img {
        max-width: 80px;
    }

    
}

@media only screen and (max-width: 400px) {
    .cart-table th, .cart-table td {
        font-size: 12px;
    }
}

</style>

<!-- Cart Data Section -->
<div id="cartData" class="content-section ">

<?php
// Include the database configuration file
include 'config.php';

// Prepare and execute SQL query to fetch data from the user_info table
$stmt = $conn->prepare("SELECT name, phone FROM user_info");
$stmt->execute();
$result = $stmt->get_result();

// Check if there are any rows returned
if ($result->num_rows > 0) {
    // Display table header
    echo "<table class='cart-table'>";
    echo "<tr><th class='name'>Name</th><th class='phone'>Phone</th></tr>";

    // Loop through each row and display name and phone number
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td class='name'><a href='view_order.php?name=" . urlencode($row['name']) . "'>" . $row['name'] . "</a></td>";
        echo "<td class='phone'>" . $row['phone'] . "</td>";
        echo "</tr>";
    }

    // Close the table
    echo "</table>";
} else {
    // If no data found, display a message
    echo '<p class="no-data">No data found.</p>';
}

// Close the statement
$stmt->close();

// Close the database connection
$conn->close();
?>

</div>





<div id="foodHandling" class="content-section">

<!-- Form for uploading food -->
<form id="foodUploadForm" enctype="multipart/form-data">
    <h2>Food Upload</h2>
    <label for="foodImage">Food Image (Max size: 2MB):</label>
    <input type="file" id="foodImage" name="foodImage" accept="image/*" onchange="validateFileSize(this)"><br>
    <label for="foodName">Food Name:</label>
    <input type="text" id="foodName" name="foodName"><br>
    <label for="foodPrice">Price (RM):</label>
    <input type="text" id="foodPrice" name="foodPrice"><br>
    <button type="submit">Upload Food</button>
</form>


<!-- Form for uploading drinks -->
<form id="drinkUploadForm" enctype="multipart/form-data">
    <h2>Drink Upload</h2>
    <label for="drinkImage">Drink Image (Max size: 2MB):</label>
    <input type="file" id="drinkImage" name="drinkImage" accept="image/*" onchange="validateFileSize(this)"><br>
    <label for="drinkName">Drink Name:</label>
    <input type="text" id="drinkName" name="drinkName"><br>
    <label for="drinkPrice">Price (RM):</label>
    <input type="text" id="drinkPrice" name="drinkPrice"><br>
    <button type="submit">Upload Drink</button>
</form>


</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Function to validate file size
    function validateFileSize(input) {
        const maxSize = 2 * 1024 * 1024; // 2MB
        if (input.files && input.files[0]) {
            if (input.files[0].size > maxSize) {
                alert("File size exceeds the limit (2MB). Please choose a smaller file.");
                input.value = ""; // Reset the file input field
            }
        }
    }

    // Function to handle form submission
    function handleFormSubmit(formElement, uploadUrl, successMessage) {
        event.preventDefault(); // Prevent form submission

        // Perform any additional validation if needed

        // Submit the form via AJAX
        var formData = new FormData(formElement);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", uploadUrl, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    // Handle success
                    console.log(xhr.responseText);
                    alert(successMessage); // Display success message
                } else {
                    // Handle failure
                    console.error("Error:", xhr.status);
                    // Display error message if needed
                }
            }
        };
        xhr.send(formData);
    }

    // Handle food form submission
    document.getElementById("foodUploadForm").addEventListener("submit", function (event) {
        handleFormSubmit(this, "upload_food.php", "Food uploaded successfully!");
    });

    // Handle drink form submission
    document.getElementById("drinkUploadForm").addEventListener("submit", function (event) {
        handleFormSubmit(this, "upload_drink.php", "Drink uploaded successfully!");
    });
</script>

<div id="totalSales" class="content-section">
<?php
// Include the database configuration file
include 'config.php';

// Check if a specific date is selected
$selectedDate = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Query to fetch total sales for the selected date
$stmt_sales = $conn->prepare("SELECT SUM(subtotal) AS total_sales FROM cart2 WHERE DATE(created_at) = ?");
$stmt_sales->bind_param("s", $selectedDate);
$stmt_sales->execute();
$result_sales = $stmt_sales->get_result();

// Fetch total sales
$row_sales = $result_sales->fetch_assoc();
$totalSales = $row_sales['total_sales'];

// Query to fetch total participants for the selected date
$stmt_participants = $conn->prepare("SELECT COUNT(DISTINCT user_id) AS total_participants FROM cart2 WHERE DATE(created_at) = ?");
$stmt_participants->bind_param("s", $selectedDate);
$stmt_participants->execute();
$result_participants = $stmt_participants->get_result();

// Fetch total participants
$row_participants = $result_participants->fetch_assoc();
$totalParticipants = $row_participants['total_participants'];

// Display total sales and participants
echo "<h2 style='font-size: 24px; margin-bottom: 10px;'>Total Sales and Participants for $selectedDate</h2>";
echo "<div style='display: flex;'>";
echo "<div style='flex: 1; background-color: #eb9553; padding: 10px; margin-right: 10px;'>";
echo "<p style='font-size: 18px; margin-bottom: 5px;'><strong>Total Sales:</strong></p>";
echo "<p style='font-size: 18px; margin-bottom: 5px;'>RM " . $totalSales . "</p>";
echo "</div>";
echo "<div style='flex: 1; background-color: #eb9553; padding: 10px;'>";
echo "<p style='font-size: 18px; margin-bottom: 5px;'><strong>Total Participants:</strong></p>";
echo "<p style='font-size: 18px; margin-bottom: 5px;'>" . $totalParticipants . "</p>";
echo "</div>";
echo "</div>";

// Close the statements
$stmt_sales->close();
$stmt_participants->close();

// Close the database connection
$conn->close();
?>

<div class="calendar-section">
    <form action="" method="GET">
        <label for="date">Select Date:</label>
        <input type="date" id="date" name="date" value="<?php echo $selectedDate; ?>">
        <input type="submit" value="Submit">
    </form>
</div>
</div>





<div id="paymentMethods" class="content-section">
    <h2>Payment Methods</h2>
    <p>This section displays the available payment methods.</p>

    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Payment Method</th>
                <th>Status</th>

            </tr>
        </thead>
        <tbody>
        <?php
    // Include the database configuration file
    include 'config.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["action"])) {
        if ($_POST["action"] == "receivePayment") {
            // Handle receiving payment
            // Retrieve user_id from the form data
            $user_id = $_POST["user_id"];

            // Update the payment status in the payment_method table
            $sql_update_payment = "UPDATE payment_method SET status = 'Received' WHERE user_id = ?";
            $stmt = $conn->prepare($sql_update_payment);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
        } elseif ($_POST["action"] == "declinePayment") {
            // Handle declining payment
            // Retrieve user_id from the form data
            $user_id = $_POST["user_id"];

            // Update the payment status in the payment_method table
            $sql_update_payment = "UPDATE payment_method SET status = 'Declined' WHERE user_id = ?";
            $stmt = $conn->prepare($sql_update_payment);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
        }
    }

    // Perform database query to fetch user information from user_info table
    $sql = "SELECT u.name, u.phone, p.method, p.user_id, p.status 
            FROM user_info u 
            LEFT JOIN payment_method p ON u.user_id = p.user_id 
            WHERE p.done = 1"; // Only select rows where done is 1
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Output data of each row
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . $row["name"] . "</td>";
            echo "<td>" . $row["phone"] . "</td>";
            echo "<td>" . ($row["method"] ?? "No method") . "</td>"; // Display payment method or "No method" if not available
            
            // Display the appropriate button based on payment status
            echo "<td>";
            if ($row["status"] == "Received") {
                echo "Received";
            } else {
                echo "<form method='post' style='display: inline;'>";
                echo "<input type='hidden' name='user_id' value='" . $row["user_id"] . "'>";
                echo "<button type='submit' name='action' value='receivePayment' style='background-color: green; color: white;'>Receive</button>";
                echo "</form>";
                echo "<form method='post' style='display: inline;'>";
                echo "<input type='hidden' name='user_id' value='" . $row["user_id"] . "'>";
                echo "<button type='submit' name='action' value='declinePayment' style='background-color: red; color: white;'>Decline</button>";
                echo "</form>";
            }
            echo "</td>";
            
            echo "</tr>";
        }
    } else {
        echo "<tr><td colspan='5'>No users found</td></tr>";
    }
?>


        </tbody>
    </table>
</div>


<script>
    // Provided JavaScript code
    function showContent(sectionId) {
        var contentSections = document.getElementsByClassName('content-section');

        for (var i = 0; i < contentSections.length; i++) {
            contentSections[i].style.display = 'none';
        }

        var selectedSection = document.getElementById(sectionId);

        if (selectedSection) {
            selectedSection.style.display = 'block';
            // Store the current section in local storage
            storeCurrentSection(sectionId);
        }
    }

    function showHomeSection() {
        showContent('home');
    }

    function storeCurrentSection(sectionId) {
        localStorage.setItem('currentSection', sectionId);
    }

    window.onload = function() {
        // Retrieve the current section from local storage
        var currentSection = localStorage.getItem('currentSection');
        
        // If there is a current section stored, show it
        if (currentSection) {
            showContent(currentSection);
        } else {
            // Otherwise, show the default section (e.g., "Home")
            showHomeSection();
        }
    };
</script>

</body>
</html>


<style>
    /* CSS for styling the form for uploading menu items */
    #foodUploadForm,
#drinkUploadForm {
    max-width: 400px;
    margin: auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
}

#foodUploadForm label,
#drinkUploadForm label {
    display: block;
    margin-bottom: 10px;
}

#foodUploadForm input[type="file"],
#foodUploadForm input[type="text"],
#drinkUploadForm input[type="file"],
#drinkUploadForm input[type="text"] {
    width: 100%;
    padding: 8px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box; /* Ensures padding and border are included in the width */
}

#foodUploadForm button[type="submit"],
#drinkUploadForm button[type="submit"] {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#foodUploadForm button[type="submit"]:hover,
#drinkUploadForm button[type="submit"]:hover {
    background-color: #45a049;
}



</style>