<?php
require_once __DIR__ . '/../../classes/Inventory.php';
include '../../includes/header.php';






$branchId = $auth->getUserBranch($_SESSION['user_id']);


if (!isset($inventory)) {
    $inventory = new Inventory($conn);
}


$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branchId]);
$branchName = $stmt->fetchColumn();




$itemType = isset($_GET['item_type']) ? $_GET['item_type'] : 'simple';




function getSearchFieldOptions($itemType, $currentField) {
    $commonOptions = [
        'unique_id' => 'Unique Code',
        'item_name' => 'Item Name',
        'unit_price' => 'Price'
    ];

    $detailedOptions = [
        'serial_number' => 'Serial Number',
        'technical_specs' => 'Technical Specs'
    ];

    $options = $commonOptions;
  //  if ($itemType === 'detailed') {
        $options = array_merge($options, $detailedOptions);
   // }

    $html = '';
    foreach ($options as $value => $label) {
        $selected = $currentField === $value ? 'selected' : '';
        $html .= "<option value=\"{$value}\" {$selected}>{$label}</option>";
    }

    return $html;
}


function getTableHeaders($itemType) {
    return ['Details', 'Item Name', 'Available Qty', 'Category', 'Price', 'Date Entered', 'Warranty', 'Technical Specs'];
}


?>




<style>
    .branch-stock-page {
        width: calc(100vw - 40px);
        max-width: none;
        margin-left: calc(50% - 50vw + 20px);
        margin-right: 0;
        padding: 0 0 32px;
    }

    .branch-stock-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 16px;
        margin-bottom: 24px;
    }

    .branch-stock-title {
        margin: 0;
        color: #243447;
        font-weight: 700;
        text-align: left;
    }

    .branch-stock-subtitle {
        margin: 6px 0 0;
        color: #6c757d;
        font-size: 0.95rem;
    }

    .branch-stock-card {
        background: #ffffff;
        border: 1px solid #d7dee8;
        border-radius: 8px;
        box-shadow: 0 8px 22px rgba(31, 41, 51, 0.08);
        padding: 20px;
    }

    .branch-stock-card .table-responsive {
        margin: 0;
        padding: 0;
        border-radius: 8px;
        box-shadow: none;
        overflow-x: auto;
    }

    .branch-stock-table {
        margin-bottom: 0;
        min-width: 980px;
    }

    .branch-stock-table th,
    .branch-stock-table td {
        text-align: left;
        vertical-align: middle;
    }

    .branch-stock-table th:nth-child(1),
    .branch-stock-table td:nth-child(1),
    .branch-stock-table th:nth-child(3),
    .branch-stock-table td:nth-child(3),
    .branch-stock-table th:nth-child(5),
    .branch-stock-table td:nth-child(5),
    .branch-stock-table th:nth-child(6),
    .branch-stock-table td:nth-child(6),
    .branch-stock-table th:nth-child(7),
    .branch-stock-table td:nth-child(7) {
        white-space: nowrap;
    }

    .branch-stock-table td:nth-child(5) {
        font-weight: 600;
        color: #243447;
    }

    .branch-stock-table td:nth-child(8) {
        max-width: 360px;
        white-space: normal;
    }

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

    .stock-code-panel {
        background: #f8fafc;
        border: 1px solid #d7dee8;
        border-radius: 8px;
        margin: 8px 12px;
        padding: 14px;
    }

    .stock-code-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 10px;
    }

    .stock-code-item {
        background: #fff;
        border: 1px solid #cbd5e1;
        border-radius: 6px;
        padding: 6px 10px;
    }

    .branch-stock-card .dt-container .dt-layout-row:first-child {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 16px;
        flex-wrap: wrap;
    }

    .branch-stock-card .dt-container .dt-layout-cell {
        width: auto;
    }

    .branch-stock-card .dt-search input {
        min-width: 260px;
    }

    .toggle-buttons {
        margin-bottom: 20px;
    }

    .toggle-btn {
        padding: 8px 16px;
        margin-right: 10px;
        border: 1px solid #ddd;
        background-color: #f8f9fa;
        cursor: pointer;
        text-decoration: none;
        display: inline-block;
    }

    .toggle-btn.active {
        background-color: #007bff;
        color: white;
        border-color: #007bff;
    }

    .toggle-btn:hover {
        text-decoration: none;
        background-color: #e9ecef;
    }

    .toggle-btn.active:hover {
        background-color: #0056b3;
    }

    .search-container {
        margin-bottom: 20px;
    }

    .print-btn {
        margin-left: 10px;
    }

    @media print {
        .no-print {
            display: none;
        }
        .container {
            width: 100%;
            max-width: 100%;
        }
    }

    @media (max-width: 768px) {
        .branch-stock-page {
            width: 100%;
            margin-left: 0;
            padding: 0 0 24px;
        }

        .branch-stock-header {
            align-items: stretch;
            flex-direction: column-reverse;
            margin-bottom: 18px;
        }

        .branch-stock-header .btn {
            width: 100%;
        }

        .branch-stock-card {
            padding: 12px;
        }

        .branch-stock-card .dt-container .dt-layout-row:first-child,
        .branch-stock-card .dt-container .dt-layout-row:last-child {
            align-items: stretch;
            flex-direction: column;
        }

        .branch-stock-card .dt-search input {
            min-width: 0;
            width: 100%;
        }
    }
</style>




<div class="branch-stock-page mt-3 mb-5">


    <div class="branch-stock-header no-print">
        <div>
            <h2 class="branch-stock-title">Branch Stock</h2>
            <p class="branch-stock-subtitle"><?php echo htmlspecialchars($branchName); ?> inventory list</p>
        </div>
        <a href="<?php echo getDashboardLink(); ?>" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
        </a>
    </div>


    <!--
    <div class="toggle-buttons no-print">
        <a href="?item_type=simple" class="toggle-btn <?php echo $itemType === 'simple' ? 'active' : ''; ?>">
            Simple Items
        </a>
        <a href="?item_type=detailed" class="toggle-btn <?php echo $itemType === 'detailed' ? 'active' : ''; ?>">
            Detailed Items
        </a>
    </div> -->

    <!--
    <div class="search-container no-print">
        <form method="GET" class="form-inline">
            <input type="hidden" name="item_type" value="<?php echo htmlspecialchars($itemType); ?>">
            <div class="form-row align-items-center">
                <div class="col-auto">
                    <select name="search_field" class="form-control mb-2">
                        <?php echo getSearchFieldOptions($itemType, $searchField); ?>
                    </select>
                </div>
                <div class="col-auto">
                    <input type="text"
                           name="search_term"
                           class="form-control mb-2"
                           placeholder="Search..."
                           value="<?php echo htmlspecialchars($searchTerm); ?>">
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-primary mb-2">Search</button>
                    <button type="button" class="btn btn-secondary mb-2 print-btn" onclick="window.print();">
                        Print
                    </button>
                </div>
            </div>
        </form>
    </div> -->


    <div class="branch-stock-card">
        <div class="table-responsive">
            <table class="table table-striped table-hover branch-stock-table" id="example">
                <thead>
                    <tr>
                        <?php foreach (getTableHeaders($itemType) as $header): ?>
                            <th><?php echo htmlspecialchars($header); ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>
</div>




<script>
    const stockTable = new DataTable('#example', {
        serverSide: true,
        processing: true,
        ordering: false,
        responsive: false,
        autoWidth: false,
        pageLength: 25,
        order: [[1, 'asc']],
        ajax: {
            url: '../../ajax/inventory/branch_stock_data.php',
            type: 'GET'
        },
        columns: [
            {
                data: 'group_key',
                className: 'text-center',
                searchable: false,
                render: () => '<button type="button" class="btn btn-outline-primary btn-sm stock-group-toggle" 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: 'category' },
            { data: 'unit_price' },
            { data: 'date_entered' },
            { data: 'warranty' },
            { data: 'technical_specs' }
        ],
        language: {
            search: 'Search stock:',
            lengthMenu: 'Show _MENU_ items'
        }
    });

    document.querySelector('#example tbody').addEventListener('click', async function(event) {
        const button = event.target.closest('.stock-group-toggle');
        if (!button) return;

        const row = stockTable.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 = 'stock-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 url = '../../ajax/inventory/branch_stock_group_codes.php?group_key=' + encodeURIComponent(row.data().group_key);
            const response = await fetch(url, { 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.');

            panel.replaceChildren();
            const heading = document.createElement('strong');
            heading.textContent = 'Unique codes (' + payload.codes.length + ')';
            panel.appendChild(heading);
            const list = document.createElement('div');
            list.className = 'stock-code-list';
            payload.codes.forEach((item) => {
                const code = document.createElement('span');
                code.className = 'stock-code-item';
                code.textContent = item.unique_code + (item.serial_number ? ' · Serial: ' + item.serial_number : '');
                list.appendChild(code);
            });
            if (!payload.codes.length) list.textContent = 'No available unique codes were found.';
            panel.appendChild(list);
        } catch (error) {
            panel.textContent = error.message || 'Unable to load unique codes.';
            panel.classList.add('text-danger');
        }
    });
</script>

<?php include '../../includes/footer.php'; ?>
