<?php
class SequenceController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('sequences/index', [
            'title' => lang('admin.sequences'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/sequences'], ['label' => lang('admin.sequences')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $rows = $this->db()->fetchAll("SELECT * FROM sys_sequences ORDER BY sequence_name");
        $data = [];
        foreach ($rows as $r) {
            $sample = ($r['prefix'] ?? '') . str_pad($r['current_value'] + 1, $r['pad_length'], '0', STR_PAD_LEFT) . ($r['suffix'] ?? '');
            $data[] = [
                'name' => e($r['sequence_name']),
                'prefix' => e($r['prefix'] ?? '-'),
                'current' => number_format($r['current_value']),
                'next_sample' => e($sample),
                'reset' => e($r['reset_period']),
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'actions' => '<div class="btn-group btn-group-sm"><button class="btn btn-outline-danger btn-reset-seq" data-id="' . $r['id'] . '" data-name="' . e($r['sequence_name']) . '"><i class="fas fa-undo"></i> Reset</button></div>',
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function update(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->update('sys_sequences', [
            'prefix' => $request->post('prefix'),
            'suffix' => $request->post('suffix'),
            'pad_length' => (int)$request->post('pad_length', 6),
            'is_active' => $request->post('is_active', 1) ? 1 : 0,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Sequence updated']);
    }

    public function reset(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $db = $this->db();
        $seq = $db->fetchOne("SELECT * FROM sys_sequences WHERE id = ?", [$id]);
        if (!$seq) { $this->json(['success' => false, 'message' => 'Sequence not found'], 404); return; }
        $db->update('sys_sequences', ['current_value' => $seq['min_value'] - 1, 'last_reset_date' => date('Y-m-d'), 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        $this->audit('update', 'sys_sequences', $id, 'Reset sequence: ' . $seq['sequence_name']);
        $this->json(['success' => true, 'message' => 'Sequence reset to ' . $seq['min_value']]);
    }
}