<?php
class ApplicationPeriodApiController extends Controller
{
    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw   = (int) $request->get('draw', 1);
        $start  = (int) $request->get('start', 0);
        $length = (int) $request->get('length', 25);
        $search = $request->get('search')['value'] ?? '';

        $where = "1=1";
        $params = [];
        if ($search) {
            $where .= " AND (period_name_en LIKE ? OR period_name_ar LIKE ?)";
            $params[] = "%{$search}%";
            $params[] = "%{$search}%";
        }

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM application_periods");
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM application_periods WHERE {$where}", $params);

        $rows = $db->fetchAll(
            "SELECT * FROM application_periods WHERE {$where} ORDER BY start_date DESC LIMIT " . (int)$length . " OFFSET " . (int)$start,
            $params
        );

        $data = [];
        foreach ($rows as $r) {
            $isActive = $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>';
            $actions = '<a href="/application-periods/' . $r['id'] . '/edit" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>';

            $data[] = [
                'id'          => $r['id'],
                'name'        => e(current_lang() === 'ar' ? $r['period_name_ar'] : $r['period_name_en']),
                'start_date'  => format_date($r['start_date']),
                'end_date'    => format_date($r['end_date']),
                'max'         => $r['max_applications'] ?? '-',
                'current'     => $r['current_applications'],
                'status'      => $isActive,
                'actions'     => $actions,
            ];
        }

        $this->json([
            'draw'            => $draw,
            'recordsTotal'    => $total,
            'recordsFiltered' => $filtered,
            'data'            => $data,
        ]);
    }
}