<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Profil extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();
        $id = session()->get('id');
        $user = $userModel->find($id);

        $data = [
            'title' => 'Profil Saya',
            'user' => $user,
            'validation' => \Config\Services::validation()
        ];

        return view('admin/profil_saya', $data);
    }

    public function update()
    {
        $userModel = new UserModel();
        $id = session()->get('id');
        $user = $userModel->find($id);

        if (!$this->validate([
            'nama_lengkap' => 'required',
            'username' => 'required|is_unique[users.username,id,' . $id . ']',
            'foto' => 'max_size[foto,2048]|is_image[foto]|mime_in[foto,image/jpg,image/jpeg,image/png]'
        ])) {
            return redirect()->back()->withInput();
        }

        $data = [
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'username' => $this->request->getPost('username'),
        ];

        $password = $this->request->getPost('password');
        if (!empty($password)) {
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        $fileFoto = $this->request->getFile('foto');
        if ($fileFoto && $fileFoto->isValid() && !$fileFoto->hasMoved()) {
            $oldFoto = $user['foto'];
            if ($oldFoto != 'default.jpg' && file_exists('uploads/foto_profil/' . $oldFoto)) {
                unlink('uploads/foto_profil/' . $oldFoto);
            }
            
            $namaFoto = $fileFoto->getRandomName();
            $fileFoto->move('uploads/foto_profil', $namaFoto);
            $data['foto'] = $namaFoto;
        }

        $userModel->update($id, $data);

        $sessionUpdate = [
            'nama' => $data['nama_lengkap'],
            'username' => $data['username']
        ];
        
        if (isset($data['foto'])) {
            $sessionUpdate['foto'] = $data['foto'];
        }

        session()->set($sessionUpdate);

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