<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\M_user;

class Profile extends BaseController
{
    public function index()
    {
        $session = session()->get('login');
        $userId = $session['id'] ?? null;

        if (!$userId) {
            return redirect()->to('login')->with('errors', ['Silakan login terlebih dahulu.']);
        }

        $M_user = new M_user();
        $user = $M_user->find($userId);

        if (!$user) {
            return redirect()->back()->with('errors', ['Data user tidak ditemukan.']);
        }

        $data = [
            'user' => $user,
            'role' => $session['role'] ?? null,
        ];

        return view('profile/index', $data);
    }

    public function update()
    {
        $session = session()->get('login');
        $id = $session['id'] ?? null;

        if (!$id) {
            return redirect()->to('login')->with('errors', ['User tidak ditemukan']);
        }

        $M_user = new M_user();

        $data = [
            'nama'          => $this->request->getPost('nama'),
            'no_hp'         => $this->request->getPost('no_hp'),
            'email'         => $this->request->getPost('email'),
            'agama'         => $this->request->getPost('agama'),
            'tempat_lahir'  => $this->request->getPost('tempat_lahir'),
            'tanggal_lahir' => $this->request->getPost('tanggal_lahir'),
            'jenis_kelamin' => $this->request->getPost('jenis_kelamin'),
            'alamat'        => $this->request->getPost('alamat'),
        ];

        // Upload foto
        $photo = $this->request->getFile('photo');
        if ($photo && $photo->isValid() && !$photo->hasMoved()) {
            $newName = $photo->getRandomName();
            $photo->move('uploads/photos', $newName);
            $data['photo'] = $newName;

            // Hapus foto lama jika ada
            if (!empty($session['photo']) && file_exists('uploads/photos/' . $session['photo'])) {
                unlink('uploads/photos/' . $session['photo']);
            }
        }

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

        // Ambil ulang data user setelah update
        $updatedUser = $M_user->find($id);

        // Update data session login
        session()->set('login', [
            'id'         => $updatedUser['id'],
            'username'   => $updatedUser['username'],
            'nama'       => $updatedUser['nama'],
            'photo'      => $updatedUser['photo'] ?? null,
            'role'       => $updatedUser['role'],
            'id_guru'    => $updatedUser['id_guru'] ?? null,
            'isLoggedIn' => true,
        ]);

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

    public function create()
    {
        $session = session()->get('login');
        $userId = $session['id'] ?? null;

        $M_user = new M_user();
        $user = $M_user->find($userId);

        return view('profile/create', ['user' => $user]);
    }
}
