<?php

namespace App\Controllers\Admin;

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

class Users extends BaseController
{
    protected $model;
    protected $auditLog;

    public function __construct()
    {
        $this->model = new UserModel();
        $this->auditLog = new AuditLogModel();
    }

    public function index()
    {
        $adminId = session()->get('admin_id');
        $data['users'] = $this->model->where('admin_id', $adminId)->orderBy('created_at', 'DESC')->findAll();
        return view('admin/users/index', $data);
    }

    public function create()
    {
        return view('admin/users/create');
    }

    public function store()
    {
        $adminId = session()->get('admin_id');
        $licenseId = session()->get('admin_license_id');
        
        $password = $this->request->getPost('password');
        $confirmPassword = $this->request->getPost('confirm_password');
        
        if ($password !== $confirmPassword) {
            return redirect()->back()->with('error', 'Passwords do not match');
        }
        
        if (strlen($password) < 6) {
            return redirect()->back()->with('error', 'Password must be at least 6 characters');
        }
        
        $data = [
            'license_id' => $licenseId,
            'admin_id' => $adminId,
            'user_id' => $this->request->getPost('user_id'),
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'full_name' => $this->request->getPost('full_name'),
            'email' => $this->request->getPost('email'),
            'department' => $this->request->getPost('department'),
            'role' => $this->request->getPost('role') ?? 'user',
            'status' => $this->request->getPost('status') ?? 'active',
            'created_at' => date('Y-m-d H:i:s')
        ];

        if ($this->model->insert($data)) {
            $this->auditLog->log('admin', $adminId, 'Created User', 'users', $this->model->getInsertID(), null, $data);
            return redirect()->to('/admin/users')->with('success', 'User created successfully');
        }

        return redirect()->back()->with('error', 'Failed to create user');
    }

    public function edit($id)
    {
        $adminId = session()->get('admin_id');
        $data['user'] = $this->model->where('id', $id)->where('admin_id', $adminId)->first();
        
        if (!$data['user']) {
            return redirect()->to('/admin/users')->with('error', 'User not found');
        }
        
        $data['systemUsage'] = $this->model->getSystemUsage($id);
        return view('admin/users/edit', $data);
    }

    public function update($id)
    {
        $adminId = session()->get('admin_id');
        $oldData = $this->model->where('id', $id)->where('admin_id', $adminId)->first();
        
        if (!$oldData) {
            return redirect()->to('/admin/users')->with('error', 'User not found');
        }
        
        $data = [
            'user_id' => $this->request->getPost('user_id'),
            'full_name' => $this->request->getPost('full_name'),
            'email' => $this->request->getPost('email'),
            'department' => $this->request->getPost('department'),
            'role' => $this->request->getPost('role') ?? 'user',
            'status' => $this->request->getPost('status'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        if ($this->model->update($id, $data)) {
            $this->auditLog->log('admin', $adminId, 'Updated User', 'users', $id, $oldData, $data);
            return redirect()->to('/admin/users')->with('success', 'User updated successfully');
        }

        return redirect()->back()->with('error', 'Failed to update user');
    }

    public function resetPassword($id)
    {
        $adminId = session()->get('admin_id');
        $user = $this->model->where('id', $id)->where('admin_id', $adminId)->first();
        
        if (!$user) {
            return redirect()->to('/admin/users')->with('error', 'User not found');
        }
        
        $newPassword = bin2hex(random_bytes(4));
        
        $this->model->update($id, [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        $this->auditLog->log('admin', $adminId, 'Reset User Password', 'users', $id);
        
        if ($user['email']) {
            $this->sendPasswordEmail($user['email'], $user['user_id'], $newPassword);
        }
        
        return redirect()->to('/admin/users')->with('success', 'Password reset successfully. New password: ' . $newPassword);
    }

    private function sendPasswordEmail($email, $userId, $password)
    {
        $emailService = \Config\Services::email();
        $emailService->setTo($email);
        $emailService->setSubject('Your Account Password');
        $emailService->setMessage("Your login credentials:\nUser ID: {$userId}\nPassword: {$password}");
        $emailService->send();
    }
}
