<?php

namespace App\Controllers\Admin;

use App\Models\AdminModel;

class Profile extends AdminBaseController
{
    public function index()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        if ($this->request->getMethod() === 'POST') {
            $currentPassword = $this->request->getPost('current_password');
            $newPassword = $this->request->getPost('new_password');
            $confirmPassword = $this->request->getPost('confirm_password');

            if ($newPassword !== $confirmPassword) {
                $this->session->setFlashdata('error', 'New password and confirm password do not match.');
                return redirect()->to('/admin/profile');
            }

            $model = new AdminModel();
            $adminId = $this->session->get('admin_id');
            $admin = $model->find($adminId);

            if ($admin && password_verify($currentPassword, $admin['password'])) {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $model->update($adminId, ['password' => $hashedPassword]);
                $this->session->setFlashdata('success', 'Password updated successfully.');
                return redirect()->to('/admin/profile');
            } else {
                $this->session->setFlashdata('error', 'Incorrect current password.');
                return redirect()->to('/admin/profile');
            }
        }

        $data['title'] = 'Change Password';
        return view('admin/profile/index', $data);
    }
}
