<?php

namespace App\Models;

use App\Core\Model;
use PDO;

class User extends Model {
    public function search($params = []) {
        $sql = "SELECT * FROM users WHERE role = 'staff'";
        if (!empty($params['search'])) {
            $sql .= " AND (name LIKE :search OR email LIKE :search)";
        }
        $sql .= " ORDER BY id DESC";
        $stmt = $this->db->prepare($sql);
        if (!empty($params['search'])) {
            $stmt->execute(['search' => '%' . $params['search'] . '%']);
        } else {
            $stmt->execute();
        }
        return $stmt->fetchAll();
    }

    public function findByEmail($email) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
        $stmt->execute(['email' => $email]);
        return $stmt->fetch();
    }

    public function find($id) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
        $stmt->execute(['id' => $id]);
        return $stmt->fetch();
    }

    public function save($data) {
        if (!empty($data['id'])) {
            $sql = "UPDATE users SET name = :name, email = :email, role = :role, permissions = :permissions";
            $params = [
                'name' => $data['name'],
                'email' => $data['email'],
                'role' => $data['role'],
                'permissions' => $data['permissions'] ?? null,
                'id' => $data['id']
            ];
            if (!empty($data['password'])) {
                $sql .= ", password = :password";
                $params['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            $sql .= " WHERE id = :id";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute($params);
        } else {
            $sql = "INSERT INTO users (name, email, password, role, permissions) 
                    VALUES (:name, :email, :password, :role, :permissions)";
            $stmt = $this->db->prepare($sql);
            return $stmt->execute([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                'role' => $data['role'],
                'permissions' => $data['permissions'] ?? null
            ]);
        }
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM users WHERE id = :id AND role != 'admin'");
        return $stmt->execute(['id' => $id]);
    }
}
