<?php
class UserController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? ''; $role = $_GET['role'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE u.deleted_at IS NULL AND u.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
        if ($role) { $where .= " AND u.role_id = ?"; $params[] = $role; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM users u $where", $params);
        $offset = ($page - 1) * $perPage;
        $users = $this->db->fetchAll("SELECT u.*, r.name as role_name FROM users u LEFT JOIN roles r ON u.role_id=r.id $where ORDER BY u.created_at DESC LIMIT $perPage OFFSET $offset", $params);
        $roles = $this->db->fetchAll("SELECT id, name FROM roles WHERE company_id=? OR company_id IS NULL ORDER BY name", [$cid]);
        $pagination = paginationHtml($total, $page, $perPage, '?page=users');
        require 'app/views/users/index.php';
    }

    public function create() {
        $user = null; $cid = Auth::user()['company_id'];
        $roles = $this->db->fetchAll("SELECT id, name FROM roles WHERE company_id=? OR company_id IS NULL ORDER BY name", [$cid]);
        require 'app/views/users/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('first_name')->required('last_name')->required('email')->required('password');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=users&action=create'); }
        $exists = $this->db->fetchColumn("SELECT COUNT(*) FROM users WHERE email=? AND deleted_at IS NULL", [$_POST['email']]);
        if ($exists) { flash('error', 'Email already in use.'); redirect('?page=users&action=create'); }
        $this->db->insert('users', [
            'company_id' => Auth::user()['company_id'], 'role_id' => $_POST['role_id'] ?: null,
            'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'],
            'email' => $_POST['email'], 'password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
            'phone' => $_POST['phone'] ?? null, 'status' => $_POST['status'] ?? 'active',
        ]);
        flash('success', 'User created.'); redirect('?page=users');
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $user = $this->db->fetch("SELECT * FROM users WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$user) { flash('error', 'User not found.'); redirect('?page=users'); }
        $roles = $this->db->fetchAll("SELECT id, name FROM roles WHERE company_id=? OR company_id IS NULL ORDER BY name", [$cid]);
        require 'app/views/users/form.php';
    }

    public function update($id) {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $data = [
            'role_id' => $_POST['role_id'] ?: null, 'first_name' => $_POST['first_name'],
            'last_name' => $_POST['last_name'], 'email' => $_POST['email'],
            'phone' => $_POST['phone'] ?? null, 'status' => $_POST['status'] ?? 'active',
        ];
        if (!empty($_POST['password'])) $data['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $this->db->update('users', $data, 'id = ? AND company_id = ?', [$id, $cid]);
        flash('success', 'User updated.'); redirect('?page=users');
    }

    public function delete($id) {
        CSRF::verify();
        if ($id == Auth::user()['id']) { flash('error', 'Cannot delete your own account.'); redirect('?page=users'); }
        $this->db->softDelete('users', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'User deleted.'); redirect('?page=users');
    }
}
