<?php
/**
 * Checker - Pending Counts (Verification & Approval Workflow)
 *
 * Primary verification interface for the Checker to review counted
 * inventory data. The Checker drives the status of inventory tasks by:
 *   - Approving: Locks the count data for final reporting
 *   - Rejecting/Returning: Sends the task back to the Counter for recount
 *   - Commenting: Adds notes or rejection reasons to guide the Counter
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
checker_only();

$pageTitle = 'Pending Reviews';
$db = Database::getInstance();
$userId = SessionManager::getUserId();

// Handle POST actions (Approve / Reject)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';
    $assignmentId = (int)($_POST['assignment_id'] ?? 0);
    $comments = trim($_POST['comments'] ?? '');

    // Validate assignment belongs to this checker and is in 'counted' status
    $assignment = $db->fetch("
        SELECT a.*, ce.id as count_entry_id, ce.counted_quantity, ce.counter_id as assigned_counter
        FROM assignments a
        JOIN count_entries ce ON ce.assignment_id = a.id
        WHERE a.id = ? AND a.checker_id = ? AND a.status = 'counted'
    ", [$assignmentId, $userId]);

    if (!$assignment) {
        set_error('Assignment not found or not available for review.');
        redirect(APP_URL . '/checker/pending_counts.php');
    }

    if ($action === 'approve') {
        $db->beginTransaction();
        try {
            // Record the review
            $db->insert('check_reviews', [
                'assignment_id'  => $assignmentId,
                'count_entry_id' => $assignment['count_entry_id'],
                'checker_id'     => $userId,
                'decision'       => 'approved',
                'comments'       => $comments ?: null,
            ]);

            // Update assignment status to approved (data locked for reporting)
            $db->update('assignments', [
                'status'      => ASSIGN_APPROVED,
                'updated_at'  => date('Y-m-d H:i:s'),
            ], 'id = ?', [$assignmentId]);

            $db->commit();

            log_action($userId, 'approve_count', 'assignment', $assignmentId, [
                'counted_quantity' => $assignment['counted_quantity'],
                'comments'         => $comments,
            ]);

            set_success('Count approved successfully. Data is now locked for final reporting.');
            redirect(APP_URL . '/checker/pending_counts.php');
        } catch (Exception $e) {
            $db->rollBack();
            set_error('Failed to approve: ' . $e->getMessage());
            redirect(APP_URL . '/checker/pending_counts.php');
        }
    }

    if ($action === 'reject') {
        if (empty($comments)) {
            set_error('A comment is required when rejecting a count. Please explain the discrepancy.');
            redirect(APP_URL . '/checker/pending_counts.php?assignment_id=' . $assignmentId);
        }

        $db->beginTransaction();
        try {
            // Record the review with rejection comments
            $db->insert('check_reviews', [
                'assignment_id'  => $assignmentId,
                'count_entry_id' => $assignment['count_entry_id'],
                'checker_id'     => $userId,
                'decision'       => 'rejected',
                'comments'       => $comments,
            ]);

            // Update assignment status to recount (sends back to counter)
            $db->update('assignments', [
                'status'      => ASSIGN_RECOUNT,
                'updated_at'  => date('Y-m-d H:i:s'),
            ], 'id = ?', [$assignmentId]);

            $db->commit();

            log_action($userId, 'reject_count', 'assignment', $assignmentId, [
                'counted_quantity' => $assignment['counted_quantity'],
                'comments'         => $comments,
                'returned_to'      => $assignment['assigned_counter'],
            ]);

            set_warning('Count rejected and returned to Counter for recount.');
            redirect(APP_URL . '/checker/pending_counts.php');
        } catch (Exception $e) {
            $db->rollBack();
            set_error('Failed to reject: ' . $e->getMessage());
            redirect(APP_URL . '/checker/pending_counts.php');
        }
    }

    if ($action === 'bulk_approve') {
        // Bulk approve all zero-variance counts assigned to this checker
        $zeroVarianceAssignments = $db->fetchAll("
            SELECT a.id, ce.id as count_entry_id, ce.counted_quantity
            FROM assignments a
            JOIN count_entries ce ON ce.assignment_id = a.id
            JOIN items i ON a.item_id = i.id
            WHERE a.checker_id = ? AND a.status = 'counted'
              AND ce.counted_quantity = i.System_Qty
        ", [$userId]);

        if (empty($zeroVarianceAssignments)) {
            set_info('No zero-variance items to approve.');
            redirect(APP_URL . '/checker/pending_counts.php');
        }

        $db->beginTransaction();
        try {
            $approvedCount = 0;
            foreach ($zeroVarianceAssignments as $za) {
                $db->insert('check_reviews', [
                    'assignment_id'  => $za['id'],
                    'count_entry_id' => $za['count_entry_id'],
                    'checker_id'     => $userId,
                    'decision'       => 'approved',
                    'comments'       => 'Bulk approved - zero variance',
                ]);

                $db->update('assignments', [
                    'status'      => ASSIGN_APPROVED,
                    'updated_at'  => date('Y-m-d H:i:s'),
                ], 'id = ?', [$za['id']]);

                $approvedCount++;
            }

            $db->commit();

            log_action($userId, 'bulk_approve', 'assignment', 0, [
                'approved_count' => $approvedCount,
            ]);

            set_success("Successfully approved {$approvedCount} item(s) with zero variance.");
            redirect(APP_URL . '/checker/pending_counts.php');
        } catch (Exception $e) {
            $db->rollBack();
            set_error('Failed to bulk approve: ' . $e->getMessage());
            redirect(APP_URL . '/checker/pending_counts.php');
        }
    }
}

// Filters
$sessionFilter = $_GET['session_id'] ?? '';
$assignmentId = (int)($_GET['assignment_id'] ?? 0);

// If specific assignment requested, show detail view
$activeAssignment = null;
if ($assignmentId) {
$activeAssignment = $db->fetch("
        SELECT a.*, s.name as session_name,
               i.Item_Code as item_code, i.Item_Description as item_name, i.Item_Description as item_description,
               i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone, i.Uom as unit_of_measure, i.Item_Group as category,
               ce.counted_quantity, ce.count_method, ce.notes as count_notes,
               ce.counted_at,
               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.id = ? AND a.checker_id = ? AND a.status = 'counted'
    ", [$assignmentId, $userId]);

    if (!$activeAssignment) {
        set_error('Assignment not found or not available for review.');
        redirect(APP_URL . '/checker/pending_counts.php');
    }

    // Get previous reviews for this assignment
    $previousReviews = $db->fetchAll("
        SELECT cr.*, u.full_name as reviewer_name
        FROM check_reviews cr
        JOIN users u ON cr.checker_id = u.id
        WHERE cr.assignment_id = ?
        ORDER BY cr.reviewed_at DESC
    ", [$assignmentId]);
}

// Build assignment list for pending counts
$where = "a.checker_id = ? AND a.status = 'counted'";
$params = [$userId];
if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}

    $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, a.zone,
           ce.counted_quantity, ce.count_method, ce.counted_at,
           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 $where
    ORDER BY
        FIELD(a.priority, 'urgent', 'high', 'normal', 'low'),
        ce.counted_at ASC
", $params);

// Sessions with pending counts for this checker
$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 = ? AND a.status = 'counted'
    ORDER BY s.name
", [$userId]);

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

<?php if ($activeAssignment): ?>
<!-- DETAIL VIEW: Review a specific count -->
<div class="mb-3">
    <a href="<?= APP_URL ?>/checker/pending_counts.php" class="btn btn-outline">Back to List</a>
</div>

<?php
    $variance = $activeAssignment['counted_quantity'] - $activeAssignment['system_quantity'];
    $variancePct = $activeAssignment['system_quantity'] > 0
        ? round(abs($variance) / $activeAssignment['system_quantity'] * 100, 1)
        : ($activeAssignment['counted_quantity'] > 0 ? 100 : 0);
?>

<div style="display:grid;grid-template-columns:1fr 380px;gap:24px">
    <!-- Main Review Area -->
    <div>
        <!-- Count Comparison Card -->
        <div class="card mb-3">
            <div class="card-header">
                <h3>Count Comparison</h3>
                <?= priority_badge($activeAssignment['priority']) ?>
            </div>
            <div class="card-body">
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:20px">
                    <div style="background:var(--bg-secondary);padding:20px;border-radius:8px;text-align:center">
                        <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px">System Quantity</div>
                        <div style="font-size:32px;font-weight:700;color:var(--text-primary)">
                            <?= format_number($activeAssignment['system_quantity'], 0) ?>
                        </div>
                        <div style="font-size:12px;color:var(--text-muted)"><?= e($activeAssignment['unit_of_measure']) ?></div>
                    </div>
                    <div style="background:var(--bg-secondary);padding:20px;border-radius:8px;text-align:center">
                        <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px">Counted Quantity</div>
                        <div style="font-size:32px;font-weight:700;color:var(--primary)">
                            <?= format_number($activeAssignment['counted_quantity'], 0) ?>
                        </div>
                        <div style="font-size:12px;color:var(--text-muted)"><?= e($activeAssignment['unit_of_measure']) ?></div>
                    </div>
                    <div style="background:<?= $variance == 0 ? 'rgba(40,167,69,0.1)' : 'rgba(220,53,69,0.1)' ?>;padding:20px;border-radius:8px;text-align:center">
                        <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px">Variance</div>
                        <div style="font-size:32px;font-weight:700;color:<?= $variance == 0 ? 'var(--success)' : 'var(--danger)' ?>">
                            <?= $variance > 0 ? '+' : '' ?><?= format_number($variance, 0) ?>
                        </div>
                        <div style="font-size:12px;color:var(--text-muted)"><?= $variancePct ?>% diff</div>
                    </div>
                </div>

                <!-- Item Details -->
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:14px">
                    <div>
                        <span class="text-muted">Item:</span>
                        <strong><?= e($activeAssignment['item_code']) ?></strong> - <?= e($activeAssignment['item_name']) ?>
                    </div>
                    <div>
                        <span class="text-muted">Location:</span>
                        <strong><?= format_location($activeAssignment['Stores'], $activeAssignment['Rack'], $activeAssignment['Level'], $activeAssignment['Bin'], $activeAssignment['zone']) ?></strong>
                    </div>
                    <div>
                        <span class="text-muted">Counter:</span>
                        <strong><?= e($activeAssignment['counter_name']) ?></strong>
                    </div>
                    <div>
                        <span class="text-muted">Count Method:</span>
                        <strong><?= ucfirst($activeAssignment['count_method']) ?></strong>
                    </div>
                    <div>
                        <span class="text-muted">Counted At:</span>
                        <strong><?= format_datetime($activeAssignment['counted_at']) ?></strong>
                    </div>
                    <div>
                        <span class="text-muted">Category:</span>
                        <strong><?= e($activeAssignment['category'] ?: '-') ?></strong>
                    </div>
                </div>

                <?php if ($activeAssignment['count_notes']): ?>
                <div style="margin-top:16px;padding:12px;background:var(--bg-secondary);border-radius:6px">
                    <div style="font-size:12px;color:var(--text-muted);margin-bottom:4px">Counter Notes</div>
                    <div><?= nl2br(e($activeAssignment['count_notes'])) ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Checker Action Form -->
        <div class="card">
            <div class="card-header">
                <h3>Checker Decision</h3>
            </div>
            <div class="card-body">
                <form method="POST" id="checkerForm">
                    <?= Csrf::field() ?>
                    <input type="hidden" name="assignment_id" value="<?= $activeAssignment['id'] ?>">
                    <input type="hidden" name="action" id="checkerAction" value="">

                    <div class="form-group">
                        <label class="form-label">Comments / Notes</label>
                        <textarea name="comments" class="form-control" rows="4" id="commentsField"
                                  placeholder="Add notes or reasons for rejection to guide the Counter during recount..."><?= e($_POST['comments'] ?? '') ?></textarea>
                        <small class="text-muted">Required when rejecting. Optional when approving.</small>
                    </div>

                    <div class="btn-group" style="margin-top:16px">
                        <button type="button" class="btn btn-success btn-lg" onclick="submitAction('approve')">
                            &#10004; Approve
                        </button>
                        <button type="button" class="btn btn-danger btn-lg" onclick="submitAction('reject')">
                            &#10008; Reject & Return for Recount
                        </button>
                        <a href="<?= APP_URL ?>/checker/pending_counts.php" class="btn btn-outline">Cancel</a>
                    </div>
                </form>
            </div>
        </div>

        <?php if (!empty($previousReviews)): ?>
        <!-- Previous Reviews -->
        <div class="card mt-3">
            <div class="card-header">
                <h3>Review History</h3>
            </div>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Checker</th>
                            <th>Decision</th>
                            <th>Comments</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($previousReviews as $review): ?>
                        <tr>
                            <td><?= e($review['reviewer_name']) ?></td>
                            <td><?= $review['decision'] === 'approved' ? status_badge('approved') : status_badge('rejected') ?></td>
                            <td><?= $review['comments'] ? nl2br(e($review['comments'])) : '<span class="text-muted">-</span>' ?></td>
                            <td><small><?= format_datetime($review['reviewed_at']) ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Sidebar -->
    <div>
        <div class="card mb-2">
            <div class="card-header"><h3>Item Details</h3></div>
            <div class="card-body" style="font-size:14px">
                <div style="margin-bottom:12px">
                    <div class="text-muted">Item Code</div>
                    <div><strong><?= e($activeAssignment['item_code']) ?></strong></div>
                </div>
                <div style="margin-bottom:12px">
                    <div class="text-muted">Item Name</div>
                    <div><?= e($activeAssignment['item_name']) ?></div>
                </div>
                <?php if ($activeAssignment['item_description']): ?>
                <div style="margin-bottom:12px">
                    <div class="text-muted">Description</div>
                    <div><?= e($activeAssignment['item_description']) ?></div>
                </div>
                <?php endif; ?>
                <div style="margin-bottom:12px">
                    <div class="text-muted">Category</div>
                    <div><?= e($activeAssignment['category'] ?: '-') ?></div>
                </div>
                <div style="margin-bottom:12px">
                    <div class="text-muted">Unit of Measure</div>
                    <div><?= e($activeAssignment['unit_of_measure']) ?></div>
                </div>
                    <div style="margin-bottom:12px">
                    <div class="text-muted">Location</div>
                    <div><?= format_location($activeAssignment['Stores'], $activeAssignment['Rack'], $activeAssignment['Level'], $activeAssignment['Bin'], $activeAssignment['zone']) ?></div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header"><h3>Quick Reference</h3></div>
            <div class="card-body">
                <a href="<?= APP_URL ?>/checker/checking_guidelines.php" class="btn btn-outline btn-block" style="width:100%;text-align:center;margin-bottom:8px">View Checking Guidelines</a>
            </div>
        </div>
    </div>
</div>

<script>
function submitAction(action) {
    var comments = document.getElementById('commentsField').value.trim();
    if (action === 'reject' && comments === '') {
        alert('Please provide a comment explaining the reason for rejection.');
        document.getElementById('commentsField').focus();
        return;
    }
    if (action === 'approve') {
        if (!confirm('Approve this count? The data will be locked for final reporting.')) {
            return;
        }
    } else {
        if (!confirm('Reject this count and send it back to the Counter for recount?')) {
            return;
        }
    }
    document.getElementById('checkerAction').value = action;
    document.getElementById('checkerForm').submit();
}
</script>

<?php else: ?>
<!-- LIST VIEW: All pending counts -->


<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>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Counter</th>
                    <th>System Qty</th>
                    <th>Counted</th>
                    <th>Variance</th>
                    <th>Method</th>
                    <th>Priority</th>
                    <th>Counted At</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($pendingCounts)): ?>
                <tr><td colspan="10" class="text-center text-muted" style="padding:40px">No counts pending review.</td></tr>
                <?php else: 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) ?> <?= e($pc['unit_of_measure']) ?></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><?= ucfirst($pc['count_method']) ?></td>
                    <td><?= priority_badge($pc['priority']) ?></td>
                    <td><small><?= time_ago($pc['counted_at']) ?></small></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; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Quick Approve Section -->
<?php if (!empty($pendingCounts)): ?>
<div class="card mt-3">
    <div class="card-header">
        <h3>Quick Actions</h3>
    </div>
    <div class="card-body">
        <p class="text-muted" style="margin-bottom:12px">Items with zero variance can be approved in bulk for faster processing.</p>
        <?php
        $zeroVariance = array_filter($pendingCounts, fn($p) => $p['counted_quantity'] == $p['system_quantity']);
        ?>
        <?php if (!empty($zeroVariance)): ?>
        <form method="POST" id="bulkApproveForm">
            <?= Csrf::field() ?>
            <input type="hidden" name="action" value="bulk_approve">
            <button type="submit" class="btn btn-success" onclick="return confirm('Approve all ' + <?= count($zeroVariance) ?> + ' items with zero variance?')">
                &#10004; Approve All Zero Variance (<?= count($zeroVariance) ?> items)
            </button>
        </form>
        <?php else: ?>
        <span class="text-muted">No items with zero variance to approve in bulk.</span>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

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