<?php
namespace App\Controllers\Frontend;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\EmailChangeRequestModel;
use App\Libraries\EmailService;

class ProfileController extends BaseController
{
    /**
     * Menampilkan halaman utama profil dengan data pengguna.
     */
    public function index()
    {
        $userModel = new UserModel();
        $data['user'] = $userModel->find(session()->get('user_id'));
        return view('frontend/profile/index', $data);
    }

    /**
     * Memproses update untuk detail dasar: Nama, Telepon, KTA.
     */
    public function updateDetails()
    {
        $userId = session()->get('user_id');
        $rules = [
            'name' => 'required|alpha_space|min_length[3]|max_length[255]',
            'phone_number' => "required|regex_match[/^\+[1-9]\d{1,14}$/]|is_unique[users.phone_number,id,{$userId}]",
            'kta_number' => "permit_empty|validate_kta_and_birthdate[birth_date]",
            'birth_date' => 'permit_empty|valid_date'
        ];

        if (!$this->validate($rules)) {
            return redirect()->to(route_to('profile.show'))->withInput()->with('errors', $this->validator->getErrors());
        }

        $userModel = new UserModel();
        $data = [
            'name' => $this->request->getPost('name'),
            'phone_number' => $this->request->getPost('phone_number'),
            'kta_number' => $this->request->getPost('kta_number'),
            'birth_date' => $this->request->getPost('birth_date'),
        ];
        
        $userModel->update($userId, $data);

        if ($data['name'] !== session()->get('user_name')) {
            session()->set('user_name', $data['name']);
        }

        return redirect()->to(route_to('profile.show'))->with('success', lang('Profile.successDetails'));
    }

    /**
     * Memproses perubahan password.
     */
    public function updatePassword()
    {
        $userId = session()->get('user_id');
        $rules = [
            'current_password' => 'required',
            'new_password' => 'required|min_length[8]',
            'confirm_new_password' => 'required|matches[new_password]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->to(route_to('profile.show'))->withInput()->with('errors', $this->validator->getErrors());
        }

        $userModel = new UserModel();
        $user = $userModel->find($userId);

        if (!password_verify($this->request->getPost('current_password'), $user->password)) {
            return redirect()->to(route_to('profile.show'))->with('error', lang('Profile.errorCurrentPass'));
        }

        $userModel->update($userId, ['password' => $this->request->getPost('new_password')]);
        
        return redirect()->to(route_to('profile.show'))->with('success', lang('Profile.successPassChange'));
    }

    /**
     * Memulai proses permintaan perubahan email.
     */
    public function requestEmailChange()
    {
        $userId = session()->get('user_id');
        $newEmail = $this->request->getPost('new_email');
        
        $rules = [ 'new_email' => "required|valid_email|is_unique[users.email,id,{$userId}]" ];
        if (!$this->validate($rules)) {
            return redirect()->to(route_to('profile.show'))->withInput()->with('errors', $this->validator->getErrors());
        }

        $tokenModel = new EmailChangeRequestModel();
        $tokenModel->where('user_id', $userId)->delete();

        $token = bin2hex(random_bytes(32));
        $tokenModel->insert([
            'user_id'    => $userId,
            'new_email'  => $newEmail,
            'token'      => $token,
            'expires_at' => date('Y-m-d H:i:s', time() + 3600)
        ]);

        $emailService = new EmailService();
        $verificationLink = site_url(route_to('profile.email.verify', $token));
        // Disarankan membuat metode khusus untuk email ini di EmailService
        $isSent = $emailService->sendEmailChangeVerification($newEmail, $verificationLink);
       if (!$isSent) {
            return redirect()->to(route_to('profile.show'))->with('error', 'Failed to send verification email. Please try again.');
        }
        
        return redirect()->to(route_to('profile.show'))->with('success', lang('Profile.successEmailRequest'));
    }
    
    /**
     * Memproses link verifikasi untuk email baru.
     */
    public function verifyNewEmail(string $token)
    {
        $tokenModel = new EmailChangeRequestModel();
        $storedToken = $tokenModel->where('token', $token)
                                  ->where('expires_at >', date('Y-m-d H:i:s'))
                                  ->first();
        
        if (!$storedToken) {
            return redirect()->to(route_to('login.show'))->with('error', lang('Profile.errorEmailLink'));
        }

        $userModel = new UserModel();
        $userModel->update($storedToken->user_id, ['email' => $storedToken->new_email]);
        
        if (session()->get('user_id') == $storedToken->user_id) {
            session()->set('user_email', $storedToken->new_email);
        }
        
        $tokenModel->delete($storedToken->id);
        
        return redirect()->to(route_to('profile.show'))->with('success', lang('Profile.successEmailVerified'));
    }
}