<?php
namespace App\Controllers;

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

class UsersController extends Controller {
    public function index(): void {
        $users = User::all('name ASC');
        $this->render('users/index', ['users' => $users]);
    }

    public function store(): void {
        $name = trim(Request::post('name', ''));
        $email = trim(Request::post('email', ''));
        $password = Request::post('password', '');
        $role = Request::post('role', 'agent');
        $phone = trim(Request::post('phone', ''));

        if (empty($name) || empty($email) || empty($password)) {
            Response::error('Name, Email, and Password are required.');
        }

        $existing = User::findByEmail($email);
        if ($existing) {
            Response::error('A user with this email already exists.');
        }

        $userId = User::create([
            'name'          => $name,
            'email'         => $email,
            'password_hash' => password_hash($password, PASSWORD_BCRYPT),
            'role'          => $role,
            'phone'         => $phone ?: null,
            'status'        => 'active',
            'created_at'    => date('Y-m-d H:i:s')
        ]);

        if (Request::isAjax()) {
            Response::success(User::find($userId), 'User created successfully');
        }
        Response::redirect('/users');
    }

    public function update(int $id): void {
        $name = trim(Request::post('name', ''));
        $email = trim(Request::post('email', ''));
        $role = Request::post('role', 'agent');
        $status = Request::post('status', 'active');
        $phone = trim(Request::post('phone', ''));
        $password = Request::post('password');

        $updateData = [
            'name'   => $name,
            'email'  => $email,
            'role'   => $role,
            'status' => $status,
            'phone'  => $phone ?: null
        ];

        if (!empty($password)) {
            $updateData['password_hash'] = password_hash($password, PASSWORD_BCRYPT);
        }

        User::update($id, $updateData);

        if (Request::isAjax()) {
            Response::success(User::find($id), 'User updated');
        }
        Response::redirect('/users');
    }

    public function delete(int $id): void {
        if ($id === 1) {
            Response::error('Cannot delete the primary administrator account.');
        }
        User::delete($id);
        if (Request::isAjax()) {
            Response::success(null, 'User deleted');
        }
        Response::redirect('/users');
    }
}
