<?php

namespace Core\App\Controllers;

use Core\App\Models\AdminProfileModel;
use Core\App\Services\UploadService;
use Core\System\Request;
use Core\System\Response;

class AdminProfileController
{
    public function index(): void
    {
        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/profile.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    public function update(): void
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $adminId = $_SESSION['admin_id'] ?? null;
        if (!$adminId) {
            Response::redirect('/admin/login');
        }

        $model = new AdminProfileModel();
        $admin = $model->findById((int) $adminId);
        if (!$admin) {
            $_SESSION['profile_error'] = __('admin.profile.not_found', 'Admin not found');
            Response::redirect('/admin/profile');
        }

        $updated = false;
        $uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');

        if (isset($_POST['username']) || !empty($_FILES['avatar']['name'])) {
            $username = isset($_POST['username']) ? trim((string) Request::input('username')) : $admin['username'];
            $email    = isset($_POST['email']) ? trim((string) Request::input('email')) : ($admin['email'] ?? '');
            $email    = $email !== '' ? $email : null;
            $phone    = isset($_POST['phone']) ? preg_replace('/[^\d+]/', '', trim((string) Request::input('phone'))) : ($admin['phone'] ?? null);
            $phone    = ($phone !== '' && $phone !== null) ? $phone : null;
            $avatar   = $admin['avatar'];

            if (!empty($_FILES['avatar']['name'])) {
                try {
                    $avatar = $uploads->storeImage($_FILES['avatar'], 'admins');
                    $uploads->deleteByWebPath($admin['avatar'] ?? null);
                } catch (\Throwable $e) {
                    $_SESSION['profile_error'] = __('admin.profile.avatar_invalid', 'Invalid avatar image');
                }
            }

            $model->updateProfile((int) $adminId, $username, $email, $avatar, $phone);
            $updated = true;
        }

        if (isset($_POST['current_password'])) {
            $current = (string) Request::input('current_password');
            $new     = (string) Request::input('new_password');
            $confirm = (string) Request::input('confirm_password');

            if (!password_verify($current, $admin['password'])) {
                $_SESSION['profile_error'] = __('admin.profile.password_wrong', 'Current password is incorrect');
            } elseif ($new !== $confirm) {
                $_SESSION['profile_error'] = __('admin.profile.password_mismatch', 'Password confirmation does not match');
            } elseif (mb_strlen($new) < 8) {
                $_SESSION['profile_error'] = __('admin.profile.password_short', 'Password must be at least 8 characters');
            } else {
                $model->updatePassword((int) $adminId, $new);
                $updated = true;
            }
        }

        if ($updated && empty($_SESSION['profile_error'])) {
            $_SESSION['profile_success'] = __('admin.profile.updated', 'Profile updated successfully');
        }

        Response::redirect('/admin/profile');
    }
}
