<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\UserProfileModel;
use App\Models\StudyProgramModel;
use CodeIgniter\Shield\Entities\User;

class UserController extends BaseController
{
    public function index()
    {
        $filters = [
            'role'   => $this->request->getGet('role'),
            'status' => $this->request->getGet('status'),
            'search' => $this->request->getGet('q'),
        ];

        $users = model(UserProfileModel::class)->getAllWithUsers($filters);

        return view('admin/users/index', [
            'title'   => 'Pengguna',
            'users'   => $users,
            'filters' => $filters,
        ]);
    }

    public function create()
    {
        return view('admin/users/form', [
            'title'    => 'Tambah Pengguna',
            'user'     => null,
            'programs' => model(StudyProgramModel::class)->orderBy('name')->findAll(),
        ]);
    }

    public function store()
    {
        if (! $this->validate([
            'name'     => 'required|max_length[150]',
            'email'    => 'required|valid_email|max_length[254]|is_unique[auth_identities.secret]',
            'password' => 'required|min_length[8]',
            'role'     => 'required|in_list[super_admin,admin,lecturer,student]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $role = $this->request->getPost('role');
        $nim  = trim($this->request->getPost('identity_number') ?? '');

        $userProvider = auth()->getProvider();
        $entity = new User([
            'username' => ! empty($nim) ? $nim : strtolower(str_replace(' ', '.', $this->request->getPost('name'))),
            'email'    => $this->request->getPost('email'),
            'password' => $this->request->getPost('password'),
            'active'   => true,
        ]);

        $userProvider->save($entity);
        $userId = $userProvider->getInsertID();
        $newUser = $userProvider->findById($userId);
        $newUser->addGroup($role);

        model(UserProfileModel::class)->insert([
            'user_id'          => $userId,
            'name'             => $this->request->getPost('name'),
            'identity_number'  => ! empty($nim) ? $nim : null,
            'study_program_id' => $this->request->getPost('study_program_id') ?: null,
            'role'             => $role,
            'status'           => 'active',
        ]);

        return redirect()->to('/admin/users')->with('success', 'Pengguna berhasil ditambahkan.');
    }

    public function edit(int $id)
    {
        $user = model(UserProfileModel::class)->getWithUser($id);
        if (! $user) throw new \CodeIgniter\Exceptions\PageNotFoundException();

        return view('admin/users/form', [
            'title'    => 'Edit Pengguna',
            'user'     => $user,
            'programs' => model(StudyProgramModel::class)->orderBy('name')->findAll(),
        ]);
    }

    public function update(int $id)
    {
        $profile = model(UserProfileModel::class)->findByUserId($id);
        if (! $profile) throw new \CodeIgniter\Exceptions\PageNotFoundException();

        if (! $this->validate([
            'name' => 'required|max_length[150]',
            'role' => 'required|in_list[super_admin,admin,lecturer,student]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $role = $this->request->getPost('role');
        $nim  = trim($this->request->getPost('identity_number') ?? '');

        model(UserProfileModel::class)->where('user_id', $id)->set([
            'name'             => $this->request->getPost('name'),
            'identity_number'  => ! empty($nim) ? $nim : null,
            'study_program_id' => $this->request->getPost('study_program_id') ?: null,
            'role'             => $role,
        ])->update();

        // Update group
        $userProvider = auth()->getProvider();
        $user = $userProvider->findById($id);
        foreach (['super_admin','admin','lecturer','student'] as $g) {
            if ($user->inGroup($g)) $user->removeGroup($g);
        }
        $user->addGroup($role);

        // Update password if provided
        $pass = $this->request->getPost('password');
        if (! empty($pass)) {
            $userProvider->save($user->fill(['password' => $pass]));
        }

        return redirect()->to('/admin/users')->with('success', 'Pengguna berhasil diperbarui.');
    }

    public function toggleStatus(int $id)
    {
        $profile = model(UserProfileModel::class)->findByUserId($id);
        if (! $profile) throw new \CodeIgniter\Exceptions\PageNotFoundException();

        $newStatus = $profile['status'] === 'active' ? 'inactive' : 'active';
        model(UserProfileModel::class)->where('user_id', $id)->set(['status' => $newStatus])->update();

        return redirect()->back()->with('success', 'Status pengguna diperbarui.');
    }

    public function importForm()
    {
        return view('admin/users/import', ['title' => 'Import Pengguna CSV']);
    }

    public function import()
    {
        $file = $this->request->getFile('csv_file');

        if (! $file || ! $file->isValid()) {
            return redirect()->back()->with('error', 'File CSV tidak valid.');
        }

        // Validate MIME
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mime  = $finfo->file($file->getTempName());
        if (! in_array($mime, ['text/plain', 'text/csv', 'application/csv', 'application/vnd.ms-excel'], true)) {
            return redirect()->back()->with('error', 'File harus berformat CSV.');
        }

        $handle   = fopen($file->getTempName(), 'r');
        $header   = fgetcsv($handle); // skip header row
        $imported = 0;
        $skipped  = 0;

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) < 4) { $skipped++; continue; }

            [$name, $nim, $email, $role] = array_map('trim', $row);
            $role = in_array($role, ['super_admin','admin','lecturer','student']) ? $role : 'student';

            // Check if email exists
            $existing = db_connect()->table('auth_identities')
                ->where('secret', $email)->where('type', 'email_password')->get()->getRowArray();
            if ($existing) { $skipped++; continue; }

            $defaultPass = 'Pass@' . substr($nim ?: uniqid(), 0, 6);

            $userProvider = auth()->getProvider();
            $entity = new User([
                'username' => $nim ?: strtolower(str_replace(' ', '.', $name)),
                'email'    => $email,
                'password' => $defaultPass,
                'active'   => true,
            ]);
            $userProvider->save($entity);
            $uid = $userProvider->getInsertID();
            $newUser = $userProvider->findById($uid);
            $newUser->addGroup($role);

            model(UserProfileModel::class)->insert([
                'user_id'         => $uid,
                'name'            => $name,
                'identity_number' => $nim ?: null,
                'role'            => $role,
                'status'          => 'active',
            ]);

            $imported++;
        }

        fclose($handle);

        return redirect()->to('/admin/users')
            ->with('success', "$imported pengguna berhasil diimpor. $skipped dilewati.");
    }
}
