<?php

namespace App\Controllers\Api;

use App\Libraries\AuditLogger;
use App\Libraries\ResponseHelper;
use App\Libraries\UuidHelper;
use App\Models\ChurchModel;
use App\Models\UserModel;
use App\Models\RoleModel;

class ChurchController extends BaseApiController
{
    private ChurchModel $model;

    public function initController(
        \CodeIgniter\HTTP\RequestInterface $request,
        \CodeIgniter\HTTP\ResponseInterface $response,
        \Psr\Log\LoggerInterface $logger
    ): void {
        parent::initController($request, $response, $logger);
        $this->model = new ChurchModel();

        if (!$this->ctx->isPlatformAdmin()) {
            // Return forbidden — but we can't return from initController, so we'll check in each action.
        }
    }

    private function guardPlatformAdmin()
    {
        if (!$this->ctx->isPlatformAdmin()) {
            return ResponseHelper::forbidden('Platform admin access required');
        }
        return null;
    }

    public function index()
    {
        if ($g = $this->guardPlatformAdmin()) return $g;

        $perPage = $this->getPerPage();
        $page    = (int) ($this->request->getGet('page') ?? 1);
        $offset  = ($page - 1) * $perPage;
        $total   = $this->model->where('deleted_at IS NULL')->countAllResults(false);
        $rows    = $this->model->where('deleted_at IS NULL')->findAll($perPage, $offset);

        return ResponseHelper::paginated([
            'data' => array_map([$this, 'format'], $rows),
            'meta' => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => (int) ceil($total / $perPage),
            ],
        ]);
    }

    public function create()
    {
        if ($g = $this->guardPlatformAdmin()) return $g;

        $data = $this->getJson();

        $validation = service('validation');
        $validation->setRules([
            'name'               => 'required|min_length[2]|max_length[255]',
            'email'              => 'permit_empty|valid_email',
            'admin_name'         => 'required|min_length[2]',
            'admin_email'        => 'required|valid_email',
            'admin_password'     => 'required|min_length[8]',
        ]);

        if (!$validation->run($data)) {
            return ResponseHelper::validationError($validation->getErrors());
        }

        $db = \Config\Database::connect();
        $db->transStart();

        $churchUuid = UuidHelper::generate();
        $this->model->insert([
            'uuid'      => $churchUuid,
            'name'      => $data['name'],
            'address'   => $data['address'] ?? null,
            'phone'     => $data['phone'] ?? null,
            'email'     => $data['email'] ?? null,
            'website'   => $data['website'] ?? null,
            'is_active' => 1,
        ]);
        $churchId = $this->model->getInsertID();

        // Create default super-admin role
        $roleModel = new RoleModel();
        $roleModel->setChurchId($churchId);
        $roleModel->insert([
            'uuid'      => UuidHelper::generate(),
            'church_id' => $churchId,
            'name'      => 'Super Admin',
        ]);
        $roleId = $roleModel->getInsertID();

        // Create admin user
        $userModel = new UserModel();
        $userModel->insert([
            'uuid'          => UuidHelper::generate(),
            'church_id'     => $churchId,
            'role_id'       => $roleId,
            'name'          => $data['admin_name'],
            'email'         => $data['admin_email'],
            'password_hash' => password_hash($data['admin_password'], PASSWORD_DEFAULT),
            'is_active'     => 1,
        ]);

        $db->transComplete();

        if (!$db->transStatus()) {
            return ResponseHelper::serverError('Failed to create church');
        }

        $church = $this->model->findByUuid($churchUuid);

        AuditLogger::log('church.created', 'churches', $churchUuid, null, $church, null, null);

        return ResponseHelper::created($this->format($church));
    }

    public function show(string $uuid)
    {
        if ($g = $this->guardPlatformAdmin()) return $g;

        $church = $this->model->findByUuid($uuid);
        if (!$church) {
            return ResponseHelper::notFound();
        }

        $church['branches'] = array_map([$this, 'format'], $this->model->getBranches($church['id']));

        return ResponseHelper::success($this->format($church));
    }

    public function update(string $uuid)
    {
        if ($g = $this->guardPlatformAdmin()) return $g;

        $church = $this->model->findByUuid($uuid);
        if (!$church) {
            return ResponseHelper::notFound();
        }

        $data = $this->getJson();
        $allowed = ['name', 'address', 'phone', 'email', 'website', 'logo', 'is_active'];
        $update  = array_intersect_key($data, array_flip($allowed));

        if (empty($update)) {
            return ResponseHelper::error('No valid fields to update', 422);
        }

        $old = $church;
        $this->model->update($church['id'], $update);
        $new = $this->model->findByUuid($uuid);

        AuditLogger::log('church.updated', 'churches', $uuid, $old, $new, null, null);

        return ResponseHelper::success($this->format($new));
    }

    public function branches(string $uuid)
    {
        if ($g = $this->guardPlatformAdmin()) return $g;

        $church = $this->model->findByUuid($uuid);
        if (!$church) {
            return ResponseHelper::notFound();
        }

        $branches = $this->model->getBranches($church['id']);

        return ResponseHelper::success(array_map([$this, 'format'], $branches));
    }

    private function format(array $c): array
    {
        return [
            'uuid'             => $c['uuid'],
            'name'             => $c['name'],
            'address'          => $c['address'],
            'phone'            => $c['phone'],
            'email'            => $c['email'],
            'website'          => $c['website'],
            'logo'             => $c['logo'],
            'parent_church_id' => $c['parent_church_id'],
            'is_active'        => (bool) ($c['is_active'] ?? true),
            'created_at'       => $c['created_at'],
            'branches'         => $c['branches'] ?? [],
        ];
    }
}
