<?php
class LookupController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $categories = $db->fetchAll("SELECT * FROM sys_lookup_categories ORDER BY category_name_en");
        $this->view('lookups/index', [
            'title' => lang('admin.lookups'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/lookups'], ['label' => lang('admin.lookups')]],
            'categories' => $categories,
        ]);
    }

    public function categoriesDatatable(Request $request): void
    {
        $rows = $this->db()->fetchAll("SELECT lc.*, (SELECT COUNT(*) FROM sys_lookup_values lv WHERE lv.category_id = lc.id) as value_count FROM sys_lookup_categories lc ORDER BY lc.category_name_en");
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id' => $r['id'],
                'code' => e($r['category_code']),
                'name_en' => e($r['category_name_en']),
                'name_ar' => e($r['category_name_ar']),
                'values' => $r['value_count'],
                'system' => $r['is_system'] ? '<span class="badge bg-info">System</span>' : '',
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function valuesDatatable(Request $request): void
    {
        $categoryId = (int)$request->post('category_id');
        $rows = $this->db()->fetchAll("SELECT * FROM sys_lookup_values WHERE category_id = ? ORDER BY sort_order, value_en", [$categoryId]);
        $data = [];
        foreach ($rows as $r) {
            $actions = '<div class="btn-group btn-group-sm">';
            $actions .= '<button class="btn btn-outline-primary btn-edit-value" data-id="' . $r['id'] . '" data-code="' . e($r['lookup_code']) . '" data-en="' . e($r['value_en']) . '" data-ar="' . e($r['value_ar']) . '" data-sort="' . $r['sort_order'] . '" data-active="' . $r['is_active'] . '"><i class="fas fa-edit"></i></button>';
            $actions .= '<button class="btn btn-outline-danger btn-delete-value" data-id="' . $r['id'] . '"><i class="fas fa-trash"></i></button>';
            $actions .= '</div>';
            $data[] = [
                'code' => e($r['lookup_code']),
                'value_en' => e($r['value_en']),
                'value_ar' => e($r['value_ar']),
                'sort' => $r['sort_order'],
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'actions' => $actions,
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function storeValue(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->insert('sys_lookup_values', [
            'category_id' => (int)$request->post('category_id'),
            'lookup_code' => $request->post('lookup_code'),
            'value_en' => $request->post('value_en'),
            'value_ar' => $request->post('value_ar'),
            'sort_order' => (int)$request->post('sort_order', 0),
            'is_active' => 1,
        ]);
        $this->json(['success' => true, 'message' => 'Value created']);
    }

    public function updateValue(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_lookup_values', [
            'value_en' => $request->post('value_en'),
            'value_ar' => $request->post('value_ar'),
            'sort_order' => (int)$request->post('sort_order', 0),
            'is_active' => $request->post('is_active', 1) ? 1 : 0,
        ], 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Value updated']);
    }

    public function deleteValue(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->delete('sys_lookup_values', 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Value deleted']);
    }
}