<?php
/**
 * Inventory Count Summary Report
 * Detailed item-level performance with company branding
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
require_once __DIR__ . '/../lib/ExcelExport.php';
require_once __DIR__ . '/../lib/PDFGenerator.php';
controller_only();

$pageTitle = 'Inventory Count Summary';
$db = Database::getInstance();
$userId = SessionManager::getUserId();

$sessionFilter = $_GET['session_id'] ?? '';
$export = $_GET['export'] ?? '';

// Build Where Clause
$where = "1=1";
$params = [];
if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}

// Fetch Detailed Item Data
$reportData = $db->fetchAll("
    SELECT
        i.Item_Code as item_code,
        i.Item_Description AS name,
        i.Uom as uom,
        ce.counted_quantity,
        s.name as session_name,
        a.status
    FROM assignments a
    JOIN sessions s ON a.session_id = s.id
    JOIN items i ON a.item_id = i.id
    LEFT JOIN count_entries ce ON ce.assignment_id = a.id AND ce.counter_id = a.counter_id
    WHERE $where
    ORDER BY ce.counted_at DESC, i.Item_Code ASC
", $params);

// Export Logic
if ($export === 'excel') {
    $excel = new ExcelExport();
    $excel->setTitle('Inventory Count Summary');
    $excel->setFilename('inventory_summary_' . date('Ymd'));
    $excel->setHeaders(['Session', 'Item Code', 'Description', 'UOM', 'Counted Qty', 'Status']);

    foreach ($reportData as $d) {
        $excel->addRow([
            $d['session_name'],
            $d['item_code'], 
            $d['name'], 
            $d['uom'],
            $d['counted_quantity'] ?? 0,
            $d['status'],
        ]);
    }
    $excel->downloadCSV();
    exit;
}

// Summary Stats
$stats = $db->fetch("
    SELECT
        COUNT(*) as total_assignments,
        SUM(CASE WHEN a.status = 'approved' THEN 1 ELSE 0 END) as approved
    FROM assignments a
    WHERE 1=1" . ($sessionFilter ? " AND a.session_id = ?" : ""), $sessionFilter ? [$sessionFilter] : []);

$sessions = $db->fetchAll("SELECT id, name FROM sessions ORDER BY name ASC");

$sessionTitle = '';
if ($sessionFilter) {
    $sessionTitle = $db->fetch("SELECT name FROM sessions WHERE id = ?", [$sessionFilter]);
    $sessionTitle = $sessionTitle['name'] ?? '';
}

include APP_ROOT . '/templates/header.php';
?>

<style>
.report-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 20px 0;
    border-bottom: 2px solid #eee;
    margin-bottom: 30px;
}
.report-header img {
    width: 100%;
    max-width: 100%;
    height: auto;
    margin-bottom: 10px;
}
.report-title h1 {
    margin: 0;
    color: #4b2c20;
    font-size: 1.8rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}
.stat-box {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    border-top: 4px solid #4b2c20;
}
.stat-box .label { font-size: 0.85rem; color: #666; text-transform: uppercase; }
.stat-box .value { font-size: 1.5rem; font-weight: bold; color: #333; margin-top: 5px; }

@media print {
    .no-print { display: none; }
    .card { border: none; box-shadow: none; }
}
</style>

<div class="report-header">
    <?php $logoPath = get_setting('report_logo_path', 'assets/images/PAB Logo.png'); ?>
    <?php if ($logoPath && file_exists(APP_ROOT . '/' . $logoPath)): ?>
    <img src="<?= APP_URL . '/' . $logoPath ?>" alt="<?= get_setting('company_name', 'Company') ?> Logo" style="width:100%;max-width:100%;height:auto;">
    <?php endif; ?>
</div>

<div class="stats-container">
    <div class="stat-box">
        <div class="label">Total Items</div>
        <div class="value"><?= number_format($stats['total_assignments']) ?></div>
    </div>
    <div class="stat-box">
        <div class="label">Accuracy Rate</div>
        <div class="value">
            <?= $stats['total_assignments'] > 0 ? round(($stats['approved'] / $stats['total_assignments']) * 100, 1) : 0 ?>%
        </div>
    </div>
</div>

<div class="toolbar no-print">
    <form method="GET" class="toolbar-left">
        <select name="session_id" class="form-control" style="width:250px">
            <option value="">All Count Sessions</option>
            <?php foreach ($sessions as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $sessionFilter==$s['id']?'selected':'' ?>><?= e($s['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="btn btn-primary">Filter</button>
    </form>
    <div class="toolbar-right">
        <button onclick="window.print()" class="btn btn-outline">Print PDF</button>
        <a href="?session_id=<?= $sessionFilter ?>&export=excel" class="btn btn-success">Export CSV</a>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Inventory Count Details</h3>
    </div>
    <div class="table-container">
        <table class="table">
                <thead>
                    <tr>
                        <th>Session</th>
                        <th>Item Code</th>
                        <th>Item Description</th>
                        <th class="text-center">UOM</th>
                        <th class="text-right">Count Qty</th>
                        <th class="text-center">Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($reportData)): ?>
                    <tr><td colspan="6" class="text-center p-5 text-muted">No count records found for the selected criteria.</td></tr>
                <?php else: foreach ($reportData as $row):
                    $countQty = $row['counted_quantity'] ?? 0;
                    $statusClass = $row['status'] === 'approved' ? 'badge-success' : ($row['status'] === 'pending' ? 'badge-warning' : 'badge-secondary');
                ?>
                    <tr>
                        <td><small class="text-muted"><?= e($row['session_name']) ?></small></td>
                        <td><strong><?= e($row['item_code']) ?></strong></td>
                        <td><?= e($row['name']) ?></td>
                        <td class="text-center"><small class="text-muted"><?= e($row['uom'] ?: 'N/A') ?></small></td>
                        <td class="text-right font-weight-bold"><?= number_format($countQty, 2) ?></td>
                        <td class="text-center"><span class="badge <?= $statusClass ?>"><?= e($row['status']) ?></span></td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include APP_ROOT . '/templates/footer.php'; ?>
