<?php
/**
 * Checker Dashboard - Verification Stats & Pending Reviews
 *
 * The Checker is the quality assurance role responsible for verifying
 * count data submitted by Counters. The Checker drives the status of
 * inventory tasks by approving, rejecting, or commenting on counts.
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
checker_only();

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

// Statistics for assignments assigned to this checker
$stats = $db->fetch("
    SELECT
        COUNT(*) as total,
        SUM(CASE WHEN a.status = 'counted' THEN 1 ELSE 0 END) as pending_review,
        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,
        SUM(CASE WHEN a.status = 'checked' THEN 1 ELSE 0 END) as checked
    FROM assignments a
    WHERE a.checker_id = ?
", [$userId]);

// Reviews made by this checker
$totalReviews = $db->fetchColumn(
    "SELECT COUNT(*) FROM check_reviews WHERE checker_id = ?",
    [$userId]
);

$approvedReviews = $db->fetchColumn(
    "SELECT COUNT(*) FROM check_reviews WHERE checker_id = ? AND decision = 'approved'",
    [$userId]
);

$rejectedReviews = $db->fetchColumn(
    "SELECT COUNT(*) FROM check_reviews WHERE checker_id = ? AND decision = 'rejected'",
    [$userId]
);

// Active sessions with assignments for this checker
$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.checker_id = ? AND s.status IN ('open', 'in_progress')
    ORDER BY s.created_at DESC
", [$userId]);

// Pending counts awaiting review
$pendingCounts = $db->fetchAll("
    SELECT a.*, 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, i.Uom as unit_of_measure,
           ce.counted_quantity, ce.counted_at, a.zone,
           u.full_name as counter_name
    FROM assignments a
    JOIN sessions s ON a.session_id = s.id
    JOIN items i ON a.item_id = i.id
    JOIN count_entries ce ON ce.assignment_id = a.id
    JOIN users u ON a.counter_id = u.id
    WHERE a.checker_id = ? AND a.status = 'counted'
    ORDER BY
        FIELD(a.priority, 'urgent', 'high', 'normal', 'low'),
        ce.counted_at ASC
    LIMIT 10
", [$userId]);

// Recent reviews by this checker
$recentReviews = $db->fetchAll("
    SELECT cr.*, a.status as assignment_status, i.Item_Code as item_code, i.Item_Description as item_name,
           s.name as session_name
    FROM check_reviews cr
    JOIN assignments a ON cr.assignment_id = a.id
    JOIN items i ON a.item_id = i.id
    JOIN sessions s ON a.session_id = s.id
    WHERE cr.checker_id = ?
    ORDER BY cr.reviewed_at DESC
    LIMIT 10
", [$userId]);

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



<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon warning">&#128203;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)($stats['pending_review'] ?? 0) ?></div>
            <div class="stat-label">Pending Review</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'] ?? 0) ?></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'] ?? 0) ?></div>
            <div class="stat-label">Rejected</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon info">&#128260;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)($stats['recount'] ?? 0) ?></div>
            <div class="stat-label">Recount</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon primary">&#128202;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)$totalReviews ?></div>
            <div class="stat-label">Total Reviews</div>
        </div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
    <!-- Pending Reviews -->
    <div class="card">
        <div class="card-header">
            <h3>Awaiting Review (<?= count($pendingCounts) ?>)</h3>
            <a href="<?= APP_URL ?>/checker/pending_counts.php" class="btn btn-sm btn-primary">View All</a>
        </div>
        <?php if (empty($pendingCounts)): ?>
        <div class="card-body">
            <div class="empty-state">
                <div class="icon">&#9989;</div>
                <h3>All Caught Up</h3>
                <p>No counts are awaiting your review.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Location</th>
                        <th>Counter</th>
                        <th>System</th>
                        <th>Counted</th>
                        <th>Var</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($pendingCounts as $pc):
                        $var = $pc['counted_quantity'] - $pc['system_quantity'];
                    ?>
                    <tr>
                        <td>
                            <strong><?= e($pc['item_code']) ?></strong><br>
                            <small class="text-muted"><?= e($pc['item_name']) ?></small>
                        </td>
                        <td><?= format_location($pc['Stores'], $pc['Rack'], $pc['Level'], $pc['Bin'], $pc['zone']) ?></td>
                        <td><?= e($pc['counter_name']) ?></td>
                        <td><?= format_number($pc['system_quantity'], 0) ?></td>
                        <td><strong><?= format_number($pc['counted_quantity'], 0) ?></strong></td>
                        <td>
                            <span class="variance <?= $var > 0 ? 'positive' : ($var < 0 ? 'negative' : 'zero') ?>">
                                <?= $var > 0 ? '+' : '' ?><?= format_number($var, 0) ?>
                            </span>
                        </td>
                        <td>
                            <a href="<?= APP_URL ?>/checker/pending_counts.php?assignment_id=<?= $pc['id'] ?>" class="btn btn-sm btn-primary">Review</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- Recent Reviews -->
    <div class="card">
        <div class="card-header">
            <h3>Recent Reviews</h3>
            <a href="<?= APP_URL ?>/checker/reports.php" class="btn btn-sm btn-outline-primary">Reports</a>
        </div>
        <?php if (empty($recentReviews)): ?>
        <div class="card-body">
            <div class="empty-state">
                <div class="icon">&#128203;</div>
                <h3>No Reviews Yet</h3>
                <p>Your reviewed counts will appear here.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Session</th>
                        <th>Decision</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentReviews as $review): ?>
                    <tr>
                        <td>
                            <strong><?= e($review['item_code']) ?></strong><br>
                            <small class="text-muted"><?= e($review['item_name']) ?></small>
                        </td>
                        <td><small><?= e($review['session_name']) ?></small></td>
                        <td><?= $review['decision'] === 'approved' ? status_badge('approved') : status_badge('rejected') ?></td>
                        <td><small><?= time_ago($review['reviewed_at']) ?></small></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Active Sessions -->
<div class="card mt-3">
    <div class="card-header">
        <h3>Active Sessions</h3>
    </div>
    <?php if (empty($activeSessions)): ?>
    <div class="card-body">
        <p class="text-muted">No active sessions with assignments for you.</p>
    </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 ?>/checker/pending_counts.php?session_id=<?= $session['id'] ?>" class="btn btn-sm btn-primary">Review Counts</a></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

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