<?php

namespace App\Controllers\Api;

use App\Models\RoleModel;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;

class Profile extends BaseApiController
{
    public function show(): ResponseInterface
    {
        $user = $this->currentUser();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }

        return $this->ok($this->serializeUser($user));
    }

    public function update(): ResponseInterface
    {
        $user = $this->currentUser();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }

        $data = $this->request->getJSON(true);
        if (!is_array($data)) {
            $data = $this->request->getPost() ?: [];
        }

        $name = trim((string) ($data['name'] ?? ''));
        $username = trim((string) ($data['username'] ?? ''));
        $email = trim((string) ($data['email'] ?? ''));
        $address = (string) ($data['address'] ?? '');

        $errors = [];
        if ($name === '') {
            $errors['name'] = 'Name is required';
        }

        if ($username !== '' && strlen($username) < 5) {
            $errors['username'] = 'Username must be at least 5 characters';
        }

        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Invalid email';
        }

        if (empty($errors) && $username !== '') {
            $existsUsername = (new UserModel())
                ->where('username', $username)
                ->where('id !=', (int) $user->id)
                ->countAllResults() > 0;
            if ($existsUsername) {
                $errors['username'] = 'Username already taken';
            }
        }

        if (empty($errors) && $email !== '') {
            $existsEmail = (new UserModel())
                ->where('email', $email)
                ->where('id !=', (int) $user->id)
                ->countAllResults() > 0;
            if ($existsEmail) {
                $errors['email'] = 'Email already exists';
            }
        }

        if (!empty($errors)) {
            return $this->fail('Validation failed', 422, $errors);
        }

        $update = [
            'name' => $name,
            'address' => $address,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if ($username !== '') {
            $update['username'] = $username;
        }
        if ($email !== '') {
            $update['email'] = $email;
        }

        (new UserModel())->update((int) $user->id, $update);
        $fresh = (new UserModel())->getById((int) $user->id);
        if (!$fresh) {
            return $this->fail('User not found', 404);
        }

        return $this->ok($this->serializeUser($fresh));
    }

    public function picture(): ResponseInterface
    {
        $user = $this->currentUser();
        if (!$user) {
            return $this->fail('Unauthorized', 401);
        }

        $ext = uploadPublicImage('image', 'users', (string) ((int) $user->id));
        if (!$ext) {
            return $this->fail('Validation failed', 422, ['image' => 'Invalid or missing image']);
        }

        (new UserModel())->update((int) $user->id, [
            'img_type' => $ext,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        $fresh = (new UserModel())->getById((int) $user->id);
        if (!$fresh) {
            return $this->fail('User not found', 404);
        }

        return $this->ok($this->serializeUser($fresh));
    }

    private function currentUser(): ?object
    {
        if (!function_exists('is_logged') || !is_logged()) {
            return null;
        }
        if (!function_exists('logged')) {
            return null;
        }
        return logged() ?: null;
    }

    private function serializeUser(object $user): array
    {
        $role = (new RoleModel())->getById((int) ($user->role ?? 0));
        $countryId = isset($user->countryid) ? (int) $user->countryid : null;

        $imageUrl = !empty($user->img_type)
            ? urlUpload('users/' . (int) $user->id . '.' . $user->img_type, true)
            : urlUpload('users/default.png', true);

        return [
            'id' => (int) ($user->id ?? 0),
            'name' => (string) ($user->name ?? ''),
            'username' => (string) ($user->username ?? ''),
            'email' => (string) ($user->email ?? ''),
            'phone' => (string) ($user->phone ?? ''),
            'address' => (string) ($user->address ?? ''),
            'countryid' => $countryId,
            'country_id' => $countryId,
            'countryId' => $countryId,
            'role_id' => (int) ($user->role ?? 0),
            'roleId' => (int) ($user->role ?? 0),
            'role_title' => $role ? (string) $role->title : null,
            'roleTitle' => $role ? (string) $role->title : null,
            'image_url' => $imageUrl,
            'imageUrl' => $imageUrl,
            'last_login' => isset($user->last_login) ? (string) $user->last_login : null,
            'lastLogin' => isset($user->last_login) ? (string) $user->last_login : null,
            'created_at' => isset($user->created_at) ? (string) $user->created_at : null,
            'createdAt' => isset($user->created_at) ? (string) $user->created_at : null,
            'updated_at' => isset($user->updated_at) ? (string) $user->updated_at : null,
            'updatedAt' => isset($user->updated_at) ? (string) $user->updated_at : null,
        ];
    }
}

