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

$pageTitle = 'Session Management';
$db = Database::getInstance();

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

    if ($action === 'create') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $startDate = $_POST['start_date'] ?? null;
        $endDate = $_POST['end_date'] ?? null;

        if (empty($name)) {
            set_error('Session name is required.');
        } else {
            $db->insert('sessions', [
                'name' => $name,
                'description' => $description,
                'start_date' => $startDate ?: null,
                'end_date' => $endDate ?: null,
                'created_by' => SessionManager::getUserId(),
                'status' => 'draft',
            ]);
            log_action(SessionManager::getUserId(), 'create', 'sessions', $db->fetchColumn("SELECT LAST_INSERT_ID()"), ['name' => $name]);
            set_success('Session created successfully.');
        }
    } elseif ($action === 'update_status') {
        $sessionId = (int) ($_POST['session_id'] ?? 0);
        $newStatus = $_POST['new_status'] ?? '';
        $validStatuses = ['draft', 'open', 'in_progress', 'completed', 'cancelled'];

        if ($sessionId && in_array($newStatus, $validStatuses)) {
            $db->update('sessions', ['status' => $newStatus], 'id = ?', [$sessionId]);
            log_action(SessionManager::getUserId(), 'update', 'sessions', $sessionId, ['status' => $newStatus]);
            set_success("Session status updated to '$newStatus'.");
        }
    } elseif ($action === 'delete') {
        $sessionId = (int) ($_POST['session_id'] ?? 0);
        if ($sessionId) {
            $db->delete('sessions', 'id = ?', [$sessionId]);
            log_action(SessionManager::getUserId(), 'delete', 'sessions', $sessionId);
            set_success('Session deleted.');
        }
    }

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

$statusFilter = $_GET['status'] ?? '';
$page = max(1, (int) ($_GET['page'] ?? 1));
$where = '1=1';
$params = [];
if ($statusFilter) {
    $where .= ' AND s.status = ?';
    $params[] = $statusFilter;
}

$total = $db->fetchColumn("SELECT COUNT(*) FROM sessions s WHERE $where", $params);
$pagination = new Pagination($total, ITEMS_PER_PAGE, $page);
$sessions = $db->fetchAll("
    SELECT s.*, u.full_name as creator_name,
        (SELECT COUNT(*) FROM assignments a WHERE a.session_id = s.id) as assignment_count,
        (SELECT COUNT(*) FROM assignments a WHERE a.session_id = s.id AND a.status = 'approved') as approved_count
    FROM sessions s
    LEFT JOIN users u ON s.created_by = u.id
    WHERE $where
    ORDER BY s.created_at DESC
    LIMIT {$pagination->getLimit()} OFFSET {$pagination->getOffset()}
", $params);

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

<!-- Create Session Modal -->
<div class="modal-overlay" id="createModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Create New Session</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">Session Name *</label>
                    <input type="text" name="name" class="form-control" required placeholder="e.g., Q1 2026 Stocktake">
                </div>
                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="Optional description..."></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Start Date</label>
                        <input type="datetime-local" name="start_date" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">End Date</label>
                        <input type="datetime-local" name="end_date" class="form-control">
                    </div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Create Session</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('createModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="toolbar">
    <div class="toolbar-left" style="display:flex;gap:10px">
        <button class="btn btn-primary" onclick="document.getElementById('createModal').style.display='flex'">+ New Session</button>
    </div>
    <form method="GET" class="toolbar-right" style="display:flex;gap:10px">
        <select name="status" class="form-control" style="width:auto" onchange="this.form.submit()">
            <option value="">All Status</option>
            <?php foreach (['draft','open','in_progress','completed','cancelled'] as $s): ?>
            <option value="<?= $s ?>" <?= $statusFilter === $s ? 'selected' : '' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</div>

<?php if (empty($sessions)): ?>
<div class="card">
    <div class="empty-state">
        <div class="icon">&#128197;</div>
        <h3>No Sessions Found</h3>
        <p>Create your first inventory counting session to get started.</p>
        <button class="btn btn-primary" onclick="document.getElementById('createModal').style.display='flex'">+ New Session</button>
    </div>
</div>
<?php else: ?>
<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Session Name</th>
                    <th>Status</th>
                    <th>Assignments</th>
                    <th>Approved</th>
                    <th>Start Date</th>
                    <th>End Date</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($sessions as $session): ?>
                <tr>
                    <td><strong><?= e($session['name']) ?></strong>
                        <?php if ($session['description']): ?>
                        <br><small class="text-muted"><?= truncate($session['description'], 60) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><?= status_badge($session['status']) ?></td>
                    <td><?= $session['assignment_count'] ?></td>
                    <td><?= $session['approved_count'] ?> / <?= $session['assignment_count'] ?></td>
                    <td><?= format_datetime($session['start_date']) ?></td>
                    <td><?= format_datetime($session['end_date']) ?></td>
                    <td><?= e($session['creator_name'] ?? '') ?></td>
                    <td>
                        <div class="table-actions">
                            <!-- Status change dropdown -->
                            <form method="POST" style="display:inline">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="session_id" value="<?= $session['id'] ?>">
                                <input type="hidden" name="action" value="update_status">
                                <select name="new_status" class="form-control" style="width:auto;font-size:0.8rem;padding:4px 8px" onchange="if(confirm('Change status?'))this.form.submit()">
                                    <?php foreach (['draft','open','in_progress','completed','cancelled'] as $s): ?>
                                    <option value="<?= $s ?>" <?= $session['status']===$s?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </form>
                            <form method="POST" style="display:inline" onsubmit="return confirm('Delete this session?')">
                                <?= Csrf::field() ?>
                                <input type="hidden" name="session_id" value="<?= $session['id'] ?>">
                                <input type="hidden" name="action" value="delete">
                                <button type="submit" class="btn btn-sm btn-danger" title="Delete">&#128465;</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination->getTotalPages() > 1): ?>
    <div class="card-footer"><?= $pagination->render(get_current_url()) ?></div>
    <?php endif; ?>
</div>
<?php endif; ?>

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