<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\LeadSourceModel;
use App\Services\ActivityLogger;

final class LeadSourceController extends BaseController
{
    public function index(Request $request): Response
    {
        $rows = (new LeadSourceModel())->allWithLeadCounts();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($rows);
        }

        return $this->view('lead-sources/index', [
            'title' => 'Lead Sources',
            'activeNav' => 'lead-sources',
            'breadcrumbs' => [['Home', 'dashboard'], ['CRM', 'leads'], ['Lead Sources', 'lead-sources']],
            'rows' => $rows,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, ['name' => 'required|string|max:100']);
        $data['slug'] = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '_', $data['name']), '_'));
        $data['is_active'] = 1;
        $data['sort_order'] = 99;

        $model = new LeadSourceModel();
        $id = $model->insert($data);
        ActivityLogger::record('lead_source', $id, 'lead_source_created', "Created source \"{$data['name']}\"", category: 'admin');

        return AjaxResponse::created($model->find($id), 'Lead source created.');
    }

    public function update(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, ['name' => 'required|string|max:100']);
        $id = (int) $params['id'];

        $model = new LeadSourceModel();
        $model->update($id, $data);
        ActivityLogger::record('lead_source', $id, 'lead_source_updated', 'Lead source updated', category: 'admin');

        return AjaxResponse::success($model->find($id), 'Lead source updated.');
    }

    public function destroy(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new LeadSourceModel())->update($id, ['is_active' => 0]);
        ActivityLogger::record('lead_source', $id, 'lead_source_deactivated', 'Lead source deactivated', category: 'admin');

        return AjaxResponse::success(null, 'Lead source deactivated.');
    }
}
