<?php

namespace App\Controllers;

use App\Models\CustomerModel;
use App\Models\PegawaiModel;
use App\Models\UserModel;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Controller;
use CodeIgniter\Shield\Models\UserIdentityModel;

class AuthController extends Controller
{
    public function register()
    {
        helper(['form']);

        if ($this->request->getMethod() == 'POST') {
            // Aturan validasi
            $rules = [
                'nama'              => 'required|min_length[3]|max_length[255]',
                'username'          => 'required|min_length[3]|max_length[30]|is_unique[users.username]',
                'password'          => 'required|min_length[8]|max_length[255]',
                'password_confirm'  => 'required|matches[password]',
                'telepon'             => 'required|min_length[10]|max_length[20]|numeric',
            ];

            if (!$this->validate($rules)) {
                return view('auth/register', [
                    'title'      => 'Register',
                    'validation' => $this->validator,
                ]);
            }

            $CustomersModel = new \App\Models\CustomerModel();

            $CustomersModel->insert([
                'nama' => $this->request->getPost('nama'),
                'username' => $this->request->getPost('username'),
                'telepon'     => $this->request->getPost('telepon')
            ]);
            $NewCustomerId = $CustomersModel->getInsertID();

            $usersModel = new \App\Models\UserModel();

            $usersModel->insert([
                'username' => $this->request->getPost('username'),
                'name' => $this->request->getPost('nama'),
                'user_id'    => $NewCustomerId,
                'role'      => 'customer',
                'image'     => 'assets/img/avatar4.png',
            ]);
            $newUserId = $usersModel->getInsertID();

            $identityModel = new UserIdentityModel();

            $identityModel->insert([
                'user_id' => $newUserId,
                'type' => 'email_password',
                'secret' => $this->request->getPost('username'),
                'secret2' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            if ($identityModel->affectedRows() > 0) {
                session()->setFlashdata('success', 'Registrasi berhasil! Silakan login.');
                return redirect()->to('/login');
            }

            session()->setFlashdata('error', 'Terjadi kesalahan, coba lagi.');
        }

        return view('auth/register', ['title' => 'Register']);
    }

    public function login()
    {
        $data['title'] = 'Login';
        return view('auth/login', $data);
    }

    public function attemptLogin()
    {
        helper('auth');

        if (auth()->loggedIn()) {
            auth()->logout();
        }

        $username = $this->request->getPost('username'); // atau 'email'
        $password = $this->request->getPost('password');

        if (empty($username) || empty($password)) {
            return redirect()->back()->withInput()->with('error', 'Username dan Password wajib diisi.');
        }

        $credentials = [
            'username' => $username, // atau 'email' jika memakai email
            'password' => $password,
        ];

        $result = auth()->attempt($credentials);

        if (!$result->isOK()) {
            return redirect()->back()->withInput()->with('error', $result->reason());
        }

        return redirect()->to('dashboard')->with('success', 'Selamat datang!');
    }

    public function edit_profile()
    {
        if (auth()->user()->role == "customer") {
            $userModel = new CustomerModel();
            $data = $userModel->find(auth()->user()->user_id);
        } else {
            $userModel = new PegawaiModel();
            $data = $userModel->find(auth()->user()->user_id);
        }
        return view('edit-profile', [
            'title' => 'Edit Profile',
            'data' => $data
        ]);
    }

    public function edit_profile_proses($id)
    {
        // Cek IDOR: Pastikan ID pada URL cocok dengan ID pengguna yang sedang login.
        // Ini adalah langkah terpenting untuk mencegah manipulasi data pengguna lain.
        if ($id != auth()->user()->user_id) {
            return redirect()->back()->with('error', 'Anda tidak diizinkan untuk mengubah data pengguna ini.');
        }

        $userAuth = auth()->user();
        $request = $this->request;

        // Tentukan model berdasarkan peran pengguna
        $model = ($userAuth->role === "customer") ? new CustomerModel() : new PegawaiModel();
        $user = $model->find($userAuth->user_id);

        // Jika pengguna tidak ditemukan, kembalikan pesan error
        if (!$user) {
            return redirect()->back()->with('error', 'Pengguna tidak ditemukan.');
        }

        // Tentukan aturan validasi
        $rules = [
            'nama'             => 'required|min_length[3]|max_length[255]',
            'username'         => 'required|min_length[3]|max_length[30]|is_unique[users.username, id,' . $userAuth->id . ']',
            'password'         => 'min_length[8]|max_length[255]|permit_empty',
            'password_confirm' => 'matches[password]|permit_empty',
        ];

        // Jika peran 'customer', tambahkan aturan validasi khusus
        if ($userAuth->role === "customer") {
            $rules['telepon'] = 'required|min_length[10]|max_length[20]|numeric';
        }

        // Jalankan validasi
        if (!$this->validate($rules)) {
            return view('edit-profile', [
                'title'      => 'Edit Profile',
                'data'       => $user,
                'validation' => $this->validator
            ]);
        }

        // Siapkan data update
        $dataUpdate = [
            'name'     => $request->getPost('nama'),
            'username' => $request->getPost('username'),
        ];

        $dataUpdateProfile = ($userAuth->role === "customer") ?
            [
                'nama'   => $request->getPost('nama'),
                'telepon'  => $request->getPost('telepon'),
            ] :
            [
                'nama' => $request->getPost('nama'),
            ];

        // Perbarui data pengguna utama
        $userModel = new UserModel();
        $userModel->update($userAuth->id, $dataUpdate);

        // Perbarui data profil (customer atau pegawai)
        $model->update($userAuth->user_id, $dataUpdateProfile);

        // Jika password diisi, perbarui password
        $password = $request->getPost('password');
        if ($password != null && trim($password) != '') {
            $authModel = new UserIdentityModel();
            $authIdentity = $authModel->where('user_id', $userAuth->id)->first();
            if ($authIdentity) {
                $authModel->update($authIdentity->id, [
                    'secret2' => password_hash($password, PASSWORD_DEFAULT),
                ]);
            }
        }

        return redirect()->to('edit_profile')->with('success', 'Edit Profile Berhasil');
    }

    public function logout()
    {
        auth()->logout();
        return redirect()->to('/login');
    }
}
