<?php
//session_start();
// Start output buffering to catch any accidental output (e.g. auto-prepended scripts)
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("../db/cn.php");
$conn = $connection;

// 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;
}

// --------------------- AJAX: Search Customer ---------------------
if (isset($_GET['action']) && $_GET['action'] === 'search_customer' && isset($_GET['term'])) {
    // Clean any output that may have been added before (like injected scripts)
    ob_clean();
    header('Content-Type: application/json');
    $term     = trim($_GET['term']);
    $likeTerm = '%' . $term . '%';
    $stmt     = $conn->prepare("SELECT cr_name, phone_number, city, transport FROM credit_note WHERE cr_name LIKE ? LIMIT 10");
    $stmt->bind_param("s", $likeTerm);
    $stmt->execute();
    $result    = $stmt->get_result();
    $customers = [];
    while ($row = $result->fetch_assoc()) {
        $customers[] = $row;
    }
    $stmt->close();
    echo json_encode($customers);
    exit;
}

// --------------------- FETCH PACKAGES ---------------------
$packages = $conn->query("SELECT package_name FROM add_pack");

// --------------------- HANDLE FORM SUBMISSION ---------------------
$success_msg = '';
$error_msg   = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['gatePass'])) {
    $customer_name  = trim($_POST['customer_name'] ?? '');
    $customer_phone = trim($_POST['customer_phone'] ?? '');
    $city           = trim($_POST['city'] ?? '');
    $transport      = trim($_POST['transport'] ?? '');
    $qtys           = $_POST['qty'] ?? [];
    $packages_sel   = $_POST['packing_type'] ?? [];

    if (empty($customer_name) || empty($customer_phone) || empty($city) || empty($transport)) {
        $error_msg = "Please fill all customer details.";
    } elseif (empty($qtys) || empty($packages_sel)) {
        $error_msg = "Please add at least one item.";
    } else {
        do {
            $order_id = 'GP-' . sprintf("%05d", rand(0, 99999));
            $check    = $conn->prepare("SELECT id FROM gatepass WHERE order_id = ?");
            $check->bind_param("s", $order_id);
            $check->execute();
            $check->store_result();
            $exists = $check->num_rows > 0;
            $check->close();
        } while ($exists);

        $date_time     = date('Y-m-d');
        $total_qty_sum = array_sum($qtys);

        $insertStmt = $conn->prepare("INSERT INTO gatepass (customer_name, customer_phone, city, transport, item_name, qty, package, total_qty, order_id, date_time, user_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        $errors = [];
        for ($i = 0; $i < count($qtys); $i++) {
            $qty  = (int) $qtys[$i];
            $pkg  = trim($packages_sel[$i] ?? '');
            if ($qty <= 0 || empty($pkg)) {
                $errors[] = "Row " . ($i + 1) . " has invalid data.";
                continue;
            }
            // item_name is always '0', removed from UI
            $item = '0';
            $insertStmt->bind_param("sssssssssss",
                $customer_name, $customer_phone, $city, $transport,
                $item, $qty, $pkg, $total_qty_sum, $order_id, $date_time, $userName
            );
            $insertStmt->execute();
        }
        $insertStmt->close();

        if (!empty($errors)) {
            $error_msg = "Some rows could not be saved: " . implode("; ", $errors);
        } else {
            $success_msg = "Gate Pass generated successfully! Order ID: $order_id";
        }
    }
}

// URL for AJAX calls – automatically matches your file name (add_gp.php)
$ajax_url = htmlspecialchars($_SERVER['PHP_SELF']);
?>
<!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>Add GatePass</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">

    <script src="https://cdn.jsdelivr.net/npm/chart.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-wrapper { position: relative; }
        .autocomplete-items {
            position: absolute;
            border: 1px solid #d4d4d4;
            border-top: none;
            z-index: 9999;
            top: 100%;
            left: 0;
            right: 0;
            max-height: 220px;
            overflow-y: auto;
            background: #fff;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-radius: 0 0 4px 4px;
        }
        .autocomplete-items div {
            padding: 10px 14px;
            cursor: pointer;
            background-color: #fff;
            border-bottom: 1px solid #f0f0f0;
            font-weight: 600;
            font-size: 14px;
        }
        .autocomplete-items div:hover,
        .autocomplete-active {
            background-color: #0A4657 !important;
            color: #fff !important;
        }
    </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-fluid">
                <div class="row">
                    <div class="col-sm-9">
                        <h3 style="color:#212529; font-weight:700;">Add Gate Pass</h3>
                    </div>
                </div>
            </div>
            <br>

            <div class="container-fluid">

                <?php if ($success_msg): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($success_msg) ?>
                        <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                    </div>
                <?php endif; ?>
                <?php if ($error_msg): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($error_msg) ?>
                        <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                    </div>
                <?php endif; ?>

                <form method="post" id="gatePassForm">
                    <div class="row">

                        <div class="col-sm-3">
                            <div class="form-group autocomplete-wrapper">
                                <label>Customer Name</label>
                                <input type="text" class="form-control" name="customer_name" id="customer_name"
                                       autocomplete="off" placeholder="Type to search..." required>
                                <div id="customerNameDropdown" class="autocomplete-items" style="display:none;"></div>
                            </div>
                        </div>

                        <div class="col-sm-3">
                            <div class="form-group">
                                <label>Customer Phone</label>
                                <input type="text" class="form-control" name="customer_phone" id="customer_phone" required>
                            </div>
                        </div>

                        <div class="col-sm-3">
                            <div class="form-group">
                                <label>City</label>
                                <input type="text" class="form-control" name="city" id="city" required>
                            </div>
                        </div>

                        <div class="col-sm-3">
                            <div class="form-group">
                                <label>Transport</label>
                                <input type="text" class="form-control" name="transport" id="transport" required>
                            </div>
                        </div>

                    </div><!-- /.row -->

                    <div class="col-sm-12" style="max-height:500px; overflow-y:auto;">
                        <table class="table table-bordered text-center font-weight-bold" id="itemsTable">
                            <thead class="bg-dark text-white">
                                <tr>
                                    <th>Sr#</th>
                                    <th>Packing - Type</th>
                                    <th>Qty</th>
                                    <th>Add / Remove</th>
                                </tr>
                            </thead>
                            <tbody id="itemRows">
                                <tr class="item-row">
                                    <td class="sr-no">1</td>
                                    <td>
                                        <select name="packing_type[]" class="form-control packing-type" required>
                                            <option value="">Select Packing Type</option>
                                            <?php if ($packages && $packages->num_rows > 0): ?>
                                                <?php while ($pkg = $packages->fetch_assoc()): ?>
                                                    <option value="<?= htmlspecialchars($pkg['package_name']) ?>">
                                                        <?= htmlspecialchars($pkg['package_name']) ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            <?php endif; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" name="qty[]" class="form-control qty" min="1" value="1" required></td>
                                    <td>
                                        <button type="button" class="btn btn-primary btn-sm add-row-btn">+</button>
                                        <button type="button" class="btn btn-danger btn-sm remove-row-btn">-</button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="row mt-3">
                        <div class="col-sm-3">
                            <div class="form-group">
                                <label>Total Qty</label>
                                <input type="text" class="form-control" name="total_qty" id="total_qty" readonly>
                            </div>
                        </div>
                        <div class="col-sm-3">
                            <div class="form-group">
                                <label>Generate</label><br>
                                <button type="submit" name="gatePass" class="btn btn-primary w-100 font-weight-bold">
                                    Generate GatePass
                                </button>
                            </div>
                        </div>
                    </div>

                </form>
            </div><!-- /.container-fluid -->
        </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>&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</a>
            </div>
        </div>
    </div>
</div>

<script src="../vendor/jquery/jquery.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>

<!-- Dynamic item rows -->
<script>
$(document).ready(function () {

    function updateSrNumbers() {
        $('#itemRows .item-row').each(function (i) {
            $(this).find('.sr-no').text(i + 1);
        });
    }

    function calculateTotalQty() {
        var total = 0;
        $('#itemRows .qty').each(function () {
            total += parseInt($(this).val()) || 0;
        });
        $('#total_qty').val(total);
    }

    $(document).on('click', '.add-row-btn', function () {
        var row   = $(this).closest('.item-row');
        var clone = row.clone();
        // Clear values for new row
        clone.find('input.qty').val('1');
        clone.find('select.packing-type').val('');
        row.after(clone);
        updateSrNumbers();
        calculateTotalQty();
    });

    $(document).on('click', '.remove-row-btn', function () {
        if ($('#itemRows .item-row').length > 1) {
            $(this).closest('.item-row').remove();
            updateSrNumbers();
            calculateTotalQty();
        } else {
            Swal.fire('Info', 'At least one item row is required.', 'info');
        }
    });

    $(document).on('input', '.qty', calculateTotalQty);
    calculateTotalQty();
});
</script>

<!-- Customer Autocomplete (clean JSON response) -->
<script>
$(document).ready(function () {
    var AJAX_URL = '<?= $ajax_url ?>';
    var $input   = $('#customer_name');
    var $dropdown = $('#customerNameDropdown');
    var $phone   = $('#customer_phone');
    var $city    = $('#city');
    var $trans   = $('#transport');

    var activeIdx = -1;
    var customers = [];
    var timer     = null;

    function hideDropdown() {
        $dropdown.hide().empty();
        activeIdx = -1;
        customers = [];
    }

    function fillCustomer(c) {
        $input.val(c.cr_name || '');
        $phone.val(c.phone_number || '');
        $city.val(c.city || '');
        $trans.val(c.transport || '');
        hideDropdown();
    }

    function highlightActive() {
        $dropdown.find('div').removeClass('autocomplete-active');
        $dropdown.find('div').eq(activeIdx).addClass('autocomplete-active');
    }

    function renderDropdown(list) {
        $dropdown.empty();
        activeIdx = -1;

        if (!list || list.length === 0) {
            hideDropdown();
            return;
        }

        customers = list;
        $.each(list, function (i, c) {
            var $div = $('<div></div>').text(c.cr_name);
            $div.on('mousedown', function (e) {
                e.preventDefault();
                fillCustomer(c);
            });
            $dropdown.append($div);
        });
        $dropdown.show();
    }

    function search(term) {
        $.ajax({
            url: AJAX_URL,
            data: { action: 'search_customer', term: term },
            dataType: 'json',
            cache: false,
            success: function (data) {
                renderDropdown(data);
            },
            error: function (xhr, status, error) {
                console.error('Autocomplete error:', status, error, xhr.responseText);
                hideDropdown();
            }
        });
    }

    $input.on('input', function () {
        var term = $.trim($(this).val());
        clearTimeout(timer);
        if (term.length < 2) {
            hideDropdown();
            return;
        }
        timer = setTimeout(function () { search(term); }, 300);
    });

    $input.on('keydown', function (e) {
        var $divs = $dropdown.find('div');
        if (!$divs.length || !$dropdown.is(':visible')) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            activeIdx = (activeIdx + 1) % $divs.length;
            highlightActive();
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            activeIdx = (activeIdx - 1 + $divs.length) % $divs.length;
            highlightActive();
        } else if (e.key === 'Enter' && activeIdx > -1) {
            e.preventDefault();
            fillCustomer(customers[activeIdx]);
        } else if (e.key === 'Escape') {
            hideDropdown();
        }
    });
 
    $input.on('blur', function () {
        setTimeout(hideDropdown, 200);
    });

    $(document).on('click', function (e) {
        if (!$(e.target).closest('.autocomplete-wrapper').length) {
            hideDropdown();
        }
    });
});
</script>


    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>
<?php
// Flush the output buffer (the whole page) at the very end
ob_end_flush();
?>