<?php
/**
 * Counter Dashboard - View Assignments & Personal Stats
 *
 * The Counter is the operational user responsible for the physical
 * execution of the stocktake. They act as the primary data entry
 * point, gathering raw inventory data from the physical environment.
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
require_once __DIR__ . '/../lib/ExcelExport.php';
counter_only();

$pageTitle = 'Counter Dashboard';
$db = Database::getInstance();
$userId = SessionManager::getUserId();

// Performance Summary logic from reports.php
$sessionFilter = $_GET['session_id'] ?? '';
$export = $_GET['export'] ?? '';

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

if ($export === 'excel') {
    $data = $db->fetchAll("
        SELECT a.*, s.name as session_name, i.Item_Code as item_code, i.Item_Description AS name,
               i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone, i.Uom as unit_of_measure,
               ce.counted_quantity, ce.counted_at, ce.count_method,
               cr.decision, cr.comments as review_comments
        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
        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 Report');
    $excel->setFilename('my_count_report');
    $excel->setHeaders(['Item Code', 'Item Name', 'Location', 'Session', 'Counted Qty', 'Method', 'Status', 'Decision', 'Counted At']);
    foreach ($data as $d) {
        $excel->addRow([
            $d['item_code'], $d['name'], format_location($d['Stores'], $d['Rack'], $d['Level'], $d['Bin'], $d['zone']),
            $d['session_name'],
            $d['counted_quantity'] ?? '-',
            ucfirst($d['count_method'] ?? '-'),
            ucfirst($d['status']),
            $d['decision'] ? ucfirst($d['decision']) : '-',
            $d['counted_at'] ? format_datetime($d['counted_at']) : '-',
        ]);
    }
    $excel->downloadCSV();
    exit;
}

$varianceBySession = $db->fetchAll("
    SELECT s.name as session_name, s.id as session_id,
        COUNT(a.id) as total,
        SUM(CASE WHEN a.status = 'approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN a.status = 'rejected' THEN 1 ELSE 0 END) as rejected,
        SUM(CASE WHEN a.status = 'counted' THEN 1 ELSE 0 END) as awaiting_review,
        AVG(CASE WHEN ce.id IS NOT NULL THEN ABS(ce.counted_quantity - i.System_Qty) ELSE NULL END) as avg_abs_variance
    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 a.counter_id = ?
    GROUP BY s.id
    ORDER BY s.created_at DESC
", [$userId]);

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



// Personal statistics
$stats = $db->fetch("
    SELECT
        COUNT(*) as total_assignments,
        SUM(CASE WHEN a.status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN a.status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN a.status = 'counted' THEN 1 ELSE 0 END) as counted,
        SUM(CASE WHEN a.status = 'approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN a.status = 'rejected' THEN 1 ELSE 0 END) as rejected,
        SUM(CASE WHEN a.status = 'recount' THEN 1 ELSE 0 END) as recount
    FROM assignments a
    WHERE a.counter_id = ?
", [$userId]);

// Count entries made by this counter
$totalEntries = $db->fetchColumn(
    "SELECT COUNT(*) FROM count_entries WHERE counter_id = ?",
    [$userId]
);

// Active sessions with assignments for this counter
$activeSessions = $db->fetchAll("
    SELECT DISTINCT s.id, s.name, s.status as session_status
    FROM sessions s
    JOIN assignments a ON a.session_id = s.id
    WHERE a.counter_id = ? AND s.status IN ('open', 'in_progress')
    ORDER BY s.created_at DESC
", [$userId]);

// Recent assignments for this counter
$recentAssignments = $db->fetchAll("
    SELECT a.*, s.name as session_name, i.Item_Code as item_code, i.Item_Description as item_name,
           i.Stores, i.Rack, i.Level, i.Bin,
           ce.counted_quantity, ce.counted_at, ce.notes as count_notes, a.zone
    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 a.counter_id = ?
    ORDER BY
        FIELD(a.status, 'recount', 'in_progress', 'pending', 'counted', 'approved', 'rejected'),
        a.updated_at DESC
    LIMIT 20
", [$userId]);

// Unread instructions count
$instructionCount = $db->fetchColumn("
    SELECT COUNT(*) FROM counting_instructions WHERE status = 'active'
");

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



<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon warning">&#9999;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['pending'] ?></div>
            <div class="stat-label">Pending</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon info">&#9203;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['in_progress'] ?></div>
            <div class="stat-label">In Progress</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon success">&#9989;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['counted'] ?></div>
            <div class="stat-label">Submitted</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon success">&#10004;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['approved'] ?></div>
            <div class="stat-label">Approved</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon danger">&#10008;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['rejected'] ?></div>
            <div class="stat-label">Rejected</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon warning">&#128260;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$stats['recount'] ?></div>
            <div class="stat-label">Recount</div>
        </div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
    <!-- Active Sessions -->
    <div class="card">
        <div class="card-header">
            <h3>Active Sessions</h3>
        </div>
        <?php if (empty($activeSessions)): ?>
        <div class="card-body">
            <div class="empty-state">
                <div class="icon">&#128197;</div>
                <h3>No Active Sessions</h3>
                <p>You have no assignments in active sessions.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Session</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($activeSessions as $session): ?>
                    <tr>
                        <td><strong><?= e($session['name']) ?></strong></td>
                        <td><?= status_badge($session['session_status']) ?></td>
                        <td><a href="<?= APP_URL ?>/counter/count_items.php?session_id=<?= $session['id'] ?>" class="btn btn-sm btn-primary">Start Counting</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- Quick Stats -->
    <div class="card">
        <div class="card-header">
            <h3>Personal Tracking</h3>
        </div>
        <div class="card-body">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
                <div style="background:var(--bg-secondary);padding:16px;border-radius:8px;text-align:center">
                    <div style="font-size:28px;font-weight:700;color:var(--primary)"><?= (int)$stats['total_assignments'] ?></div>
                    <div style="font-size:13px;color:var(--text-muted)">Total Assignments</div>
                </div>
                <div style="background:var(--bg-secondary);padding:16px;border-radius:8px;text-align:center">
                    <div style="font-size:28px;font-weight:700;color:var(--success)"><?= (int)$totalEntries ?></div>
                    <div style="font-size:13px;color:var(--text-muted)">Counts Submitted</div>
                </div>
                <div style="background:var(--bg-secondary);padding:16px;border-radius:8px;text-align:center">
                    <div style="font-size:28px;font-weight:700;color:var(--info)"><?= $instructionCount ?></div>
                    <div style="font-size:13px;color:var(--text-muted)">Active Instructions</div>
                </div>
                <div style="background:var(--bg-secondary);padding:16px;border-radius:8px;text-align:center">
                    <div style="font-size:28px;font-weight:700;color:var(--warning)"><?= count($activeSessions) ?></div>
                    <div style="font-size:13px;color:var(--text-muted)">Active Sessions</div>
                </div>
            </div>
            <div style="margin-top:16px">
                <a href="<?= APP_URL ?>/counter/counting_instructions.php" class="btn btn-outline btn-block" style="width:100%;text-align:center">View Counting Instructions</a>
            </div>
        </div>
    </div>
</div>

<!-- Performance Summary Section -->
<div class="page-header" style="margin-top: 48px;">
    <h2>Performance Summary</h2>
    <span class="text-muted">Session performance and accuracy metrics</span>
</div>

<!-- Filters Toolbar -->
<div class="toolbar">
    <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>

<!-- Performance by Session -->
<div class="card mb-3">
    <div class="card-header"><h3>Performance by Session</h3></div>
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Session</th>
                    <th>Total</th>
                    <th>Approved</th>
                    <th>Rejected</th>
                    <th>Awaiting</th>
                    <th>Avg Variance</th>
                    <th>Accuracy</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($varianceBySession)): ?>
                <tr><td colspan="7" class="text-center text-muted" style="padding:30px">No data available.</td></tr>
                <?php else: foreach ($varianceBySession as $vs): ?>
                <tr>
                    <td><strong><?= e($vs['session_name']) ?></strong></td>
                    <td><?= $vs['total'] ?></td>
                    <td><?= status_badge('approved') ?> <?= $vs['approved'] ?></td>
                    <td><?= status_badge('rejected') ?> <?= $vs['rejected'] ?></td>
                    <td><?= status_badge('counted') ?> <?= $vs['awaiting_review'] ?></td>
                    <td><?= $vs['avg_abs_variance'] !== null ? format_number($vs['avg_abs_variance'], 1) : '-' ?></td>
                    <td>
                        <?php $reviewed = $vs['approved'] + $vs['rejected']; ?>
                        <?php if ($reviewed > 0): ?>
                            <?php $accuracy = round(($vs['approved'] / $reviewed) * 100); ?>
                            <div style="background:#e5e7eb;border-radius:10px;height:8px;width:80px;display:inline-block">
                                <div style="background:<?= $accuracy >= 90 ? 'var(--success)' : ($accuracy >= 70 ? 'var(--warning)' : 'var(--danger)') ?>;height:8px;border-radius:10px;width:<?= $accuracy ?>%"></div>
                            </div>
                            <small><?= $accuracy ?>%</small>
                        <?php else: ?>
                            <span class="text-muted">-</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>



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