<?php
session_start();
include_once('../includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:../logout.php');
    exit();
}

$categoryId = isset($_GET['categoryId']) ? trim($_GET['categoryId']) : '';
$brandId = isset($_GET['brandId']) ? trim($_GET['brandId']) : '';
$locationId = isset($_GET['locationId']) ? trim($_GET['locationId']) : '';
$itemCode = isset($_GET['itemCode']) ? trim($_GET['itemCode']) : '';
$stockStatus = isset($_GET['stockStatus']) ? trim($_GET['stockStatus']) : '';

// Get store settings
$storeSettingsQuery = "SELECT * FROM tblstore_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$storeSettingsResult = mysqli_query($con, $storeSettingsQuery);
$storeSettings = null;

if ($storeSettingsResult && mysqli_num_rows($storeSettingsResult) > 0) {
    $storeSettings = mysqli_fetch_assoc($storeSettingsResult);
}
?>
<!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.0">
    <title>Print | Item Stock Report</title>
    <style>
        :root {
            --primary-color: #1a1a1a;
            --success-color: #0d6e5f;
            --danger-color: #991b1b;
            --warning-color: #d97706;
            --accent-color: #2c3e50;
            --border-color: #cbd5e0;
            --muted-text: #64748b;
            --background-color: #f8fafc;
        }

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

        body {
            font-family: 'Arial', 'Helvetica Neue', sans-serif;
            font-size: 10px;
            color: #1a1a1a;
            line-height: 1.3;
            background: #e2e8f0;
        }

        .print-container {
            max-width: 297mm;
            margin: 10px auto;
            padding: 15px;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .print-controls {
            display: flex;
            justify-content: flex-end;
            gap: 6px;
            margin-bottom: 10px;
        }

        .print-controls button {
            padding: 5px 10px;
            border: 1px solid var(--border-color);
            background: white;
            color: var(--accent-color);
            border-radius: 3px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .print-controls button:hover {
            background: var(--background-color);
        }

        .print-controls button.print {
            background: var(--accent-color);
            color: white;
            border-color: var(--accent-color);
        }

        .print-controls button.print:hover {
            background: var(--primary-color);
        }

        .print-header {
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 8px;
            margin-bottom: 12px;
        }

        .header-layout {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .company-section {
            flex: 1;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .logo-container {
            flex-shrink: 0;
        }

        .logo-container img {
            width: 60px;
            height: 60px;
            object-fit: contain;
        }

        .company-info {
            flex: 1;
        }

        .company-name {
            font-size: 16px;
            font-weight: 700;
            letter-spacing: 0.5px;
            color: var(--primary-color);
            text-transform: uppercase;
        }

        .company-details {
            font-size: 9px;
            color: var(--muted-text);
            margin-top: 2px;
            line-height: 1.5;
        }

        .company-details {
            font-size: 9px;
            color: var(--muted-text);
            margin-top: 2px;
        }

        .report-info {
            text-align: right;
            flex: 0 0 auto;
        }

        .report-title {
            font-size: 13px;
            font-weight: 700;
            color: var(--accent-color);
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .report-meta {
            font-size: 9px;
            color: var(--muted-text);
            line-height: 1.4;
        }

        .report-meta strong {
            color: var(--accent-color);
            font-weight: 600;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
            margin-bottom: 10px;
        }

        .summary-card {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 8px;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .summary-card h3 {
            font-size: 8px;
            text-transform: uppercase;
            color: var(--muted-text);
            letter-spacing: 0.3px;
            margin-bottom: 4px;
            font-weight: 600;
        }

        .summary-card .amount {
            font-size: 14px;
            font-weight: 700;
            color: var(--primary-color);
        }

        .summary-card.highlight {
            background: linear-gradient(135deg, #f0fdfa 0%, #e6fffa 100%);
            border-color: #5eead4;
        }

        .summary-card.highlight .amount {
            color: var(--success-color);
        }

        .summary-card.success .amount {
            color: var(--success-color);
        }

        .summary-card.danger .amount {
            color: var(--danger-color);
        }

        .summary-card.warning .amount {
            color: var(--warning-color);
        }

        .stock-info {
            font-size: 9px;
            color: var(--muted-text);
            margin-bottom: 6px;
            padding: 4px 0;
            border-bottom: 1px solid var(--border-color);
        }

        .table-wrapper {
            page-break-inside: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            font-size: 9px;
            border: 1px solid var(--primary-color);
        }

        thead {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        thead th {
            padding: 5px 4px;
            text-align: left;
            font-size: 8px;
            font-weight: 700;
            letter-spacing: 0.3px;
            text-transform: uppercase;
            background: var(--primary-color);
            color: white;
            border-right: 1px solid rgba(255,255,255,0.1);
        }

        thead th:last-child {
            border-right: none;
        }

        tbody td {
            padding: 4px;
            border-bottom: 1px solid #e5e7eb;
            vertical-align: top;
        }

        tbody tr:nth-child(even) {
            background: #f9fafb;
        }

        tbody tr {
            page-break-inside: avoid;
        }

        .totals-section {
            page-break-inside: avoid;
            margin-top: 0;
        }

        tfoot {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        tfoot td {
            padding: 6px 4px;
            font-weight: 700;
            background: #e5e7eb;
            border-top: 2px solid var(--primary-color);
            font-size: 10px;
        }

        tfoot tr:last-child td {
            background: var(--primary-color);
            color: white;
            font-size: 11px;
            padding: 8px 4px;
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }

        .status-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 7px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-in-stock {
            background: #d4edda;
            color: #155724;
        }

        .status-low-stock {
            background: #fff3cd;
            color: #856404;
        }

        .status-out-of-stock {
            background: #f8d7da;
            color: #721c24;
        }

        .status-negative {
            background: #dc3545;
            color: white;
        }

        .text-success {
            color: var(--success-color);
        }

        .text-danger {
            color: var(--danger-color);
        }

        .text-warning {
            color: var(--warning-color);
        }

        .status-message {
            text-align: center;
            padding: 30px 0;
            color: var(--muted-text);
            font-size: 12px;
        }

        .no-print {
            display: block;
        }

        @media print {
            @page {
                size: A4 landscape;
                margin: 8mm;
            }

            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }

            body {
                background: white;
                font-size: 8px;
            }

            .print-container {
                margin: 0;
                padding: 0;
                box-shadow: none;
                max-width: 100%;
            }

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

            .print-header {
                margin-bottom: 8px;
                padding-bottom: 6px;
            }

            .summary-grid {
                margin-bottom: 8px;
                gap: 6px;
            }

            table {
                font-size: 7px;
            }

            thead th {
                font-size: 6.5px;
                padding: 3px 2px;
            }

            tbody td {
                padding: 2px 3px;
            }

            tfoot td {
                padding: 4px 3px;
                font-size: 8px;
            }

            tfoot tr:last-child td {
                font-size: 9px;
                padding: 5px 3px;
            }

            .table-wrapper {
                display: block;
            }

            .totals-section {
                page-break-before: auto;
                page-break-inside: avoid;
                page-break-after: avoid;
            }

            tbody tr {
                page-break-inside: avoid;
            }
        }
    </style>
</head>
<body>
    <div class="print-container">
        <div class="print-controls no-print">
            <button type="button" class="print" onclick="window.print()">🖨️ Print Report</button>
            <button type="button" onclick="window.close()">✕ Close</button>
        </div>

        <div id="loadingState" class="status-message">
            ⏳ Loading stock data...
        </div>

        <div id="errorState" class="status-message" style="display: none; color: var(--danger-color);">
            ⚠️ Unable to load report. Please close this tab and try again.
        </div>

        <div id="reportContent" style="display: none;">
            <div class="print-header">
                <div class="header-layout">
                    <div class="company-section">
                        <?php if ($storeSettings && !empty($storeSettings['StoreLogo1'])): ?>
                        <div class="logo-container">
                            <img src="../<?php echo htmlspecialchars($storeSettings['StoreLogo1']); ?>" alt="Logo">
                        </div>
                        <?php endif; ?>
                        <div class="company-info">
                            <div class="company-name"><?php echo strtoupper(htmlspecialchars($storeSettings['StoreName'] ?? 'STORE NAME')); ?></div>
                            <div class="company-details">
                                <?php if (!empty($storeSettings['Address'])): ?>
                                <?php echo htmlspecialchars($storeSettings['Address']); ?><br>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['City'])): ?>
                                <?php echo htmlspecialchars($storeSettings['City']); ?><?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?><br>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['Mobile'])): ?>
                                Ph: <?php echo htmlspecialchars($storeSettings['Mobile']); ?>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['GSTNumber'])): ?>
                                | GSTIN: <?php echo htmlspecialchars($storeSettings['GSTNumber']); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="report-info">
                        <div class="report-title">Item Stock Report</div>
                        <div class="report-meta">
                            <div id="categoryDiv"><strong>Category:</strong> <span id="reportCategory">All Categories</span></div>
                            <div id="brandDiv"><strong>Brand:</strong> <span id="reportBrand">All Brands</span></div>
                            <div id="locationDiv"><strong>Location:</strong> <span id="reportLocation">All Locations</span></div>
                            <div id="itemDiv"><strong>Item:</strong> <span id="reportItem">All Items</span></div>
                            <div id="statusDiv"><strong>Status:</strong> <span id="reportStatus">-</span></div>
                            <div><strong>Generated:</strong> <span id="generatedDate">-</span></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="summary-grid">
                <div class="summary-card">
                    <h3>Total Items</h3>
                    <div class="amount" id="totalItems">0</div>
                </div>
                <div class="summary-card">
                    <h3>Opening Stock</h3>
                    <div class="amount" id="totalOpeningStock">0</div>
                </div>
                <div class="summary-card highlight">
                    <h3>Current Stock</h3>
                    <div class="amount" id="totalCurrentStock">0</div>
                </div>
                <div class="summary-card">
                    <h3>Stock Value (Cost)</h3>
                    <div class="amount" id="totalStockValueCost">₹0.00</div>
                </div>
                <div class="summary-card success">
                    <h3>Stock Value (Selling)</h3>
                    <div class="amount" id="totalStockValueSelling">₹0.00</div>
                </div>
                <div class="summary-card">
                    <h3>Potential Profit</h3>
                    <div class="amount" id="totalPotentialProfit">₹0.00</div>
                </div>
                <div class="summary-card success">
                    <h3>In Stock</h3>
                    <div class="amount" id="inStockItems">0</div>
                </div>
                <div class="summary-card warning">
                    <h3>Low Stock</h3>
                    <div class="amount" id="lowStockItems">0</div>
                </div>
                <div class="summary-card danger">
                    <h3>Out of Stock</h3>
                    <div class="amount" id="outOfStockItems">0</div>
                </div>
                <div class="summary-card danger">
                    <h3>Negative</h3>
                    <div class="amount" id="negativeStockItems">0</div>
                </div>
            </div>

            <div class="stock-info">
                <strong>Item Count:</strong> <span id="itemCount">0</span> items
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 3%;">S.No</th>
                            <th style="width: 8%;">Item Code</th>
                            <th style="width: 16%;">Item Name</th>
                            <th style="width: 10%;">Category</th>
                            <th style="width: 8%;">Brand</th>
                            <th style="width: 8%;">Location</th>
                            <th style="width: 4%;" class="text-center">Unit</th>
                            <th style="width: 6%;" class="text-right">Opening</th>
                            <th style="width: 6%;" class="text-right">Current</th>
                            <th style="width: 6%;" class="text-right">Alert</th>
                            <th style="width: 7%;" class="text-right">Cost</th>
                            <th style="width: 7%;" class="text-right">Selling</th>
                            <th style="width: 8%;" class="text-right">Value</th>
                            <th style="width: 3%;" class="text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                        <tr><td colspan="14" class="text-center" style="padding: 20px;">No data</td></tr>
                    </tbody>
                </table>
                <table class="totals-section">
                    <tfoot>
                        <tr>
                            <td colspan="7" class="text-right" style="width: 47%;">TOTALS:</td>
                            <td class="text-right" style="width: 6%;" id="totalOpeningFooter">0</td>
                            <td class="text-right" style="width: 6%;" id="totalCurrentFooter">0</td>
                            <td class="text-right" style="width: 6%;">-</td>
                            <td class="text-right" style="width: 7%;">-</td>
                            <td class="text-right" style="width: 7%;">-</td>
                            <td class="text-right" style="width: 8%;" id="totalValueFooter">₹0.00</td>
                            <td class="text-right" style="width: 3%;">-</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <script>
        const PRINT_PARAMS = <?php echo json_encode([
            'categoryId' => $categoryId,
            'brandId' => $brandId,
            'locationId' => $locationId,
            'itemCode' => $itemCode,
            'stockStatus' => $stockStatus,
        ]); ?>;

        function formatCurrency(amount) {
            return '₹' + Number(amount || 0).toLocaleString('en-IN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        function formatNumber(num) {
            return Number(num || 0).toLocaleString('en-IN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        function formatDateTime(date) {
            return date.toLocaleString('en-IN', {
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        function loadPrintReport() {
            const { categoryId, brandId, locationId, itemCode, stockStatus } = PRINT_PARAMS;
            let apiUrl = 'api/get-item-stock-report.php?';
            const params = [];

            if (categoryId) params.push(`categoryId=${encodeURIComponent(categoryId)}`);
            if (brandId) params.push(`brandId=${encodeURIComponent(brandId)}`);
            if (locationId) params.push(`locationId=${encodeURIComponent(locationId)}`);
            if (itemCode) params.push(`itemCode=${encodeURIComponent(itemCode)}`);
            if (stockStatus) params.push(`stockStatus=${encodeURIComponent(stockStatus)}`);

            apiUrl += params.join('&');

            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'API error');
                    }
                    renderPrintReport(data);
                    setTimeout(() => window.print(), 400);
                })
                .catch(() => {
                    document.getElementById('loadingState').style.display = 'none';
                    document.getElementById('errorState').style.display = 'block';
                });
        }

        function renderPrintReport(data) {
            const { summary, items, categoryInfo, brandInfo, locationInfo, itemInfo, stockStatus } = data;

            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('reportContent').style.display = 'block';

            if (categoryInfo) {
                document.getElementById('reportCategory').textContent = categoryInfo;
            } else {
                document.getElementById('categoryDiv').style.display = 'none';
            }

            if (brandInfo) {
                document.getElementById('reportBrand').textContent = brandInfo;
            } else {
                document.getElementById('brandDiv').style.display = 'none';
            }

            if (locationInfo) {
                document.getElementById('reportLocation').textContent = locationInfo;
            } else {
                document.getElementById('locationDiv').style.display = 'none';
            }

            if (itemInfo) {
                document.getElementById('reportItem').textContent = itemInfo.ItemName;
            } else {
                document.getElementById('itemDiv').style.display = 'none';
            }

            if (stockStatus) {
                const statusMap = {
                    'all': 'All Items',
                    'in-stock': 'In Stock',
                    'low-stock': 'Low Stock',
                    'out-of-stock': 'Out of Stock',
                    'negative': 'Negative Stock'
                };
                document.getElementById('reportStatus').textContent = statusMap[stockStatus] || stockStatus;
            } else {
                document.getElementById('statusDiv').style.display = 'none';
            }

            document.getElementById('generatedDate').textContent = formatDateTime(new Date());

            document.getElementById('totalItems').textContent = summary.totalItems;
            document.getElementById('totalOpeningStock').textContent = formatNumber(summary.totalOpeningStock);
            document.getElementById('totalCurrentStock').textContent = formatNumber(summary.totalCurrentStock);
            document.getElementById('totalStockValueCost').textContent = formatCurrency(summary.totalStockValueAtCost);
            document.getElementById('totalStockValueSelling').textContent = formatCurrency(summary.totalStockValueAtSelling);
            document.getElementById('totalPotentialProfit').textContent = formatCurrency(summary.totalPotentialProfit);
            document.getElementById('inStockItems').textContent = summary.inStockItems;
            document.getElementById('lowStockItems').textContent = summary.lowStockItems;
            document.getElementById('outOfStockItems').textContent = summary.outOfStockItems;
            document.getElementById('negativeStockItems').textContent = summary.negativeStockItems;

            renderItemsTable(items, summary);
        }

        function renderItemsTable(items, summary) {
            const tbody = document.getElementById('itemsBody');
            document.getElementById('itemCount').textContent = items.length;

            if (!items.length) {
                tbody.innerHTML = '<tr><td colspan="14" class="text-center" style="padding: 20px;">No items found.</td></tr>';
            } else {
                let rows = '';
                let serialNo = 1;

                items.forEach(item => {
                    let statusClass = '';
                    switch (item.StockStatus) {
                        case 'In Stock':
                            statusClass = 'status-in-stock';
                            break;
                        case 'Low Stock':
                            statusClass = 'status-low-stock';
                            break;
                        case 'Out of Stock':
                            statusClass = 'status-out-of-stock';
                            break;
                        case 'Negative':
                            statusClass = 'status-negative';
                            break;
                    }

                    rows += `
                        <tr>
                            <td class="text-center">${serialNo++}</td>
                            <td><strong>${item.ItemCode}</strong></td>
                            <td>${item.ItemName}</td>
                            <td>${item.CategoryName || '-'}</td>
                            <td>${item.BrandName || '-'}</td>
                            <td>${item.LocationName || '-'}</td>
                            <td class="text-center">${item.UnitName || '-'}</td>
                            <td class="text-right">${formatNumber(item.OpeningStock)}</td>
                            <td class="text-right"><strong>${formatNumber(item.CurrentStock)}</strong></td>
                            <td class="text-right">${formatNumber(item.AlertQuantity)}</td>
                            <td class="text-right">${formatCurrency(item.PurchasePrice)}</td>
                            <td class="text-right">${formatCurrency(item.SalesPrice)}</td>
                            <td class="text-right"><strong>${formatCurrency(item.StockValueAtCost)}</strong></td>
                            <td class="text-center">
                                <span class="status-badge ${statusClass}">${item.StockStatus}</span>
                            </td>
                        </tr>
                    `;
                });

                tbody.innerHTML = rows;
            }

            document.getElementById('totalOpeningFooter').textContent = formatNumber(summary.totalOpeningStock);
            document.getElementById('totalCurrentFooter').textContent = formatNumber(summary.totalCurrentStock);
            document.getElementById('totalValueFooter').textContent = formatCurrency(summary.totalStockValueAtCost);
        }

        document.addEventListener('DOMContentLoaded', loadPrintReport);
    </script>
</body>
</html>
