<?php
include('include/session.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// session_start();

include('include/navigation.php');
include('connection.php');
include('class.php');

// Check for session ID and redirect if necessary
if (isset($_SESSION["id"])) {
    header("Location: _order_list.php");
    exit;
}

// Create database connection
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

$Orders = new NewOrder();
// var_dump($_POST);
// $prices =trim(price.value) ;
// var_dump($prices);
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Extract the submitted data
    $categories = $_POST["category"] ?? [];
    $products = $_POST["product"] ?? [];
    $variations = $_POST["variation"] ?? [];
    $prices = $_POST["price"] ?? [];
    $quantities = $_POST["quantity"] ?? [];

    // Check if all arrays are not empty and have the same count
    if (
        is_array($categories) && is_array($products) && is_array($variations) &&
        is_array($prices) && is_array($quantities) &&
        count($categories) > 0 && count($categories) === count($products) &&
        count($products) === count($variations) && count($variations) === count($prices) &&
        count($prices) === count($quantities)
    ) {
        $count = count($categories);
        for ($i = 0; $i < $count; $i++) {
            // Retrieve data for each product entry
            $category = $categories[$i];
            $product = $products[$i];
            $variation = $variations[$i];
            $price = $prices[$i];
            $quantity = $quantities[$i];

            // Prepare and execute the query for each entry
            $query = "INSERT INTO warehouse (category, product, variation, price, quantity) VALUES (?, ?, ?, ?, ?)";
            $stmt = mysqli_prepare($connection, $query);
            mysqli_stmt_bind_param($stmt, "sssss", $category, $product, $variation, $price, $quantity);

            if (mysqli_stmt_execute($stmt)) {
                echo "<script>alert('Entry $i Added Successfully');</script>";
            } else {
                echo "<script>alert('Something went wrong with Entry $i. Please try again later.');</script>";
            }

            mysqli_stmt_close($stmt);
        }
    } else {
        echo "<script>alert('Error: Form fields are empty or not aligned.');</script>";
    }
}

?>
<html lang="en">
<head>
    <link rel="stylesheet" href="assets/css/style.css">
<?php
include('include/header_links.php'); // Move the header links include here
?>
</head>
<body>
      <div class="container_main">
        <div id="warantee_button">
          <div class="item-right">
            <button class="reset-button">
              <a href="store.php">
                <i class="fa-solid fa-backward">
                </i>
              </a>
            </button>
          </div>
          <!--<div class="item-left"><a href="" class="reset-button">Rejected List</a></div>-->
        </div>
        <form action="" method="POST">
          <div class="form-group">
            <h1>
              Approved Store
            </h1>
            <div class="box_button" id="boxButton">
              <button type="button" class="btn btn-outline-success">
                <select class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split category_two"
                id="category_two" name="category[]" required>
                  <option value="">
                    -Select Category-
                  </option>
                  <?php
                        $sql = "SELECT * FROM arrival_store where quality_check_no=0";
                        $result = $connection->query($sql);
                        if ($result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                echo '<option value="' . $row["category"] . '">' . $row["category"] . '</option>';
                            }
                        }
                    ?>
                </select>
              </button>
              <button type="button" class="btn btn-outline-success">
                <select class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split product_two"
                name="product[]" id="product_two" required>
                  <option value="">
                    Select product
                  </option>
                  <!-- Options will be dynamically populated using JavaScript -->
                </select>
              </button>
              <button type="button" class="btn btn-outline-success">
                <select class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split variation_two"
                name="variation[]" id="variation_two" required>
                  <option value="">
                    Select variation
                  </option>
                  <optgroup label="variation">
                    <!-- Options will be dynamically populated using JavaScript -->
                  </optgroup>
                </select>
              </button>
              <button type="button" class="btn btn-outline-success" style="width:160px">
                <input type="text" id="price_two" class="form-control price_two" placeholder="Price"
                aria-label="Price_two" name="price[]" value="" required>
              </button>
            
              <button type="button" class="btn btn-outline-success" style="width:140px">
                <input type="text" class="form-control quantity" placeholder="quantity" aria-label="Text input with segmented dropdown button"
                id="quantity" name="quantity[]" required>
              </button>
              <br>
            </div>
            <div id="clonedContainer">
            </div>
            <br>
            <div class="button" id="add_button">
              <button type="button" class="btn btn-info" id="addMore">
                Add More
              </button>
            </div>
              <center>
                <button type="submit" name="submit" class="btn btn-outline-success btn btn-warning" style="height:40px;">Send to Warehouse</button>
                <button type="button" class="btn btn-outline-success reset-button" style="height:40px;">Send for Processing</button>
            </center>
        </form>
        </div>
            </div>
         <section class="footer">
     <?php include('include/footer_two.php');         ?>
     
 </section>
    </body>
    <?php include( "include/footer_link.php"); ?>
     <!--<script src="assets/script/script.js"></script>-->
      <script>
// Wait for the DOM content to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
    
    // Get references to the select elements and input fields
    var categorySelect = document.getElementById('category_two');
    var productSelect = document.getElementById('product_two');
    var variationSelect = document.getElementById('variation_two');
    var priceInput = document.getElementById('price_two');
    var quantityInput = document.getElementById('quantity');

    // Event listener for the change event on the category select element
document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.category_two')) {
        var categoryId = event.target.value;
        var url = 'fetch_approved_product.php?category=' + categoryId;
    
        // Use AJAX to fetch products
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var nextElementSibling = event.target.parentNode.nextElementSibling;
                if (nextElementSibling && nextElementSibling.querySelector) {
                    nextElementSibling.querySelector('.product_two').innerHTML = xhr.responseText;
                }
            }
        };
        xhr.open('GET', url, true);
        xhr.send();
    }
});

    document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.product_two')) {
        var productId = event.target.value;
        var url = 'fetch_approved_variations.php?product=' + productId;
    
        // Use AJAX to fetch variations
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var nextElementSibling = event.target.parentNode.nextElementSibling;
                if (nextElementSibling && nextElementSibling.querySelector) {
                    nextElementSibling.querySelector('.variation_two').innerHTML = xhr.responseText;
                }
            }
        };
        xhr.open('GET', url, true);
        xhr.send();
    }
});

document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.variation_two')) {
        var variation = event.target.value;
        var priceElement = event.target.parentNode.nextElementSibling.querySelector('.price_two');

        // console.log('Selected Variation ID:', variation);
        $.ajax({
            url: 'fetch_approved_price.php',
            method: 'POST',
            data: { variation: variation }, // Send as POST data
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var formattedPrice = response.price ;
                    if (priceElement) {
                        priceElement.value = formattedPrice;
                    }
                } else {
                    console.error("Error:", response.error);
                    alert('An error occurred while fetching price.');
                }
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert('An error occurred while fetching price.');
            }
        });
    }
});

 document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.variation_two')) {
        var variation = event.target.value;
        var Quantity = event.target.closest('.box_button').querySelector('.quantity');
        console.log(Quantity);
        console.log('Selected Variation ID:', variation);

        // AJAX call to fetch quantity
        $.ajax({
            url: 'fetch_approved_quantity.php',
            method: 'POST',
            data: { variation: variation },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    console.log(response)
                    if (Quantity) {
                        Quantity.value = response.quantity;
                    }
                } else {
                    console.error("Error:", response.error);
                    alert('An error occurred while fetching quantity.');
                }
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert('An error occurred while fetching quantity.');
            }
        });
    }
});


//  document.body.addEventListener('change', function(event) {
//     if (event.target && event.target.matches('.variation_two')) {
//         var variation = event.target.value;
//         var quantityElement = event.target.parentNode.nextElementSibling.querySelector('.quantity');

//         console.log('Selected Variation ID:', variation);

//         // Use AJAX to fetch the quantity
//         $.ajax({
//             url: 'fetch_approved_quantity.php',
//             method: 'POST',
//             data: { variation: variation },
//             dataType: 'json',
//             success: function(response) {
//                 if (response.success) {
//                     if (quantityElement) {
//                         console.log(quantityElement.value = response.quantity);
//                     }
//                 } else {
//                     console.error("Error:", response.error);
//                     alert('An error occurred while fetching quantity.');
//                 }
//             },
//             error: function(xhr, status, error) {
//                 console.error(xhr.responseText);
//                 alert('An error occurred while fetching quantity.');
//             }
//         });
//     }
// });
});


      </script>
      
      </html>