<?php
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['HTTP_HOST'];
$baseDir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$computedBaseUrl = $protocol . $domainName . $baseDir;

// Capture URL variables securely
$product_id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : 0;
$batch_id = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
?>
<script>
    const BaseConfig = { baseUrl: "<?php echo $computedBaseUrl; ?>" };
    const ProductQuery = { pid: <?php echo $product_id; ?>, bid: <?php echo $batch_id; ?> };
</script>

<div class="container-fluid py-4 px-4">
    <div class="mb-4">
        <a href="javascript:history.back()" class="text-decoration-none text-muted fw-bold mb-2 d-inline-block">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to Ledger
        </a>
        <h2 class="h4 text-dark fw-bold m-0"><i class="fa-solid fa-clock-rotate-left text-primary me-2"></i>Product Movement Lifecycle</h2>
        <p class="text-muted small m-0 mt-1">Complete historical audit trail for this specific batch and product.</p>
    </div>

    <div class="card border-0 shadow-sm rounded-3 mb-4 bg-white">
        <div class="card-body p-4 row align-items-center" id="product_meta_container">
            <div class="col-12 text-center py-3"><div class="spinner-border text-primary"></div></div>
        </div>
    </div>

    <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
        <div class="table-responsive">
            <table class="table table-hover align-middle m-0 table-sm">
                <thead class="table-dark small text-uppercase">
                    <tr>
                        <th class="py-3 px-3">Date & Time</th>
                        <th>Transaction ID</th>
                        <th>Activity Type</th>
                        <th class="text-center">Location Activity</th>
                        <th class="text-center text-success">Qty In</th>
                        <th class="text-center text-danger">Qty Out</th>
                        <th>Performed By</th>
                    </tr>
                </thead>
                <tbody id="historyGridBody" class="small">
                    <tr><td colspan="7" class="text-center py-4 text-muted">Awaiting sync...</td></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", async function() {
    if (ProductQuery.pid === 0 || ProductQuery.bid === 0) {
        document.getElementById('product_meta_container').innerHTML = '<div class="alert alert-danger w-100">Invalid Product or Batch parameters provided.</div>';
        return;
    }

    try {
        const apiPath = `${BaseConfig.baseUrl}application/dripend/systemSetup/inventory/fetchStockMovementHistory.php?product_id=${ProductQuery.pid}&batch_id=${ProductQuery.bid}`;
        const res = await fetch(apiPath);
        const data = await res.json();

        if (data.status === 'success') {
            // Render Header
            document.getElementById('product_meta_container').innerHTML = `
                <div class="col-md-5 border-end">
                    <span class="text-uppercase small fw-bold text-muted">Master Generic</span>
                    <h3 class="fw-bold text-primary m-0">${data.meta.generic_name}</h3>
                    <p class="m-0 text-secondary fw-medium mt-1">Brand: <span class="badge bg-light text-dark border">${data.meta.brand_name || 'Generic'}</span></p>
                </div>
                <div class="col-md-3 border-end px-4">
                    <span class="text-uppercase small fw-bold text-muted">Batch ID</span>
                    <h4 class="fw-bold text-dark m-0 font-monospace">${data.meta.batch_number}</h4>
                    <span class="d-block text-danger small fw-bold mt-1"><i class="fa-regular fa-calendar-xmark me-1"></i> Expires: ${data.meta.expiry_date}</span>
                </div>
                <div class="col-md-4 px-4">
                    <span class="text-uppercase small fw-bold text-muted">Current Physical Holding</span>
                    <h2 class="fw-bold text-success m-0">${data.meta.quantity_on_hand} <small class="fs-6 text-muted">Units</small></h2>
                </div>
            `;

            // Render Grid
            const tbody = document.getElementById('historyGridBody');
            tbody.innerHTML = '';
            
            data.history.forEach(tx => {
                const isIncoming = ['Receive', 'Opening Allocation', 'Transfer In'].includes(tx.transaction_type);
                const qIn = isIncoming ? `<span class="fw-bold text-success">+${tx.quantity}</span>` : '-';
                const qOut = !isIncoming ? `<span class="fw-bold text-danger">-${tx.quantity}</span>` : '-';
                
                const locStr = isIncoming ? 
                    `<i class="fa-solid fa-arrow-turn-down text-success me-1"></i> To: ${tx.dest_name || 'System'}` : 
                    `<i class="fa-solid fa-arrow-turn-up text-danger me-1"></i> From: ${tx.source_name || 'System'}`;

                tbody.insertAdjacentHTML('beforeend', `
                    <tr class="bg-white">
                        <td class="px-3 border-end fw-medium">${tx.movement_date}</td>
                        <td class="font-monospace fw-bold text-secondary">${tx.reference_id}</td>
                        <td><span class="badge bg-light text-dark border text-uppercase">${tx.transaction_type}</span></td>
                        <td class="text-center bg-light-subtle">${locStr}</td>
                        <td class="text-center bg-success-subtle">${qIn}</td>
                        <td class="text-center bg-danger-subtle">${qOut}</td>
                        <td class="text-muted"><i class="fa-regular fa-user me-1"></i> ${tx.staff_name || 'System'}</td>
                    </tr>
                `);
            });
        }
    } catch (e) { console.error("History engine failure", e); }
});
</script>