<?php
class DataQualityController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $stats = [
            'total_rules' => (int)$db->fetchColumn("SELECT COUNT(*) FROM data_quality_rules WHERE is_active = 1"),
            'open_issues' => (int)$db->fetchColumn("SELECT COUNT(*) FROM data_quality_issues WHERE status = 'open'"),
            'critical_issues' => (int)$db->fetchColumn("SELECT COUNT(*) FROM data_quality_issues WHERE status = 'open' AND severity = 'critical'"),
            'last_scan' => $db->fetchOne("SELECT * FROM data_quality_scan_runs ORDER BY started_at DESC LIMIT 1"),
        ];
        $this->view('data-quality/index', [
            'title' => lang('admin.data_quality'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/data-quality'], ['label' => lang('admin.data_quality')]],
            'stats' => $stats,
        ]);
    }

    public function rulesDatatable(Request $request): void
    {
        $db = $this->db();
        $rows = $db->fetchAll("SELECT * FROM data_quality_rules ORDER BY entity_type, rule_code");
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'code' => e($r['rule_code']),
                'name' => e($r['rule_name_en']),
                'entity' => e($r['entity_type']),
                'type' => e($r['rule_type']),
                'severity' => status_badge($r['severity']),
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Disabled</span>',
            ];
        }
        $this->json(['draw' => (int)$request->post('draw', 1), 'recordsTotal' => count($data), 'recordsFiltered' => count($data), 'data' => $data]);
    }

    public function issuesDatatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->post('draw', 1);
        $start = (int)$request->post('start', 0);
        $length = (int)$request->post('length', 25);

        $where = "1=1";
        $params = [];
        $statusFilter = $request->post('status_filter', 'open');
        if ($statusFilter) { $where .= " AND dqi.status = ?"; $params[] = $statusFilter; }
        $severityFilter = $request->post('severity_filter');
        if ($severityFilter) { $where .= " AND dqi.severity = ?"; $params[] = $severityFilter; }

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM data_quality_issues dqi WHERE {$where}", $params);
        $rows = $db->fetchAll(
            "SELECT dqi.*, dqr.rule_name_en, dqr.rule_code FROM data_quality_issues dqi JOIN data_quality_rules dqr ON dqi.rule_id = dqr.id WHERE {$where} ORDER BY dqi.detected_at DESC LIMIT {$length} OFFSET {$start}", $params
        );

        $data = [];
        foreach ($rows as $r) {
            $actions = '<div class="btn-group btn-group-sm">';
            if ($r['status'] === 'open') {
                $actions .= '<button class="btn btn-outline-success btn-issue-action" data-id="' . $r['id'] . '" data-action="fixed"><i class="fas fa-check"></i></button>';
                $actions .= '<button class="btn btn-outline-warning btn-issue-action" data-id="' . $r['id'] . '" data-action="acknowledged"><i class="fas fa-eye"></i></button>';
                $actions .= '<button class="btn btn-outline-secondary btn-issue-action" data-id="' . $r['id'] . '" data-action="ignored"><i class="fas fa-times"></i></button>';
            }
            $actions .= '</div>';
            $data[] = [
                'rule' => e($r['rule_name_en']),
                'entity' => e($r['entity_type']) . ' #' . $r['entity_id'],
                'field' => e($r['field_name'] ?? '-'),
                'issue' => e(str_limit($r['issue_description'], 60)),
                'severity' => status_badge($r['severity']),
                'status' => status_badge($r['status']),
                'detected' => format_datetime($r['detected_at']),
                'actions' => $actions,
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $total, 'data' => $data]);
    }

    public function issueAction(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $action = $request->post('action');
        $validActions = ['fixed', 'acknowledged', 'ignored', 'false_positive'];
        if (!in_array($action, $validActions)) { $this->json(['success' => false, 'message' => 'Invalid action'], 400); return; }

        $data = ['status' => $action];
        if ($action === 'fixed') { $data['fixed_at'] = date('Y-m-d H:i:s'); $data['fixed_by'] = Auth::id(); $data['fix_method'] = 'manual'; }
        $this->db()->update('data_quality_issues', $data, 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Issue updated']);
    }

    public function scan(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $db = $this->db();
        $scanId = $db->insert('data_quality_scan_runs', [
            'scan_type' => 'full',
            'started_at' => date('Y-m-d H:i:s'),
            'status' => 'running',
            'triggered_by' => Auth::id(),
        ]);

        $rules = $db->fetchAll("SELECT * FROM data_quality_rules WHERE is_active = 1");
        $issuesFound = 0;
        $rulesChecked = count($rules);
        $recordsScanned = 0;

        foreach ($rules as $rule) {
            if ($rule['entity_type'] === 'member' && $rule['rule_type'] === 'required') {
                $field = $rule['field_name'];
                if ($field) {
                    $missing = $db->fetchAll(
                        "SELECT id FROM members WHERE is_deleted = 0 AND status = 'active' AND ({$field} IS NULL OR {$field} = '')"
                    );
                    $recordsScanned += (int)$db->fetchColumn("SELECT COUNT(*) FROM members WHERE is_deleted = 0 AND status = 'active'");
                    foreach ($missing as $m) {
                        $exists = $db->fetchColumn("SELECT COUNT(*) FROM data_quality_issues WHERE rule_id = ? AND entity_type = 'member' AND entity_id = ? AND status = 'open'", [$rule['id'], $m['id']]);
                        if (!$exists) {
                            $db->insert('data_quality_issues', [
                                'rule_id' => $rule['id'],
                                'entity_type' => 'member',
                                'entity_id' => $m['id'],
                                'field_name' => $field,
                                'issue_description' => $rule['rule_name_en'] . ' - Missing ' . $field,
                                'severity' => $rule['severity'],
                                'status' => 'open',
                                'detected_at' => date('Y-m-d H:i:s'),
                            ]);
                            $issuesFound++;
                        }
                    }
                }
            }
        }

        $db->update('data_quality_scan_runs', [
            'completed_at' => date('Y-m-d H:i:s'),
            'rules_checked' => $rulesChecked,
            'records_scanned' => $recordsScanned,
            'issues_found' => $issuesFound,
            'status' => 'completed',
        ], 'id = ?', [$scanId]);

        $this->audit('execute', 'data_quality_scan_runs', $scanId, "Data quality scan: {$issuesFound} issues found");
        $this->json(['success' => true, 'message' => "Scan complete. {$issuesFound} issues found."]);
    }

    public function storeRule(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $id = $this->db()->insert('data_quality_rules', [
            'rule_code' => $request->post('rule_code'),
            'rule_name_en' => $request->post('rule_name_en'),
            'entity_type' => $request->post('entity_type'),
            'field_name' => $request->post('field_name'),
            'rule_type' => $request->post('rule_type'),
            'severity' => $request->post('severity', 'warning'),
            'is_active' => 1,
        ]);
        $this->json(['success' => true, 'message' => 'Rule created']);
    }

    public function updateRule(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('data_quality_rules', [
            'rule_name_en' => $request->post('rule_name_en'),
            'severity' => $request->post('severity'),
            'is_active' => $request->post('is_active', 1) ? 1 : 0,
        ], 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Rule updated']);
    }
}