<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Validator;
use App\Models\AuditLog;
use App\Models\MarketingList;
use App\Models\PipelineStage;
use App\Models\Territory;
use App\Models\Unsubscribe;
use App\Services\ListQuery;

final class ListController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('lists');
        $page = $this->page();
        $result = MarketingList::paginate($page, 20);
        $territories = Territory::allForTenant();
        $stages = PipelineStage::allActive();
        $territoryNames = [];
        foreach ($territories as $t) {
            $territoryNames[(int) $t['id']] = (string) $t['name'];
        }
        $stageNames = [];
        foreach ($stages as $st) {
            $stageNames[(int) $st['id']] = (string) $st['name'];
        }
        $campaignCounts = MarketingList::campaignCounts();
        $rows = [];
        foreach ($result['rows'] as $r) {
            $filters = json_decode((string) ($r['filters'] ?? ''), true);
            if (!is_array($filters)) {
                $filters = [];
            }
            $r['filters_arr'] = $filters;
            $r['chips'] = ListQuery::labels($filters, $territoryNames, $stageNames);
            $r['match_count'] = count(ListQuery::contacts($filters, 500));
            $r['campaign_count'] = $campaignCounts[(int) $r['id']] ?? 0;
            $rows[] = $r;
        }
        view('marketing/lists', [
            'title' => 'Lists / Groups',
            'rows' => $rows,
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 20)),
            'territories' => $territories,
            'stages' => $stages,
            'counts' => MarketingList::boardCounts(),
            'unsubscribes' => (int) (Unsubscribe::paginate(1, 1)['total'] ?? 0),
            'engagement' => (string) (ListQuery::normalizeFilters($request->all())['engagement'] ?? ''),
            'notifications' => $this->notifications(),
        ]);
    }

    public function preview(Request $request): void
    {
        $this->requireModule('lists');
        $filters = ListQuery::normalizeFilters($request->all());
        $contacts = ListQuery::contacts($filters, 50);
        json_out(['ok' => true, 'count' => count($contacts), 'rows' => array_map(static function (array $c): array {
            return [
                'name' => trim($c['first_name'] . ' ' . $c['last_name']),
                'email' => $c['email'],
                'company' => $c['account_name'],
            ];
        }, $contacts)]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('lists');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())->required($data, ['name' => 'Name']);
        if ($v->fails()) {
            $this->fail($v);
        }
        $filters = ListQuery::normalizeFilters($data);
        $id = MarketingList::create([
            'name' => mb_substr((string) $data['name'], 0, 150),
            'filters' => json_encode($filters, JSON_UNESCAPED_UNICODE),
            'created_by' => Auth::instance()->id(),
        ]);
        AuditLog::write('list.create', 'marketing_list', $id);
        json_out(['ok' => true, 'id' => $id]);
    }
}
