<?php
// Page settings      
$page_title = 'Sales Request Product';
require_once('includes/load.php');
page_require_level(8);

// Initialize variables for error and success messages
$error_msg = '';
$success_msg = '';

// Function to sanitize input
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $part_number = sanitize_input($_POST['part_number']);
    $quantity = sanitize_input($_POST['quantity']);

    // Validate input
    if (empty($part_number) || empty($quantity) || !is_numeric($quantity) || $quantity <= 0) {
        $error_msg = 'Please provide a valid part number and quantity.';
    } else {
        // Insert data into sales_requests table
        $query = "INSERT INTO sales_requests (part_number, quantity) VALUES ('$part_number', $quantity)";
        if (find_by_sql($query)) {
            $success_msg = 'Sales request submitted successfully.';
        } else {
            $error_msg = 'Error submitting sales request. Please try again.';
        }
    }
}

include_once('layouts/header.php');
?>

<!-- Display messages -->
<div class="row">
    <div class="col-md-12">
        <?php if (!empty($error_msg)): ?>
            <div class="alert alert-danger"><?php echo $error_msg; ?></div>
        <?php endif; ?>
        <?php if (!empty($success_msg)): ?>
            <div class="alert alert-success"><?php echo $success_msg; ?></div>
        <?php endif; ?>
    </div>
</div>

<!-- Sales Request Form -->
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <h3 class="panel-title">Request Sales Product</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="sales_request_product.php">
                    <div class="form-group">
                        <label for="part_number">Part Number:</label>
                        <input type="text" class="form-control" name="part_number" required>
                    </div>
                    <div class="form-group">
                        <label for="quantity">Quantity:</label>
                        <input type="number" class="form-control" name="quantity" required min="1">
                    </div>
                    <button type="submit" class="btn btn-primary">Submit Request</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>
