<?php
require_once __DIR__ . '/../config.php';
requireRole(['admin']);

$pageTitle = 'Admin Dashboard';
require_once __DIR__ . '/../includes/admin-header.php';

require_once __DIR__ . '/../lib/logic.php';
$kpis = getDashboardKPIs();

$pdo = getDBConnection();
$recentOrders = $pdo->query("SELECT * FROM orders ORDER BY PO_Date DESC LIMIT 10")->fetchAll();
$recentTransactions = $pdo->query("SELECT * FROM inventory_transaction ORDER BY transaction_date DESC LIMIT 10")->fetchAll();
$allUsers = $pdo->query("SELECT * FROM users ORDER BY created_at DESC")->fetchAll();
$allSuppliers = $pdo->query("SELECT * FROM suppliers ORDER BY SupplierName")->fetchAll();
?>

        <div class="row g-4 mb-4">
            <div class="col-md-3">
                <div class="card stat-card primary">
                    <div class="card-body">
                        <div class="text-muted">Total Orders</div>
                        <div class="stat-value"><?php echo number_format($kpis['total_orders']); ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card success">
                    <div class="card-body">
                        <div class="text-muted">Total Items</div>
                        <div class="stat-value"><?php echo number_format($kpis['total_items']); ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card warning">
                    <div class="card-body">
                        <div class="text-muted">Total Suppliers</div>
                        <div class="stat-value"><?php echo number_format($kpis['total_suppliers']); ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card danger">
                    <div class="card-body">
                        <div class="text-muted">Total Users</div>
                        <div class="stat-value"><?php echo count($allUsers); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4 mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Recent Orders</h5>
                        <a href="procurement.php" class="btn btn-sm btn-outline-primary">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentOrders)): ?>
                            <p class="text-muted">No orders found</p>
                        <?php else: ?>
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Item</th>
                                        <th>Qty</th>
                                        <th>Supplier</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentOrders as $order): ?>
                                    <tr>
                                        <td><?php echo $order['OrderID']; ?></td>
                                        <td><?php echo sanitize($order['ItemCode'] ?? '-'); ?></td>
                                        <td><?php echo number_format($order['Quantity'] ?? 0); ?></td>
                                        <td><?php echo sanitize($order['Supplier'] ?? '-'); ?></td>
                                        <td><?php echo $order['PO_Date'] ?? '-'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">System Users</h5>
                        <a href="users.php" class="btn btn-sm btn-outline-primary">Manage Users</a>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <th>Full Name</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($allUsers as $user): ?>
                                <tr>
                                    <td><?php echo sanitize($user['username']); ?></td>
                                    <td><?php echo sanitize($user['full_name']); ?></td>
                                    <td><span class="badge bg-<?php echo $user['role'] === 'admin' ? 'danger' : ($user['role'] === 'manager' ? 'warning' : 'info'); ?>"><?php echo ucfirst($user['role']); ?></span></td>
                                    <td><span class="badge bg-<?php echo $user['active'] ? 'success' : 'secondary'; ?>"><?php echo $user['active'] ? 'Active' : 'Inactive'; ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4 mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Recent Transactions</h5>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-success" onclick="exportTransactions()">
                                <i class="bi bi-download"></i> Export
                            </button>
                            <button class="btn btn-sm btn-outline-primary" onclick="showImportModal()">
                                <i class="bi bi-upload"></i> Import
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row g-2 mb-3">
                            <div class="col-auto">
                                <input type="date" id="filterStartDate" class="form-control form-control-sm" placeholder="Start Date">
                            </div>
                            <div class="col-auto">
                                <input type="date" id="filterEndDate" class="form-control form-control-sm" placeholder="End Date">
                            </div>
                            <div class="col-auto">
                                <input type="text" id="filterItemCode" class="form-control form-control-sm" placeholder="Item Code">
                            </div>
                        </div>
                    <div class="card-body">
                        <?php if (empty($recentTransactions)): ?>
                            <p class="text-muted">No transactions found</p>
                        <?php else: ?>
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Item</th>
                                        <th>Type</th>
                                        <th>In</th>
                                        <th>Out</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentTransactions as $t): ?>
                                    <tr>
                                        <td><?php echo $t['transaction_date']; ?></td>
                                        <td><?php echo sanitize($t['item_code']); ?></td>
                                        <td><?php echo sanitize($t['trans_type']); ?></td>
                                        <td class="text-success"><?php echo $t['quantity_in'] > 0 ? $t['quantity_in'] : '-'; ?></td>
                                        <td class="text-danger"><?php echo $t['quantity_out'] > 0 ? $t['quantity_out'] : '-'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header"><h5 class="mb-0">Suppliers</h5></div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Contact</th>
                                    <th>Lead Time</th>
                                    <th>Rating</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($allSuppliers as $s): ?>
                                <tr>
                                    <td><?php echo sanitize($s['SupplierName']); ?></td>
                                    <td><?php echo sanitize($s['ContactPerson']); ?></td>
                                    <td><?php echo $s['LeadTime_Days']; ?> days</td>
                                    <td><?php echo number_format($s['Rating'], 1); ?>/5</td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

<div class="modal-overlay" id="importModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Import Inventory Transactions</h3>
            <button type="button" class="modal-close" onclick="closeModal('importModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="importForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label class="form-label">Select XLSX File</label>
                    <input type="file" name="file" class="form-control" accept=".xlsx" required>
                    <div class="form-hint">File must be in XLSX format with columns matching the inventory transaction table.</div>
                </div>
                <div class="form-group">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="dryRun" name="dry_run" value="1" checked>
                        <label class="form-check-label" for="dryRun">Dry Run (preview only)</label>
                    </div>
                </div>
                <div id="importResult"></div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeModal('importModal')">Close</button>
            <button type="button" class="btn btn-primary" onclick="importTransactions()">Import</button>
        </div>
    </div>
</div>

<script>
function showImportModal() {
    document.getElementById('importModal').classList.add('show');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('show');
}

function exportTransactions() {
    const params = new URLSearchParams({
        start_date: document.getElementById('filterStartDate')?.value || '',
        end_date: document.getElementById('filterEndDate')?.value || '',
        item_code: document.getElementById('filterItemCode')?.value || ''
    });
    window.location.href = '../api/transactions-export.php?' + params.toString();
}

async function importTransactions() {
    const form = document.getElementById('importForm');
    const formData = new FormData(form);
    const resultDiv = document.getElementById('importResult');
    
    resultDiv.innerHTML = '<div class="alert alert-info">Processing...</div>';
    
    try {
        const response = await fetch('../api/transactions-import.php', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        
        if (result.error) {
            resultDiv.innerHTML = '<div class="alert alert-danger">' + result.error + '</div>';
            return;
        }
        
        let html = '<div class="alert alert-' + (result.errors?.length ? 'warning' : 'success') + '">';
        html += '<strong>' + result.message + '</strong><br>';
        html += 'Imported: ' + (result.imported || result.would_import || 0);
        html += ', Skipped: ' + (result.skipped || result.would_skip || 0);
        if (result.errors?.length) {
            html += '<hr><strong>Errors:</strong><ul class="mb-0">';
            result.errors.slice(0, 5).forEach(e => html += '<li>' + e + '</li>');
            if (result.errors.length > 5) html += '<li>...and ' + (result.errors.length - 5) + ' more</li>';
            html += '</ul>';
        }
        html += '</div>';
        resultDiv.innerHTML = html;
        
        if (!form.dry_run.checked && !result.errors?.length) {
            setTimeout(() => location.reload(), 2000);
        }
    } catch (e) {
        resultDiv.innerHTML = '<div class="alert alert-danger">Error: ' + e.message + '</div>';
    }
}
</script>

require_once __DIR__ . '/../includes/admin-footer.php';
