<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $this->requireAuth();
        $userModel = new User();
        $users = $userModel->getAll();
        $this->render('users/index', ['users' => $users, 'pageTitle' => 'User Management']);
    }

    public function createForm()
    {
        $this->requireAuth();
        $this->render('users/create', ['pageTitle' => 'Add User']);
    }

    public function store()
    {
        $this->requireAuth();
        $userModel = new User();
        $data = [
            'username' => $_POST['username'],
            'full_name' => $_POST['full_name'],
            'email' => $_POST['email'],
            'role' => $_POST['role'],
            'status' => $_POST['status'],
            'password' => $_POST['password']
        ];
        $userModel->create($data);
        $_SESSION['success'] = 'User created successfully.';
        $this->redirect('/users');
    }

    public function editForm($id)
    {
        $this->requireAuth();
        $userModel = new User();
        $user = $userModel->find($id);
        if (!$user) {
            $this->redirect('/users');
        }
        $this->render('users/edit', ['user' => $user, 'pageTitle' => 'Edit User']);
    }

    public function update($id)
    {
        $this->requireAuth();
        $userModel = new User();
        $data = [
            'username' => $_POST['username'],
            'full_name' => $_POST['full_name'],
            'email' => $_POST['email'],
            'role' => $_POST['role'],
            'status' => $_POST['status']
        ];
        if (!empty($_POST['password'])) {
            $data['password'] = $_POST['password'];
        }
        $userModel->update($id, $data);
        $_SESSION['success'] = 'User updated successfully.';
        $this->redirect('/users');
    }

    public function delete($id)
    {
        $this->requireAuth();
        // Prevent deleting self
        if ($id == $_SESSION['user_id']) {
            $_SESSION['error'] = 'You cannot delete your own account.';
            $this->redirect('/users');
            return;
        }
        $userModel = new User();
        $userModel->delete($id);
        $_SESSION['success'] = 'User deleted successfully.';
        $this->redirect('/users');
    }
}