<?php
/**
 * Admin - Counting Instructions
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
admin_only();

$pageTitle = 'Counting Instructions';
$db = Database::getInstance();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $db->insert('counting_instructions', [
            'title' => trim($_POST['title'] ?? ''),
            'content' => trim($_POST['content'] ?? ''),
            'session_id' => (int)($_POST['session_id'] ?? 0) ?: null,
            'status' => $_POST['status'] ?? 'active',
            'created_by' => SessionManager::getUserId(),
        ]);
        set_success('Instruction created.');
    } elseif ($action === 'update') {
        $id = (int)($_POST['instruction_id'] ?? 0);
        $db->update('counting_instructions', [
            'title' => trim($_POST['title'] ?? ''),
            'content' => trim($_POST['content'] ?? ''),
            'session_id' => (int)($_POST['session_id'] ?? 0) ?: null,
            'status' => $_POST['status'] ?? 'active',
        ], 'id = ?', [$id]);
        set_success('Instruction updated.');
    } elseif ($action === 'delete') {
        $db->delete('counting_instructions', 'id = ?', [(int)($_POST['instruction_id'] ?? 0)]);
        set_success('Instruction deleted.');
    }

    redirect(APP_URL . '/admin/counting_instructions.php');
}

$instructions = $db->fetchAll("
    SELECT ci.*, u.full_name as creator_name, s.name as session_name
    FROM counting_instructions ci
    LEFT JOIN users u ON ci.created_by = u.id
    LEFT JOIN sessions s ON ci.session_id = s.id
    ORDER BY ci.created_at DESC
");
$sessions = $db->fetchAll("SELECT id, name FROM sessions ORDER BY name");

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

<div class="toolbar">
    <button class="btn btn-primary" onclick="document.getElementById('createModal').style.display='flex'">+ Add Instruction</button>
</div>

<!-- Create Modal -->
<div class="modal-overlay" id="createModal">
    <div class="modal" style="max-width:700px">
        <div class="modal-header">
            <h3>New Instruction</h3>
            <button class="modal-close" onclick="document.getElementById('createModal').style.display='none'">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="create">
                <div class="form-group">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" class="form-control" required placeholder="Instruction title">
                </div>
                <div class="form-group">
                    <label class="form-label">Content *</label>
                    <textarea name="content" class="form-control" rows="8" required placeholder="Detailed instructions for counters..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Session (Optional)</label>
                        <select name="session_id" class="form-control">
                            <option value="">General (All Sessions)</option>
                            <?php foreach ($sessions as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Create</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('createModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if (empty($instructions)): ?>
<div class="card">
    <div class="empty-state">
        <div class="icon">&#128221;</div>
        <h3>No Instructions</h3>
        <p>Create counting instructions for your team.</p>
    </div>
</div>
<?php else: foreach ($instructions as $inst): ?>
<div class="card mb-2">
    <div class="card-header">
        <div>
            <h3><?= e($inst['title']) ?></h3>
            <small class="text-muted">
                <?= $inst['session_name'] ? 'Session: ' . e($inst['session_name']) : 'General' ?> |
                By <?= e($inst['creator_name'] ?? '') ?> |
                <?= format_date($inst['created_at']) ?>
            </small>
        </div>
        <div class="d-flex gap-1 align-center">
            <?= status_badge($inst['status']) ?>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete?')">
                <?= Csrf::field() ?>
                <input type="hidden" name="instruction_id" value="<?= $inst['id'] ?>">
                <input type="hidden" name="action" value="delete">
                <button type="submit" class="btn btn-sm btn-danger">&#128465;</button>
            </form>
        </div>
    </div>
    <div class="card-body">
        <div style="white-space:pre-wrap;line-height:1.7"><?= nl2br(e($inst['content'])) ?></div>
    </div>
</div>
<?php endforeach; endif; ?>

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