<?php

namespace App\Controllers\SuperAdmin;

use App\Controllers\BaseController;
use App\Models\SuperAdminModel;
use App\Models\AuditLogModel;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('super_admin_logged_in')) {
            return redirect()->to('/superadmin/dashboard');
        }
        return view('superadmin/login');
    }

    public function authenticate()
    {
        $model = new SuperAdminModel();
        $auditLog = new AuditLogModel();
        
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        
        $admin = $model->verifyPassword($username, $password);
        
        if ($admin) {
            session()->set([
                'super_admin_id' => $admin['id'],
                'super_admin_username' => $admin['username'],
                'super_admin_logged_in' => true
            ]);
            
            $auditLog->log('super_admin', $admin['id'], 'Login', 'super_admins', $admin['id']);
            
            return redirect()->to('/superadmin/dashboard');
        }
        
        return redirect()->to('/superadmin/login')->with('error', 'Invalid credentials');
    }

    public function logout()
    {
        $auditLog = new AuditLogModel();
        $auditLog->log('super_admin', session()->get('super_admin_id'), 'Logout', 'super_admins', session()->get('super_admin_id'));
        
        session()->destroy();
        return redirect()->to('/superadmin/login');
    }

    public function changePassword()
    {
        return view('superadmin/change_password');
    }

    public function updatePassword()
    {
        $model = new SuperAdminModel();
        $auditLog = new AuditLogModel();
        
        $currentPassword = $this->request->getPost('current_password');
        $newPassword = $this->request->getPost('new_password');
        $confirmPassword = $this->request->getPost('confirm_password');
        
        if ($newPassword !== $confirmPassword) {
            return redirect()->back()->with('error', 'New passwords do not match');
        }
        
        $admin = $model->find(session()->get('super_admin_id'));
        
        if (!password_verify($currentPassword, $admin['password'])) {
            return redirect()->back()->with('error', 'Current password is incorrect');
        }
        
        $model->update($admin['id'], [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        $auditLog->log('super_admin', $admin['id'], 'Changed Password', 'super_admins', $admin['id']);
        
        return redirect()->to('/superadmin/dashboard')->with('success', 'Password updated successfully');
    }
}
