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

    public function datatable(Request $request): void
    {
        $rows = $this->db()->fetchAll("SELECT p.*, (SELECT COUNT(*) FROM sys_form_number_issued fi WHERE fi.pool_id = p.id) as issued_count FROM sys_form_number_pools p ORDER BY p.id");
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'name' => e($r['pool_name']),
                'type' => e($r['form_type']),
                'range' => number_format($r['starting_number']) . ' - ' . number_format($r['ending_number']),
                'current' => number_format($r['current_number']),
                'issued' => $r['issued_count'],
                'remaining' => number_format($r['ending_number'] - $r['current_number']),
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'actions' => '<button class="btn btn-sm btn-outline-primary btn-issue-form" data-id="' . $r['id'] . '"><i class="fas fa-plus"></i> Issue</button>',
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->insert('sys_form_number_pools', [
            'pool_name' => $request->post('pool_name'),
            'pool_name_ar' => $request->post('pool_name_ar', ''),
            'form_type' => $request->post('form_type'),
            'prefix' => $request->post('prefix'),
            'starting_number' => (int)$request->post('starting_number', 1),
            'ending_number' => (int)$request->post('ending_number'),
            'current_number' => (int)$request->post('starting_number', 1) - 1,
            'is_active' => 1,
            'created_by' => Auth::id(),
        ]);
        $this->json(['success' => true, 'message' => 'Pool created']);
    }

    public function issue(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();
        $pool = $db->fetchOne("SELECT * FROM sys_form_number_pools WHERE id = ? AND is_active = 1", [$id]);
        if (!$pool) { $this->json(['success' => false, 'message' => 'Pool not found'], 404); return; }
        $next = $pool['current_number'] + 1;
        if ($next > $pool['ending_number']) { $this->json(['success' => false, 'message' => 'Pool exhausted'], 400); return; }

        $formNumber = ($pool['prefix'] ?? '') . str_pad($next, 6, '0', STR_PAD_LEFT);
        $db->update('sys_form_number_pools', ['current_number' => $next, 'updated_at' => date('Y-m-d H:i:s')], 'id = ?', [$id]);
        $db->insert('sys_form_number_issued', [
            'pool_id' => $id,
            'form_number' => $formNumber,
            'issued_to_user' => Auth::id(),
            'issued_at' => date('Y-m-d H:i:s'),
            'status' => 'issued',
        ]);
        $this->json(['success' => true, 'message' => 'Issued: ' . $formNumber, 'form_number' => $formNumber]);
    }
}