<?php
// session_start();
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

// Handle AJAX request FIRST - before ANY output or includes (except db)
if (isset($_GET['ajax']) && $_GET['ajax'] == 'search_products') {
    // Include database only for AJAX
    include("../db/cn.php");
    
    // Clear any existing buffers
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    header('Content-Type: application/json');
    header('Cache-Control: no-cache');
    
    $searchTerm = isset($_GET['term']) ? trim($_GET['term']) : '';

    if (empty($searchTerm)) {
        echo json_encode([]);
        exit;
    }

    $searchTerm = mysqli_real_escape_string($connection, $searchTerm);

    $query = "SELECT DISTINCT 
                product_name, 
                category, 
                company, 
                supplier, 
                product_unit
              FROM products 
              WHERE product_name LIKE '%$searchTerm%' 
                 OR product_id LIKE '%$searchTerm%'
              ORDER BY product_name ASC 
              LIMIT 20";

    $result = mysqli_query($connection, $query);
    $products = [];

    if ($result && mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $products[] = [
                'label'        => $row['product_name'] . ' (' . ($row['company'] ?: 'No Company') . ')',
                'value'        => $row['product_name'],
                'product_name' => $row['product_name'],
                'category'     => $row['category']     ?: '',
                'company'      => $row['company']      ?: '',
                'supplier'     => $row['supplier']     ?: '',
                'product_unit' => $row['product_unit'] ?: ''
            ];
        }
    }

    echo json_encode($products);
    exit;
}

// For non-AJAX requests, include everything else
include("../db/cn.php");
ob_start();

// Check session
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName       = $_SESSION['user_name'];
    $userRole       = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name    = $_SESSION['outlet_name'];
} else {
    echo "Session variables not set. Please log in.";
    exit;
}

$alertScript = "";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_new'])) {
    $product_id     = mysqli_real_escape_string($connection, $_POST['product_id']);
    $product_name   = mysqli_real_escape_string($connection, $_POST['product_name']);
    $company        = mysqli_real_escape_string($connection, $_POST['company']);
    $quantity       = (int)$_POST['quantity'];
    $retail_price   = (float)$_POST['retail_price'];
    $percentage     = (float)$_POST['percentage'];
    $trade_price    = (float)$_POST['trade_price'];
    $inches         = (float)$_POST['inches'];
    $total_amount   = (float)$_POST['total_amount'];
    $supplier       = mysqli_real_escape_string($connection, $_POST['supplier']);
    $product_unit   = mysqli_real_escape_string($connection, $_POST['product_unit']);
    $category       = mysqli_real_escape_string($connection, $_POST['category']);
    $batch_no       = mysqli_real_escape_string($connection, $_POST['batch_no']);
    $p_type         = mysqli_real_escape_string($connection, $_POST['p_type']);
    $total_purchase = $trade_price * $quantity;
    $date_time      = date("Y-m-d");

    $check_query  = "SELECT * FROM products WHERE product_id = '$product_id'";
    $check_result = mysqli_query($connection, $check_query);

    if (mysqli_num_rows($check_result) > 0) {
        $alertScript = "
            Swal.fire({
                icon: 'warning',
                title: 'Duplicate Entry',
                text: 'Product ID: $product_id already exists!'
            });
        ";
    } else {
        $insert_product_query = "INSERT INTO products 
            (product_id, product_name, category, company, quantity, retail_price, percentage, trade_price, total_amount, total_purchase, product_unit, supplier, date_time, login_user, user_role, outlet_name, outlet_address, inches, batch_no, p_type) 
            VALUES 
            ('$product_id', '$product_name', '$category', '$company', '$quantity', '$retail_price', '$percentage', '$trade_price', '$total_amount', '$total_purchase', '$product_unit', '$supplier', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address', '$inches', '$batch_no', '$p_type')";

        if (!mysqli_query($connection, $insert_product_query)) {
            $alertScript = "
                Swal.fire({
                    icon: 'error',
                    title: 'Error inserting product',
                    text: '" . addslashes(mysqli_error($connection)) . "'
                });
            ";
        } else {
            $insert_opening_product_query = "INSERT INTO opening_products 
                (product_id, product_name, category, company, quantity, retail_price, percentage, trade_price, total_amount, product_unit, supplier, date_time, login_user, user_role, outlet_name, outlet_address, inches) 
                VALUES 
                ('$product_id', '$product_name', '$category', '$company', '$quantity', '$retail_price', '$percentage', '$trade_price', '$total_amount', '$product_unit', '$supplier', '$date_time', '$userName', '$userRole', '$outlet_name', '$outlet_address', '$inches')";

            if (!mysqli_query($connection, $insert_opening_product_query)) {
                $alertScript = "
                    Swal.fire({
                        icon: 'error',
                        title: 'Error inserting opening product',
                        text: '" . addslashes(mysqli_error($connection)) . "'
                    });
                ";
            } else {
                $alertScript = "
                    Swal.fire({
                        icon: 'success',
                        title: 'Product saved successfully!',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => {
                        window.location.href = 'new_product.php';
                    });
                ";
            }
        }
    }
}

$pr_id2 = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

// Get the clean URL for AJAX calls
$ajax_url = $_SERVER['PHP_SELF'];
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>New Product Batch</title>

    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">

    <!-- jQuery BEFORE jQuery UI -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- jQuery UI CSS and JS -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
    body { font-family: 'Quicksand', sans-serif; }
    .bg-gradient-primary { background: #0A4657; color: #fff; }
    .btn-primary { background: #0A4657; color: #fff; border: 1px #0A4657 solid; }
    .btn-primary:hover { background: #fff; border: 1px #0A4657 solid; color: #0A4657; }
    .form-control, option { font-weight: 700; color: #000; }

    /* Autocomplete dropdown styles */
    .ui-autocomplete {
        max-height: 250px;
        overflow-y: auto;
        overflow-x: hidden;
        z-index: 9999 !important;
        background: #fff;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        padding: 4px 0;
        list-style: none;
    }
    .ui-menu-item { padding: 0; }
    .ui-menu-item-wrapper {
        padding: 8px 14px;
        cursor: pointer;
        font-size: 13px;
        color: #333;
        display: block;
    }
    .ui-menu-item-wrapper:hover,
    .ui-state-active,
    .ui-widget-content .ui-state-active {
        background-color: #0A4657 !important;
        color: #fff !important;
        border: none !important;
    }
    .ui-menu-item-wrapper small { font-size: 11px; opacity: 0.8; }
    .loading-spinner { 
        position: absolute; 
        right: 12px; 
        top: 36px; 
        display: none; 
        color: #999;
        z-index: 999;
    }
    .position-relative {
        position: relative;
    }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include("common/sd.php"); ?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>

                <div class="container">
                    <div class="row">
                        <div class="col-sm-9">
                            <h3 style="color:#212529; font-weight:700;">Add Product Batch</h3>
                        </div>
                    </div>
                </div><br>

                <div class="container">
                    <div class="row">
                        <div class="col-sm-1"></div>
                        <div class="col-sm-10">
                            <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" id="productForm">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>Product ID</label>
                                            <input type="text" name="product_id" class="form-control" value="<?php echo $pr_id2; ?>" readonly>
                                        </div>
                                        <div class="form-group position-relative">
                                            <label>Product Name <span class="text-danger">*</span></label>
                                            <input type="text" name="product_name" id="product_name" class="form-control" required autocomplete="off" placeholder="Type to search...">
                                            <span class="loading-spinner" id="loadingSpinner"><i class="fas fa-spinner fa-spin"></i></span>
                                            <small class="text-muted">Type to search existing products</small>
                                        </div>
                                        <div class="row">
                                            <div class="form-group col-6">
                                                <label>Category</label>
                                                <input type="text" name="category" id="category" class="form-control">
                                            </div>
                                            <div class="form-group col-6">
                                                <label>Company</label>
                                                <input type="text" name="company" id="company" class="form-control">
                                            </div>
                                        </div>
                                       
                                    </div>

                                    <div class="col-md-6">
                                         <div class="row">
                                            <div class="form-group col-6">
                                                <label>Supplier</label>
                                                <input type="text" name="supplier" id="supplier" class="form-control">
                                            </div>
                                            <div class="form-group col-6">
                                                <label>Product Unit</label>
                                                <input type="text" name="product_unit" id="product_unit" class="form-control">
                                            </div>
                                        </div>
                                        <div class="">
                                            <div class="">
                                               
                                                <input type="hidden" name="quantity" id="quantity" value="0" class="form-control" step="1" required>
                                            </div>
                                            <div class="">
                                               
                                                <input type="hidden" name="inches" id="inches" value="0" class="form-control" step="0.01" required>
                                            </div>
                                        </div>
                                        <div class="">
                                            <div class="">
                                             
                                                <input type="hidden" name="retail_price" value="0" id="retail_price" class="form-control" step="0.01" required>
                                            </div>
                                            <div class="">
                                              
                                                <input type="hidden" name="trade_price" value="0" id="trade_price" class="form-control" step="0.01" required>
                                            </div>
                                        </div>
                                        <div class="">
                                            <div class="">
                                               
                                                <input type="hidden" name="percentage" value="0" id="percentage" class="form-control" readonly>
                                            </div>
                                            <div class="">
                                         
                                                <input type="hidden" name="total_amount" value="0" id="total_amount" class="form-control" readonly>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="form-group col-6">
                                                <label>Batch No <span class="text-danger">*</span></label>
                                                <input type="text" name="batch_no" class="form-control" required>
                                                <small class="text-muted">Enter new batch number</small>
                                            </div>
                                            <div class="form-group col-6">
                                                <label>Product Type <span class="text-danger">*</span></label>
                                                <select name="p_type" class="form-control" required>
                                                    <option value="">Select Product Type</option>
                                                    <option value="own">Own</option>
                                                    <option value="comission">Comission</option>
                                                </select>
                                            </div>
                                        </div>
                                        <hr>
                                         <button class="btn btn-dark form-control text-white" name="add_new" type="submit">Save Product</button>
                                    </div>
                                </div>
                                
                               
                            </form>
                        </div>
                        <div class="col-sm-1"></div>
                    </div>
                </div>
            </div>
            <br><br>
            <?php include("common/main_ft.php"); ?>
        </div>
    </div>

    <a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>

    <!-- Logout Modal -->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Clean AJAX URL
    var AJAX_URL = window.location.pathname;
    
    $(document).ready(function () {
        console.log("AJAX URL:", AJAX_URL);
        
        $("#product_name").autocomplete({
            source: function (request, response) {
                $("#loadingSpinner").show();
                console.log("Searching for:", request.term);

                $.ajax({
                    url: AJAX_URL,
                    type: "GET",
                    dataType: "json",
                    data: {
                        ajax: "search_products",
                        term: request.term
                    },
                    success: function (data) {
                        $("#loadingSpinner").hide();
                        console.log("Search results:", data);
                        
                        if (data && data.length > 0) {
                            response(data);
                        } else {
                            response([{ label: "No products found", value: "", noResult: true }]);
                        }
                    },
                    error: function (xhr, status, error) {
                        $("#loadingSpinner").hide();
                        console.error("AJAX Error:", status, error);
                        
                        // Try to extract JSON from the response (it's there after the script tags)
                        var responseText = xhr.responseText;
                        var jsonMatch = responseText.match(/\[\{.*\}\]/s);
                        
                        if (jsonMatch) {
                            try {
                                var data = JSON.parse(jsonMatch[0]);
                                console.log("Extracted JSON:", data);
                                if (data && data.length > 0) {
                                    response(data);
                                    return;
                                }
                            } catch(e) {
                                console.error("Failed to parse extracted JSON:", e);
                            }
                        }
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'Search Error',
                            text: 'Failed to search products. Please refresh the page.',
                            footer: 'Status: ' + xhr.status
                        });
                        
                        response([{ label: "Error loading products. Please refresh the page.", value: "", noResult: true }]);
                    }
                });
            },
            minLength: 1,
            select: function (event, ui) {
                event.preventDefault();

                if (ui.item.noResult) {
                    $(this).val('');
                    return false;
                }

                $(this).val(ui.item.product_name);
                $("#category").val(ui.item.category);
                $("#company").val(ui.item.company);
                $("#supplier").val(ui.item.supplier);
                $("#product_unit").val(ui.item.product_unit);

                Swal.fire({
                    icon: 'success',
                    title: 'Product Loaded',
                    text: 'Details filled. Enter batch-specific information.',
                    timer: 1800,
                    showConfirmButton: false
                });

                return false;
            },
            focus: function (event, ui) {
                event.preventDefault();
                if (!ui.item.noResult) {
                    $(this).val(ui.item.product_name);
                }
                return false;
            }
        }).autocomplete("instance")._renderItem = function (ul, item) {
            if (item.noResult) {
                return $("<li>")
                    .append('<div style="padding:8px 14px;color:#999;font-size:13px;">' + item.label + '</div>')
                    .appendTo(ul);
            }
            return $("<li>")
                .append(
                    '<div style="padding:8px 14px;">' +
                    '<strong style="font-size:13px;">' + $('<div/>').text(item.product_name).html() + '</strong>' +
                    (item.company ? ' <span style="color:#888;font-size:12px;">(' + $('<div/>').text(item.company).html() + ')</span>' : '') +
                    '<br><small style="color:#999;">Category: ' + $('<div/>').text(item.category || 'N/A').html() + ' | Unit: ' + $('<div/>').text(item.product_unit || 'N/A').html() + '</small>' +
                    '</div>'
                )
                .appendTo(ul);
        };

        // Clear fields when product name is cleared
        $("#product_name").on('input', function () {
            if ($(this).val().trim() === '') {
                $("#category, #company, #supplier, #product_unit").val('');
            }
        });

        // Calculation listeners
        $("#quantity, #trade_price, #inches").on('input', calculateTotalAmount);
        $("#retail_price, #trade_price").on('input', calculateTradePercentage);
    });

    function calculateTotalAmount() {
        var quantity    = parseFloat($("#quantity").val())    || 0;
        var trade_price = parseFloat($("#trade_price").val()) || 0;
        var inches      = parseFloat($("#inches").val())      || 0;
        var total = (quantity * trade_price * inches).toFixed(2);
        $("#total_amount").val(total);
    }

    function calculateTradePercentage() {
        var retail_price = parseFloat($("#retail_price").val()) || 0;
        var trade_price  = parseFloat($("#trade_price").val())  || 0;
        if (retail_price > 0) {
            var percentage = ((retail_price - trade_price) * 100 / retail_price).toFixed(2);
            $("#percentage").val(percentage);
        } else {
            $("#percentage").val('');
        }
    }

    document.addEventListener("DOMContentLoaded", function () {
        <?php if (!empty($alertScript)) { echo $alertScript; } ?>
    });
    </script>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
</body>
</html>