<?php
/**
 * Checker Reports - Review History & Performance Metrics
 *
 * Provides the Checker with reports on their review activity,
 * including approval/rejection rates and review history.
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
checker_only();

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

// Filters
$sessionFilter = $_GET['session_id'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
$decisionFilter = $_GET['decision'] ?? '';

// Build filter conditions for check_reviews
$where = "cr.checker_id = ?";
$params = [$userId];

if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}
if ($dateFrom) {
    $where .= " AND DATE(cr.reviewed_at) >= ?";
    $params[] = $dateFrom;
}
if ($dateTo) {
    $where .= " AND DATE(cr.reviewed_at) <= ?";
    $params[] = $dateTo;
}
if ($decisionFilter) {
    $where .= " AND cr.decision = ?";
    $params[] = $decisionFilter;
}

// Review history
$reviews = $db->fetchAll("
    SELECT cr.*, a.status as assignment_status,
           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,
           i.Uom as unit_of_measure, s.name as session_name,
           ce.counted_quantity, ce.count_method,
           u.full_name as counter_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
    JOIN count_entries ce ON cr.count_entry_id = ce.id
    JOIN users u ON a.counter_id = u.id
    WHERE $where
    ORDER BY cr.reviewed_at DESC
    LIMIT 100
", $params);

// Summary statistics
$summaryStats = $db->fetch("
    SELECT
        COUNT(*) as total_reviews,
        SUM(CASE WHEN cr.decision = 'approved' THEN 1 ELSE 0 END) as approved_count,
        SUM(CASE WHEN cr.decision = 'rejected' THEN 1 ELSE 0 END) as rejected_count
    FROM check_reviews cr
    JOIN assignments a ON cr.assignment_id = a.id
    WHERE $where
", $params);

$approvedPct = $summaryStats['total_reviews'] > 0
    ? round($summaryStats['approved_count'] / $summaryStats['total_reviews'] * 100, 1)
    : 0;
$rejectedPct = $summaryStats['total_reviews'] > 0
    ? round($summaryStats['rejected_count'] / $summaryStats['total_reviews'] * 100, 1)
    : 0;

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

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

<!-- Summary Stats -->
<div class="stats-grid" style="grid-template-columns:repeat(4,1fr)">
    <div class="stat-card">
        <div class="stat-icon primary">&#128202;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)($summaryStats['total_reviews'] ?? 0) ?></div>
            <div class="stat-label">Total Reviews</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon success">&#10004;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)($summaryStats['approved_count'] ?? 0) ?></div>
            <div class="stat-label">Approved (<?= $approvedPct ?>%)</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon danger">&#10008;</div>
        <div class="stat-content">
            <div class="stat-value"><?= (int)($summaryStats['rejected_count'] ?? 0) ?></div>
            <div class="stat-label">Rejected (<?= $rejectedPct ?>%)</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon info">&#128200;</div>
        <div class="stat-content">
            <div class="stat-value"><?= count($reviews) ?></div>
            <div class="stat-label">Shown</div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-3">
    <div class="card-header">
        <h3>Filters</h3>
    </div>
    <div class="card-body">
        <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:end">
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label">Session</label>
                <select name="session_id" class="form-control" style="width:200px">
                    <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>
            </div>
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label">Decision</label>
                <select name="decision" class="form-control" style="width:150px">
                    <option value="">All</option>
                    <option value="approved" <?= $decisionFilter==='approved'?'selected':'' ?>>Approved</option>
                    <option value="rejected" <?= $decisionFilter==='rejected'?'selected':'' ?>>Rejected</option>
                </select>
            </div>
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= e($dateFrom) ?>" style="width:160px">
            </div>
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= e($dateTo) ?>" style="width:160px">
            </div>
            <button type="submit" class="btn btn-primary">Apply Filters</button>
            <a href="<?= APP_URL ?>/checker/reports.php" class="btn btn-outline">Reset</a>
        </form>
    </div>
</div>

<!-- Review History Table -->
<div class="card">
    <div class="card-header">
        <h3>Review History</h3>
    </div>
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Session</th>
                    <th>Counter</th>
                    <th>System Qty</th>
                    <th>Counted</th>
                    <th>Variance</th>
                    <th>Decision</th>
                    <th>Comments</th>
                    <th>Reviewed</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($reviews)): ?>
                <tr><td colspan="10" class="text-center text-muted" style="padding:40px">No reviews found matching the filters.</td></tr>
                <?php else: foreach ($reviews as $r):
                    $var = $r['counted_quantity'] - $r['system_quantity'];
                ?>
                <tr>
                    <td>
                        <strong><?= e($r['item_code']) ?></strong><br>
                        <small class="text-muted"><?= e($r['name']) ?></small>
                    </td>
                    <td><?= format_location($r['Stores'], $r['Rack'], $r['Level'], $r['Bin']) ?></td>
                    <td><small><?= e($r['session_name']) ?></small></td>
                    <td><?= e($r['counter_name']) ?></td>
                    <td><?= format_number($r['system_quantity'], 0) ?></td>
                    <td><strong><?= format_number($r['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><?= $r['decision'] === 'approved' ? status_badge('approved') : status_badge('rejected') ?></td>
                    <td><?= $r['comments'] ? truncate($r['comments'], 40) : '<span class="text-muted">-</span>' ?></td>
                    <td><small><?= time_ago($r['reviewed_at']) ?></small></td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

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