<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$active_user=$_SESSION['user_id'];


if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}


$stmt = $conn->prepare("SELECT branch_id, branch_name FROM branches ORDER BY branch_name");
$stmt->execute();
$branches = $stmt->fetchAll(PDO::FETCH_ASSOC);



$branchId = null;
$selectedBranchName = null;
$itemType = null;
$items = null;
$searchTerm = '';
$searchField = '';


if (isset($_REQUEST['branch_id']) && $_REQUEST['branch_id'] !== '') {
    $branchId = filter_var($_REQUEST['branch_id'], FILTER_SANITIZE_NUMBER_INT);


    if ($branchId == 0) {
        $selectedBranchName = 'All Branches';
    } else {
        $stmtBranch = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
        $stmtBranch->execute([$branchId]);
        $selectedBranchName = $stmtBranch->fetchColumn() ?: 'Unknown Branch';
    }


    if (isset($_REQUEST['search_term'])) {
        $searchTerm = trim($_REQUEST['search_term']);
    }

    if (isset($_REQUEST['search_field'])) {
        $searchField = $_REQUEST['search_field'];
    }


    if (isset($_REQUEST['item_type']) && !empty($_REQUEST['item_type'])) {
        $itemType = $_REQUEST['item_type'];
        $items = []; // rows are now fetched by the DataTable via AJAX; this only gates which section renders
    }
}

?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<?php if ($branchId !== null && $itemType && $items !== null): ?>
<script>
    $(document).ready(function(){
        const inventoryTable = new DataTable('#example', {
            serverSide: true,
            processing: true,
            ordering: false,
            pageLength: 25,
            dom: 'rtip',
            search: { search: <?php echo json_encode($searchTerm); ?> },
            ajax: {
                url: '../../ajax/inventory/get_branch_inventory_data.php',
                type: 'GET',
                data: function (d) {
                    d.branch_id = <?php echo json_encode($branchId); ?>;
                    d.item_type = <?php echo json_encode($itemType); ?>;
                }
            },
            columns: [
                {
                    data: 'group_key', className: 'text-center', searchable: false,
                    render: () => '<button type="button" class="btn btn-sm btn-primary inventory-group-toggle no-print" aria-label="Show unique codes" aria-expanded="false"><i class="fas fa-plus"></i></button>'
                },
                {
                    data: 'item_name',
                    render: (data, type, row) => data + (row.product_code ? '<div class="text-muted small">' + row.product_code + '</div>' : '')
                },
                {
                    data: 'available_quantity', className: 'text-center', defaultContent: '0',
                    render: (data) => '<span class="badge bg-primary">' + (parseInt(data, 10) || 0) + '</span>'
                },
                { data: 'item_details', defaultContent: 'N/A' },
                { data: 'category' },
                { data: 'unit_price' },
                { data: 'date_entered' },
                { data: 'technical_specs' },
                { data: 'condition' }
            ]
        });

        inventoryTable.on('xhr', function(event, settings, json) {
            const count = document.getElementById('inventoryGroupCount');
            if (count && json && typeof json.recordsTotal !== 'undefined') {
                const total = parseInt(json.recordsTotal, 10) || 0;
                count.textContent = total + (total === 1 ? ' Item Group' : ' Item Groups');
            }
        });

        const liveSearchInput = document.getElementById('inventoryLiveSearch');
        const clearLiveSearch = document.getElementById('clearInventoryLiveSearch');
        let liveSearchTimer;
        if (liveSearchInput) {
            liveSearchInput.addEventListener('input', function() {
                clearTimeout(liveSearchTimer);
                const value = this.value.trim();
                liveSearchTimer = setTimeout(() => inventoryTable.search(value).draw(), 250);
            });
        }
        if (clearLiveSearch) {
            clearLiveSearch.addEventListener('click', function() {
                liveSearchInput.value = '';
                inventoryTable.search('').draw();
                liveSearchInput.focus();
            });
        }

        $('#example tbody').on('click', '.inventory-group-toggle', async function() {
            const button = this;
            const row = inventoryTable.row($(button).closest('tr'));
            if (row.child.isShown()) {
                row.child.hide();
                button.setAttribute('aria-expanded', 'false');
                button.querySelector('i').className = 'fas fa-plus';
                return;
            }

            const panel = document.createElement('div');
            panel.className = 'inventory-code-panel';
            panel.textContent = 'Loading unique codes...';
            row.child(panel).show();
            button.setAttribute('aria-expanded', 'true');
            button.querySelector('i').className = 'fas fa-minus';

            try {
                const params = new URLSearchParams({
                    group_key: row.data().group_key,
                    branch_id: <?php echo json_encode((string)$branchId); ?>
                });
                const response = await fetch('../../ajax/inventory/get_branch_inventory_group_codes.php?' + params.toString(), {
                    headers: { 'Accept': 'application/json' }
                });
                const responseText = await response.text();
                let payload;
                try {
                    payload = JSON.parse(responseText);
                } catch (parseError) {
                    throw new Error('The server returned an invalid response' + (response.status ? ' (HTTP ' + response.status + ')' : '') + '.');
                }
                if (!response.ok || !payload.success) throw new Error(payload.message || 'Unable to load unique codes.');
                renderInventoryGroup(panel, payload);
            } catch (error) {
                panel.textContent = error.message || 'Unable to load unique codes.';
                panel.classList.add('text-danger');
            }
        });

        function createInventoryAction(href, className, title, iconClass) {
            const link = document.createElement('a');
            link.href = href;
            link.className = 'btn btn-sm ' + className;
            link.title = title;
            const icon = document.createElement('i');
            icon.className = iconClass;
            link.appendChild(icon);
            return link;
        }

        function renderInventoryGroup(panel, payload) {
            panel.replaceChildren();
            const heading = document.createElement('strong');
            heading.textContent = 'Unique codes (' + payload.items.length + ')';
            panel.appendChild(heading);
            const list = document.createElement('div');
            list.className = 'inventory-code-list';

            payload.items.forEach((item) => {
                const unit = document.createElement('div');
                unit.className = 'inventory-code-item';
                const details = document.createElement('div');
                const code = document.createElement('strong');
                code.textContent = item.unique_code;
                details.appendChild(code);
                if (item.item_details) {
                    const itemDetails = document.createElement('div');
                    itemDetails.className = 'inventory-item-details';
                    itemDetails.textContent = item.item_details;
                    details.appendChild(itemDetails);
                }
                const metadata = [item.branch_name, item.serial_number ? 'Serial: ' + item.serial_number : ''].filter(Boolean);
                if (metadata.length) {
                    const small = document.createElement('div');
                    small.className = 'text-muted small';
                    small.textContent = metadata.join(' · ');
                    details.appendChild(small);
                }
                unit.appendChild(details);

                const actions = document.createElement('div');
                actions.className = 'action-buttons no-print';
                actions.appendChild(createInventoryAction('edit_item.php?item_id=' + item.item_id, 'btn-edit', 'Edit Item', 'fas fa-edit'));
                actions.appendChild(createInventoryAction('send_to_damaged_item.php?item_id=' + item.item_id, 'btn-send-to-damage', 'Mark as Damaged', 'fas fa-exclamation-circle'));
                actions.appendChild(createInventoryAction('mark_as_an_asset.php?item_id=' + item.item_id, 'btn-nark-as-damage', 'Mark as an Asset', 'fas fa-suitcase'));
                if (payload.can_delete) {
                    actions.appendChild(createInventoryAction('delete_item.php?item_id=' + item.item_id, 'btn-nark-as-delete danger', 'Delete Item', 'fas fa-trash'));
                }
                unit.appendChild(actions);
                list.appendChild(unit);
            });
            if (!payload.items.length) list.textContent = 'No available unique codes were found.';
            panel.appendChild(list);
        }
    });
</script>
<?php endif; ?>
<style>
        .inventory-code-panel {
            background: #f8fafc;
            border: 1px solid #d7dee8;
            border-radius: 10px;
            margin: 8px 12px;
            padding: 14px;
        }

        .inventory-code-list {
            display: grid;
            gap: 8px;
            margin-top: 10px;
        }

        .inventory-code-item {
            align-items: center;
            background: #fff;
            border: 1px solid #d7dee8;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            gap: 12px;
            padding: 10px 12px;
        }

        .inventory-group-toggle {
            border-radius: 50%;
            height: 34px;
            padding: 0;
            width: 34px;
        }

        .inventory-live-search {
            background: #f8fafc;
            border: 1px solid #d7dee8;
            border-radius: 10px;
            margin: 0 0 16px;
            padding: 14px;
        }

        .inventory-live-search label {
            color: #243447;
            display: block;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .inventory-live-search .form-control {
            min-height: 44px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: rgba(255, 255, 255, 0.95);
            padding: 20px 30px;
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .back-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            color: white;
            text-decoration: none;
        }

        .page-title {
            text-align: center;
            margin-bottom: 40px;
        }

        .page-title h1 {
            font-size: 2.5rem;
            font-weight: 700;
            color: white;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .page-title p {
            color: rgba(255, 255, 255, 0.9);
            font-size: 1.1rem;
        }

        .workflow-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .workflow-steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }

        .workflow-steps::before {
            content: '';
            position: absolute;
            top: 25px;
            left: 50px;
            right: 50px;
            height: 2px;
            background: #e9ecef;
            z-index: 1;
        }

        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }

        .step-number {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #e9ecef;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 18px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }

        .step.active .step-number {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }

        .step.completed .step-number {
            background: #28a745;
            color: white;
        }

        .step-title {
            font-weight: 600;
            color: #2c3e50;
            text-align: center;
            font-size: 14px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            width: 35px;
            height: 35px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
        }

        .form-control {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }

        .item-type-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .item-type-btn {
            padding: 20px;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
        }

        .item-type-btn:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }

        .item-type-btn.active {
            border-color: #667eea;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }

        .item-type-icon {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .item-type-title {
            font-weight: 600;
            font-size: 16px;
        }

        .item-type-description {
            font-size: 12px;
            opacity: 0.8;
        }

        .search-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .search-grid {
            display: grid;
            grid-template-columns: 1fr 2fr auto auto;
            gap: 20px;
            align-items: end;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            white-space: nowrap;
        }

        .btn-primary {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        }

        .current-view {
            background: linear-gradient(45deg, #17a2b8, #138496);
            color: white;
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
        }

        .inventory-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 0;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            overflow: hidden;
        }

        .inventory-header {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .inventory-title {
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .inventory-stats {
            display: flex;
            gap: 20px;
            font-size: 14px;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .table-container {
            overflow-x: auto;
            max-height: 600px;
        }

        .inventory-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
            background: #ffffff;
            color: #1f2933;
        }

        .inventory-table th {
            background: #243447;
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
            color: #ffffff;
            border-bottom: 2px solid #35465c;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .inventory-table td {
            padding: 12px;
            border-bottom: 1px solid #d7dee8;
            vertical-align: middle;
            color: #1f2933;
            background: inherit;
        }

        .inventory-table tbody tr {
            transition: all 0.2s ease;
            background: #ffffff;
        }

        .inventory-table tbody tr:nth-child(even) {
            background: #f6f8fb;
        }

        .inventory-table tbody tr:hover {
            background: #e8f1ff;
            transform: none;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .btn-sm {
            padding: 6px 10px;
            font-size: 12px;
            border-radius: 6px;
        }

        .btn-edit {
            background: #ffc107;
            color: #212529;
        }

        .btn-edit:hover {
            background: #e0a800;
            transform: translateY(-1px);
        }

        .btn-delete {
            background: #dc3545;
            color: white;
        }

        .btn-delete:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .loading-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 500;
        }

        .alert-info {
            background: linear-gradient(45deg, #17a2b8, #138496);
            color: white;
            border: none;
        }

        .condition-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .condition-new { background: #28a745; color: white; }
        .condition-used { background: #ffc107; color: #212529; }
        .condition-refurbished { background: #17a2b8; color: white; }

        .price-cell {
            font-weight: 600;
            color: #28a745;
        }

        .id-cell {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #6c757d;
        }

        @media print {
            body {
                background: white !important;
            }

            .no-print {
                display: none !important;
            }

            .print-section {
                display: block !important;
            }

            .inventory-container {
                box-shadow: none;
                border: 1px solid #ddd;
            }

            .inventory-header {
                background: #f8f9fa !important;
                color: #333 !important;
            }

            .action-buttons {
                display: none !important;
            }

            .inventory-table th {
                background: #243447 !important;
                color: #ffffff !important;
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .page-title h1 {
                font-size: 2rem;
            }

            .workflow-steps {
                flex-direction: column;
                gap: 20px;
            }

            .workflow-steps::before {
                display: none;
            }

            .search-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .item-type-buttons {
                grid-template-columns: 1fr;
            }

            .inventory-stats {
                flex-direction: column;
                gap: 10px;
            }

            .table-container {
                font-size: 12px;
            }

            .inventory-table th,
            .inventory-table td {
                padding: 8px 6px;
            }
        }

        .hidden {
            display: none;
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>

    <div class="container">
                <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success no-print">
                <i class="fas fa-check-circle"></i>
                <?php echo htmlspecialchars(urldecode($_GET['success'])); ?>
            </div>
        <?php endif; ?>
        <?php if (isset($_GET['error'])): ?>
            <div class="alert alert-danger no-print">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo htmlspecialchars(urldecode($_GET['error'])); ?>
            </div>
        <?php endif; ?>
        <div class="no-print">

            <div class="header">
                <?php if ($_SESSION['role'] == 'admin'): ?>
                    <a href="../dashboard/admin.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Dashboard
                    </a>
                <?php else: ?>
                    <a href="../dashboard/warehouse.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Dashboard
                    </a>
                <?php endif; ?>

                <div style="display: flex; align-items: center; gap: 15px;">
                    <i class="fas fa-user-circle" style="font-size: 24px; color: #667eea;"></i>
                    <span style="font-weight: 600; color: #2c3e50;">
                        <?php echo htmlspecialchars($_SESSION['username']); ?>
                        (<?php echo ucfirst($_SESSION['role']); ?>)
                    </span>
                </div>
            </div>


            <div class="page-title">
                <h1>Branch Inventory Management</h1>
                <p>Comprehensive inventory tracking and management system</p>
            </div>


            <div class="workflow-container">

                <div class="workflow-steps">
                    <div class="step <?php echo ($branchId !== null) ? 'completed' : 'active'; ?>">
                        <div class="step-number">1</div>
                        <div class="step-title">Select Branch</div>
                    </div>
                    <div class="step <?php echo ($branchId !== null && $itemType === null) ? 'active' : ($itemType !== null ? 'completed' : ''); ?>">
                        <div class="step-number">2</div>
                        <div class="step-title">Load Inventory</div>
                    </div>
                    <div class="step <?php echo ($items !== null) ? 'active' : ''; ?>">
                        <div class="step-number">3</div>
                        <div class="step-title">View Inventory</div>
                    </div>
                </div>

                <form id="inventoryForm" method="POST">

                    <div class="form-section">
                        <div class="section-title">
                            <div class="section-icon">
                                <i class="fas fa-building"></i>
                            </div>
                            Step 1: Select Branch Location
                        </div>
                        <select name="branch_id" id="branch_id" class="form-control" required>
                            <option value="">Choose a branch to view inventory...</option>
                            <option value="0" <?php echo (isset($branchId) && $branchId == 0) ? 'selected' : ''; ?>>
                                🏢 All Branches (Combined View)
                            </option>
                            <?php foreach ($branches as $branch): ?>
                                <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>"
                                    <?php echo (isset($branchId) && $branchId == $branch['branch_id']) ? 'selected' : ''; ?>>
                                    🏪 <?php echo htmlspecialchars($branch['branch_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>


                    <div id="itemTypeSelection" class="form-section <?php echo ($branchId !== null && $branchId !== '') ? 'fade-in' : 'hidden'; ?>">
                        <div class="section-title">
                            <div class="section-icon">
                                <i class="fas fa-tags"></i>
                            </div>
                            Step 2: Click Load Inventory
                        </div>
                        <div class="item-type-buttons">
                             <div class="item-type-btn <?php echo ($itemType === 'detailed') ? 'active' : ''; ?>" data-type="detailed">
                                <div class="item-type-icon">
                                    <i class="fas fa-th-list"></i>
                                </div>
                                <div class="item-type-title">Load inventory</div>
                                <div class="item-type-description"> View all items on stock </div>
                            </div>
                        </div>
                        <input type="hidden" name="item_type" id="item_type" value="<?php echo $itemType; ?>">
                    </div>
                </form>
            </div>
        </div>


        <?php if ($branchId !== null && $itemType && $items !== null): ?>
            <div class="no-print">

                <div class="current-view">
                    <i class="fas fa-eye"></i>
                    <strong>Currently Viewing:</strong>
                    <?php echo htmlspecialchars($selectedBranchName); ?> -
                    <?php echo ($itemType === 'simple') ? 'Simple Items' : 'Detailed Items'; ?>
                    <?php if (!empty($searchTerm)): ?>
                        | Search: "<?php echo htmlspecialchars($searchTerm); ?>"
                    <?php endif; ?>
                </div>


            </div>
        <?php endif;
	
	 
		?>


        <?php if ($branchId !== null && $itemType && $items !== null): ?>
            <div class="inventory-container print-section">
                <div class="inventory-header">
                    <div class="inventory-title">
                        <i class="fas fa-warehouse"></i>
                        <?php echo htmlspecialchars($selectedBranchName); ?> Inventory
                    </div>
                    <div class="inventory-stats">
                        <div class="stat-item">
                            <i class="fas fa-boxes"></i>
                            <span id="inventoryGroupCount">Loading item groups...</span>
                        </div>
                        <div class="stat-item">
                            <i class="fas fa-calendar"></i>
                            <span><?php echo date('M d, Y'); ?></span>
                        </div>
                        <div class="no-print">
                            <button type="button" id="printBtn" class="btn btn-success">
                                <i class="fas fa-print"></i>
                                Print Report
                            </button>
                        </div>


                        <a href="generate_branch_inventorypdf.php?branch_id=<?php echo htmlspecialchars($branchId); ?>&item_type=<?php echo htmlspecialchars($itemType); ?>&search_field=<?php echo htmlspecialchars($searchField); ?>&search_term=<?php echo urlencode($searchTerm); ?>"
                           class="btn btn-primary btn-sm" title="Download PDF">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </a>

                        <a href="generate_branch_inventoryexcel.php?branch_id=<?php echo htmlspecialchars($branchId); ?>&item_type=<?php echo htmlspecialchars($itemType); ?>&search_field=<?php echo htmlspecialchars($searchField); ?>&search_term=<?php echo urlencode($searchTerm); ?>"
                           class="btn btn-success btn-sm" title="Download Excel">
                            <i class="fas fa-file-excel"></i> Download Excel
                        </a>

                    </div>
                </div>

                <div class="inventory-live-search no-print">
                    <label for="inventoryLiveSearch"><i class="fas fa-search"></i> Live Search</label>
                    <div class="input-group">
                        <input type="search" id="inventoryLiveSearch" class="form-control"
                               autocomplete="off"
                               value="<?php echo htmlspecialchars($searchTerm); ?>"
                               placeholder="Search item name, product code, unique code, serial number, category, or specifications...">
                        <button type="button" id="clearInventoryLiveSearch" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Clear
                        </button>
                    </div>
                </div>

                <div class="table-container">
                    <table class="inventory-table" id="example">
                        <thead>
                            <tr>
                                <th class="no-print"><i class="fas fa-plus-circle"></i> Details</th>
                                <th><i class="fas fa-tag"></i> Item Name</th>
                                <th><i class="fas fa-boxes"></i> Available Qty</th>
                                <th><i class="fas fa-align-left"></i> Item Details</th>
                                <th><i class="fas fa-layer-group"></i> Category</th>
                                <th><i class="fas fa-dollar-sign"></i> Unit Price</th>
                                <th><i class="fas fa-calendar-plus"></i> Date Entered</th>
                                <th><i class="fas fa-cogs"></i> Technical Specs</th>
                                <th><i class="fas fa-check-circle"></i> Condition</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        <?php elseif ($branchId !== null): ?>
            <div class="alert alert-info no-print">
                <i class="fas fa-arrow-up"></i>
                Please select an item category above to view the inventory.
            </div>
        <?php endif; ?>
    </div>


    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <h3>Loading Inventory...</h3>
            <p>Please wait while we retrieve your data</p>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {

            const branchSelect = document.getElementById('branch_id');
            const itemTypeSection = document.getElementById('itemTypeSelection');
            const itemTypeButtons = document.querySelectorAll('.item-type-btn');
            const itemTypeInput = document.getElementById('item_type');
            const inventoryForm = document.getElementById('inventoryForm');
            const loadingOverlay = document.getElementById('loadingOverlay');
            const printBtn = document.getElementById('printBtn');
            const clearSearchBtn = document.getElementById('clearSearch');
            const searchForm = document.getElementById('searchForm');


            if (branchSelect) {
                branchSelect.addEventListener('change', function() {
                    if (this.value !== '') {
                        itemTypeSection.classList.remove('hidden');
                        itemTypeSection.classList.add('fade-in');


                        itemTypeButtons.forEach(btn => btn.classList.remove('active'));
                        itemTypeInput.value = '';
                    } else {
                        itemTypeSection.classList.add('hidden');
                        itemTypeSection.classList.remove('fade-in');
                    }
                });
            }


            itemTypeButtons.forEach(function(btn) {
                btn.addEventListener('click', function() {

                    showLoading();


                    itemTypeInput.value = this.getAttribute('data-type');


                    itemTypeButtons.forEach(function(b) {
                        b.classList.remove('active');
                    });
                    this.classList.add('active');


                    inventoryForm.submit();
                });
            });


            if (printBtn) {
                printBtn.addEventListener('click', function() {
                    let tableSearch = '';

                    if (window.jQuery && $.fn.DataTable && $.fn.DataTable.isDataTable('#example')) {
                        tableSearch = $('#example').DataTable().search();
                    }

                    const printUrl = new URL('print_branch_inventory.php', window.location.href);
                    printUrl.searchParams.set('branch_id', <?php echo json_encode((string)$branchId); ?>);
                    printUrl.searchParams.set('item_type', <?php echo json_encode($itemType); ?>);

                    if (tableSearch) {
                        printUrl.searchParams.set('search_term', tableSearch);
                    }

                    window.open(printUrl.toString(), '_blank', 'noopener');
                });
            }


            if (clearSearchBtn) {
                clearSearchBtn.addEventListener('click', function() {
                    document.getElementById('search_term').value = '';
                    document.getElementById('search_field').selectedIndex = 0;
                    searchForm.submit();
                });
            }


            if (searchForm) {
                searchForm.addEventListener('submit', function() {
                    showLoading();
                });
            }


            function showLoading() {
                if (loadingOverlay) {
                    loadingOverlay.style.display = 'flex';
                }
            }


            function hideLoading() {
                if (loadingOverlay) {
                    loadingOverlay.style.display = 'none';
                }
            }


            hideLoading();


            const tableRows = document.querySelectorAll('.inventory-table tbody tr');
            tableRows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = '#f8f9fa';
                });

                row.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '';
                });
            });


            document.addEventListener('keydown', function(e) {

                if (e.ctrlKey && e.key === 'p' && printBtn) {
                    e.preventDefault();
                    printBtn.click();
                }


                if (e.ctrlKey && e.key === 'f') {
                    const searchInput = document.getElementById('search_term');
                    if (searchInput) {
                        e.preventDefault();
                        searchInput.focus();
                    }
                }
            });


            let autoRefreshInterval;
            function startAutoRefresh() {
                autoRefreshInterval = setInterval(() => {
                    if (document.getElementById('search_term').value === '') {

                        console.log('Auto-refreshing inventory...');

                    }
                }, 300000);
            }




            const requiredFields = document.querySelectorAll('[required]');
            requiredFields.forEach(field => {
                field.addEventListener('invalid', function() {
                    this.style.borderColor = '#dc3545';
                });

                field.addEventListener('input', function() {
                    if (this.checkValidity()) {
                        this.style.borderColor = '#28a745';
                    } else {
                        this.style.borderColor = '#dc3545';
                    }
                });
            });


            if (window.location.hash === '#inventory') {
                const inventoryContainer = document.querySelector('.inventory-container');
                if (inventoryContainer) {
                    inventoryContainer.scrollIntoView({ behavior: 'smooth' });
                }
            }
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
