<?php

namespace App\Controllers\Api;

use App\Libraries\AuditLogger;
use App\Libraries\ResponseHelper;
use App\Libraries\UuidHelper;
use App\Models\AppSettingModel;
use App\Models\FinanceCategoryModel;
use App\Models\PermissionModel;
use App\Models\RoleModel;
use App\Models\RolePermissionModel;

class SettingController extends BaseApiController
{
    public function index()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $model    = $this->scopedModel(new AppSettingModel());
        $settings = $model->getAll($this->churchId());

        return ResponseHelper::success($settings);
    }

    public function update()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $data  = $this->getJson();
        $model = new AppSettingModel();

        foreach ($data as $key => $value) {
            $model->setKey($this->churchId(), (string) $key, (string) $value);
        }

        AuditLogger::log('settings.updated', 'app_settings', '', null, $data);

        return ResponseHelper::success(null);
    }

    public function roles()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $roleModel = $this->scopedModel(new RoleModel());
        $roles     = $roleModel->getRolesWithPermissions($this->churchId());

        return ResponseHelper::success($roles);
    }

    public function updateRolePermissions(int $roleId)
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $roleModel = $this->scopedModel(new RoleModel());
        $role      = $roleModel->where('id', $roleId)->first();

        if (!$role) return ResponseHelper::notFound('Role not found');

        $data        = $this->getJson();
        $permissions = $data['permissions'] ?? [];

        $rpModel   = new RolePermissionModel();
        $permModel = new PermissionModel();

        $rpModel->where('role_id', $roleId)->delete();

        foreach ($permissions as $permName) {
            $perm = $permModel->where('name', $permName)->first();
            if (!$perm) continue;

            $rpModel->insert([
                'role_id'       => $roleId,
                'permission_id' => $perm['id'],
            ]);
        }

        AuditLogger::log('role.permissions_updated', 'role_permissions', (string) $roleId, null, $permissions);

        return ResponseHelper::success(null);
    }

    public function categories()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $income  = $this->scopedModel(new FinanceCategoryModel())->where('type', 'income')->findAll();
        $expense = $this->scopedModel(new FinanceCategoryModel())->where('type', 'expense')->findAll();

        return ResponseHelper::success([
            'income'  => array_map(fn($c) => ['uuid' => $c['uuid'], 'name' => $c['name']], $income),
            'expense' => array_map(fn($c) => ['uuid' => $c['uuid'], 'name' => $c['name']], $expense),
        ]);
    }

    public function updateCategories()
    {
        if ($err = $this->requirePermission('system_settings')) return $err;

        $data     = $this->getJson();
        $catModel = new FinanceCategoryModel();

        $db = \Config\Database::connect();
        $db->table('finance_categories')
           ->where('church_id', $this->churchId())
           ->delete();

        foreach (['income', 'expense'] as $type) {
            foreach (($data[$type] ?? []) as $name) {
                $catModel->insert([
                    'uuid'      => UuidHelper::generate(),
                    'church_id' => $this->churchId(),
                    'name'      => $name,
                    'type'      => $type,
                ]);
            }
        }

        AuditLogger::log('settings.categories_updated', 'finance_categories', '', null, $data);

        return ResponseHelper::success(null);
    }
}
