<?php
/**
 * Counter - Count History
 *
 * Detailed personal count history table.
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
require_once __DIR__ . '/../lib/ExcelExport.php';
counter_only();

$pageTitle = 'My Count History';
$db = Database::getInstance();
$userId = SessionManager::getUserId();

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

$where = "ce.counter_id = ?";
$params = [$userId];
if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}

if ($export === 'excel') {
    $data = $db->fetchAll("
        SELECT ce.*, a.status as assignment_status,
               s.name as session_name, i.Item_Code as item_code, i.Item_Description as item_name,
               i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone, i.Uom as unit_of_measure,
               cr.decision, cr.comments as review_comments
        FROM count_entries ce
        JOIN assignments a ON ce.assignment_id = a.id
        JOIN sessions s ON a.session_id = s.id
        JOIN items i ON a.item_id = i.id
        LEFT JOIN check_reviews cr ON cr.assignment_id = a.id
        WHERE $where
        ORDER BY ce.counted_at DESC
    ", $params);

    $excel = new ExcelExport();
    $excel->setTitle('My Count History');
    $excel->setFilename('count_history');
    $excel->setHeaders(['Item Code', 'Item Name', 'Location', 'Session', 'Counted Qty', 'System Qty', 'Method', 'Status', 'Decision', 'Comments', 'Counted At']);
    foreach ($data as $d) {
        $excel->addRow([
            $d['item_code'], 
            $d['item_name'], 
            format_location($d['Stores'], $d['Rack'], $d['Level'], $d['Bin'], $d['zone']),
            $d['session_name'],
            $d['counted_quantity'],
            $d['system_quantity'],
            ucfirst($d['count_method'] ?? '-'),
            ucfirst($d['assignment_status']),
            $d['decision'] ? ucfirst($d['decision']) : '-',
            $d['review_comments'] ? truncate($d['review_comments'], 50) : '-',
            $d['counted_at'] ? format_datetime($d['counted_at']) : '-'
        ]);
    }
    $excel->downloadCSV();
    exit;
}

// Sessions for filter
$sessions = $db->fetchAll("
    SELECT DISTINCT s.id, s.name
    FROM sessions s
    JOIN assignments a ON a.session_id = s.id
    JOIN count_entries ce ON ce.assignment_id = a.id
    WHERE a.counter_id = ? AND ce.counter_id = ?
    ORDER BY s.name
", [$userId, $userId]);

// Detailed count history (no LIMIT)
$history = $db->fetchAll("
    SELECT ce.*, a.status as assignment_status,
           s.name as session_name, i.Item_Code as item_code, i.Item_Description as item_name,
           i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone, i.Uom as unit_of_measure,
           cr.decision, cr.comments as review_comments
    FROM count_entries ce
    JOIN assignments a ON ce.assignment_id = a.id
    JOIN sessions s ON a.session_id = s.id
    JOIN items i ON a.item_id = i.id
    LEFT JOIN check_reviews cr ON cr.assignment_id = a.id
    WHERE $where
    ORDER BY ce.counted_at DESC
", $params);

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

<!-- Filters -->
<div class="toolbar">
</new
    <form method="GET" class="toolbar-left" style="display:flex;gap:10px;flex-wrap:wrap">
        <select name="session_id" class="form-control" style="width:auto">
            <option value="">All 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-outline">Filter</button>
    </form>
    <div class="toolbar-right">
        <a href="?export=excel&session_id=<?= $sessionFilter ?>" class="btn btn-success">Export Excel</a>
    </div>
</div>

<!-- Count History Table -->
<div class="card">
    <div class="card-header"><h3>All Count Entries (<?= count($history) ?>)</h3></div>
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Session</th>
                    <th>Counted Qty</th>
                    <th>System Qty</th>
                    <th>Method</th>
                    <th>Status</th>
                    <th>Decision</th>
                    <th>Comments</th>
                    <th>Counted At</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($history)): ?>
                <tr><td colspan="10" class="text-center text-muted" style="padding:40px">No count history yet. Start counting items!</td></tr>
                <?php else: foreach ($history as $h): ?>
                <tr>
                    <td>
                        <strong><?= e($h['item_code']) ?></strong><br>
                        <small class="text-muted"><?= e($h['item_name']) ?></small>
                    </td>
                    <td><?= format_location($h['Stores'], $h['Rack'], $h['Level'], $h['Bin'], $h['zone']) ?></td>
                    <td><?= e($h['session_name']) ?></td>
                    <td><strong><?= format_number($h['counted_quantity'], 0) ?></strong></td>
                    <td><?= format_number($h['system_quantity'], 0) ?></td>
                    <td><?= ucfirst($h['count_method'] ?? '-') ?></td>
                    <td><?= status_badge($h['assignment_status']) ?></td>
                    <td>
                        <?php if ($h['decision']): ?>
                            <?= $h['decision'] === 'approved' ? status_badge('approved') : status_badge('rejected') ?>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($h['review_comments']): ?>
                            <small class="text-muted"><?= e(truncate($h['review_comments'], 40)) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><small><?= format_datetime($h['counted_at']) ?></small></td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

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