<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AdminUsersController extends Controller
{
    public function index()
    {
        $this->checkAdmin();
        $db = Database::getInstance()->getConnection();
        $users = $db->query("SELECT * FROM users ORDER BY name")->fetchAll();
        $this->view('admin.users.index', ['users' => $users]);
    }

    public function create()
    {
        $this->checkAdmin();
        $this->view('admin.users.form');
    }

    public function store()
    {
        $this->checkAdmin();
        $db = Database::getInstance()->getConnection();

        $name = trim($_POST['name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'employee';
        
        // Mandatory permissions
        $permissions = ['dashboard', 'kitchen'];
        
        // Optional permissions
        if (isset($_POST['perm_stock'])) $permissions[] = 'stock';
        if (isset($_POST['perm_menu'])) $permissions[] = 'menu';
        if (isset($_POST['perm_sales'])) $permissions[] = 'sales';

        if (empty($name) || empty($username) || empty($password)) {
            // Error handling could be better
            $this->redirect('/admin/usuarios/novo');
        }

        // Check duplicate username
        $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
             // Error: duplicate
             $this->redirect('/admin/usuarios/novo?error=user_exists');
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $permJson = json_encode($permissions);

        $stmt = $db->prepare("INSERT INTO users (name, username, password, role, permissions) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$name, $username, $hash, $role, $permJson]);

        $this->redirect('/admin/usuarios');
    }
    
    public function edit($id)
    {
        $this->checkAdmin();
        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([(int)$id]);
        $user = $stmt->fetch();

        if (!$user) {
            $this->redirect('/admin/usuarios');
        }

        $user['permissions'] = json_decode($user['permissions'] ?? '[]', true);
        $this->view('admin.users.form', ['user' => $user]);
    }

    public function update($id)
    {
        $this->checkAdmin();
        $db = Database::getInstance()->getConnection();

        $name = trim($_POST['name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $role = $_POST['role'] ?? 'employee';
        
        // Mandatory permissions
        $permissions = ['dashboard', 'kitchen'];
        
        // Optional permissions
        if (isset($_POST['perm_stock'])) $permissions[] = 'stock';
        if (isset($_POST['perm_menu'])) $permissions[] = 'menu';
        if (isset($_POST['perm_sales'])) $permissions[] = 'sales';
        
        if (empty($name) || empty($username)) {
            $this->redirect('/admin/usuarios/' . $id . '/editar');
        }

        $permJson = json_encode($permissions);
        
        // Password update only if provided
        $password = $_POST['password'] ?? '';
        if (!empty($password)) {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("UPDATE users SET name = ?, username = ?, password = ?, role = ?, permissions = ? WHERE id = ?");
            $stmt->execute([$name, $username, $hash, $role, $permJson, (int)$id]);
        } else {
            $stmt = $db->prepare("UPDATE users SET name = ?, username = ?, role = ?, permissions = ? WHERE id = ?");
            $stmt->execute([$name, $username, $role, $permJson, (int)$id]);
        }

        $this->redirect('/admin/usuarios');
    }

    public function delete($id)
    {
        $this->checkAdmin();
        // Prevent deleting self
        if ($_SESSION['user_id'] == $id) {
            $this->redirect('/admin/usuarios?error=cannot_delete_self');
        }

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([(int)$id]);

        $this->redirect('/admin/usuarios');
    }
}
