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

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

$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

if (isset($_SESSION["id"])) {
    header("Location: ");
    exit;
}

$Orders = new NewOrder();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Check if form fields are set and not empty
    if (!empty($_POST["category"]) && !empty($_POST["product"]) && !empty($_POST["variation"]) && !empty($_POST["price"]) && !empty($_POST["quantity"])) {
        // Retrieve form data
        $category = $_POST["category"];
        $product = $_POST["product"];
        $variation = $_POST["variation"];
        $price = $_POST["price"];
        $quantity = $_POST["quantity"];

        // Insert data into the database
        $query = "INSERT INTO warehouse (category, product, variation, price, quantity) VALUES (?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($connection, $query);

        if ($stmt) {
            // Bind parameters
            mysqli_stmt_bind_param($stmt, "sssss", $category, $product, $variation, $price, $quantity);

            // Execute the statement
            if (mysqli_stmt_execute($stmt)) {
                echo "<script>alert('Entry Added Successfully'); window.location='_approved_stock.php'; </script>";
            } else {
                echo "<script>alert('Failed to add entry. Please try again later.');</script>";
            }

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

?>
<body>
    <div class="container">
    
        <form action="" method="POST">
            <div class="form-group">
            <div id="warantee_button">
  <div class="item-right"><button class="reset-button"><a href="stock.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>
    <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>
<button type="button" class="btn btn-outline-success" style="width:100px">
<input type="text" class="form-control " 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>
</body>
 
<?php 
 include("include/footer_link.php");
  ?>
<script src="assets/script/script.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    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');
 
 
    categorySelect.addEventListener('change', function() {
        // Clear existing product options
        productSelect.innerHTML = '<option value="">Select product</option>';
        // Fetch selected category
        var selectedCategory = categorySelect.value;
        // Fetch products for the selected category using AJAX
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    var products = JSON.parse(xhr.responseText);
                    // Add options for each product
                    products.forEach(function(product) {
                        var option = document.createElement('option');
                        option.value = product;
                        option.textContent = product;
                        productSelect.appendChild(option);
                    });
                } else {
                    console.error('Request failed: ' + xhr.status);
                }
            }
        };
        // Send AJAX request to fetch products for selected category
        xhr.open('GET', 'fetch_approved_product.php?category=' + encodeURIComponent(selectedCategory));
        xhr.send();
    });
    
    
   productSelect.addEventListener('change', function() {
    // Check if variationSelect is defined
    if (!variationSelect) {
        console.error('variationSelect is not defined');
        return; // Exit the function if variationSelect is not defined
    }

    // Clear existing variation options
    variationSelect.innerHTML = '<option value="">Select variation</option>';

    // Fetch selected product
    var selectedProduct = productSelect.value;

    // Fetch variations for the selected product using AJAX
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var variations = JSON.parse(xhr.responseText);
                // Add options for each variation
                variations.forEach(function(variation) {
                    var option = document.createElement('option');
                    option.value = variation;
                    option.textContent = variation;
                    variationSelect.appendChild(option);
                });
            } else {
                console.error('Request failed: ' + xhr.status);
            }
        }
    };

    // Send AJAX request to fetch variations for selected product
    xhr.open('GET', 'fetch_approved_variations.php?product=' + encodeURIComponent(selectedProduct));
    xhr.send();
});

variationSelect.addEventListener('change', function() {
    var selectedVariation = variationSelect.value;

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.success && typeof response.price === 'string') {
                        // Extract numeric value from the price string
                        var numericPrice = parseFloat(response.price);
                        if (!isNaN(numericPrice)) {
                            // Set the numeric value to the input field
                            priceInput.value = '₹' + numericPrice.toFixed(2);
                        } else {
                            console.error('Invalid price format');
                        }
                    } else {
                        console.error('Invalid response format');
                    }
                } catch (error) {
                    console.error('Error parsing JSON: ', error);
                }
            } else {
                console.error('Request failed: ' + xhr.status);
            }
        }
    };

    xhr.open('GET', 'fetch_approved_price.php?variation=' + encodeURIComponent(selectedVariation));
    xhr.send();
});

variationSelect.addEventListener('change', function() {
    var selectedVariation = variationSelect.value;

    var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
            try {
                var response = JSON.parse(xhr.responseText);
                if (response.success && typeof response.quantity === 'string') {
                    var quantityValue = parseFloat(response.quantity);
                    if (!isNaN(quantityValue)) {
                        quantityInput.value = quantityValue;
                    } else {
                        console.error('Invalid quantity');
                    }
                } else {
                    console.error('Invalid response format');
                }
            } catch (error) {
                console.error('Error parsing JSON: ', error);
                console.log('Response Text:', xhr.responseText); // Log response text for debugging
            }
        } else {
            console.error('Request failed: ' + xhr.status);
        }
    }
};

    xhr.open('GET', 'fetch_approved_quantity.php?variation=' + encodeURIComponent(selectedVariation));
    xhr.send();
});
});
</script>
</html>
