<?php

declare(strict_types=1);

namespace App\Controllers;

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

final class ServiceController extends BaseController
{
    public function index(Request $request): Response
    {
        $model = new ServiceModel();
        $types = $model->allWithBusinessLine();
        $plans = $model->plans();

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success(['types' => $types, 'plans' => $plans]);
        }

        return $this->view('services/index', [
            'title' => 'Services',
            'activeNav' => 'services',
            'breadcrumbs' => [['Home', 'dashboard'], ['CRM', 'services'], ['Services', 'services']],
            'types' => $types,
            'plans' => $plans,
            'businessLines' => Database::connection()->query('SELECT id, name FROM business_lines ORDER BY name')->fetchAll(),
        ]);
    }

    public function storeType(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'business_line_id' => 'required|integer|exists:business_lines,id',
            'name' => 'required|string|max:120',
            'default_duration_minutes' => 'required|integer',
            'default_price' => 'required|numeric',
        ]);
        $data['currency'] = 'CAD';
        $data['is_active'] = 1;

        $model = new ServiceModel();
        $id = $model->insert($data);
        ActivityLogger::record('service_type', $id, 'service_type_created', "Created service \"{$data['name']}\"", category: 'admin');

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

    public function updateType(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'business_line_id' => 'required|integer|exists:business_lines,id',
            'name' => 'required|string|max:120',
            'default_duration_minutes' => 'required|integer',
            'default_price' => 'required|numeric',
        ]);

        $id = (int) $params['id'];
        $model = new ServiceModel();
        $model->update($id, $data);
        ActivityLogger::record('service_type', $id, 'service_type_updated', 'Service type updated', category: 'admin');

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

    public function destroyType(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new ServiceModel())->update($id, ['is_active' => 0]);
        ActivityLogger::record('service_type', $id, 'service_type_deactivated', 'Service type deactivated', category: 'admin');

        return AjaxResponse::success(null, 'Service type deactivated.');
    }

    public function storePlan(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'business_line_id' => 'required|integer|exists:business_lines,id',
            'name' => 'required|string|max:120',
            'billing_frequency' => 'required|in:one_time,weekly,biweekly,monthly,annually',
            'base_price' => 'required|numeric',
        ]);

        $model = new ServiceModel();
        $id = $model->insertPlan($data);
        ActivityLogger::record('service_plan', $id, 'service_plan_created', "Created plan \"{$data['name']}\"", category: 'admin');

        return AjaxResponse::created(null, 'Service plan created.');
    }

    public function updatePlan(Request $request, array $params): Response
    {
        $data = $this->validateOrFail($request, [
            'business_line_id' => 'required|integer|exists:business_lines,id',
            'name' => 'required|string|max:120',
            'billing_frequency' => 'required|in:one_time,weekly,biweekly,monthly,annually',
            'base_price' => 'required|numeric',
        ]);

        $id = (int) $params['id'];
        (new ServiceModel())->updatePlan($id, $data);
        ActivityLogger::record('service_plan', $id, 'service_plan_updated', 'Service plan updated', category: 'admin');

        return AjaxResponse::success(null, 'Service plan updated.');
    }

    public function destroyPlan(Request $request, array $params): Response
    {
        $id = (int) $params['id'];
        (new ServiceModel())->deletePlan($id);
        ActivityLogger::record('service_plan', $id, 'service_plan_deactivated', 'Service plan deactivated', category: 'admin');

        return AjaxResponse::success(null, 'Service plan deactivated.');
    }
}
