<?php
require_once __DIR__ . '/../functions.php';
require_once __DIR__ . '/../../api/response.php';

class User {
    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }

    public function getAll() {
        $stmt = $this->conn->query("SELECT * FROM users");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    
    public function get($id) {
        $stmt = $this->conn->query("SELECT * FROM users where id=$id");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    public function filter($key,$value) {
        $stmt = $this->conn->query("SELECT * FROM users where $key=$value");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function create($data) {
       
        // بررسی فیلدهای اجباری
        if (empty($data['username']) || empty($data['email']) || empty($data['password'])) {
            return ['error' => 'فیلدهای username، email و password اجباری هستند.'];
        }
    //    $user=filter('username',$data['username']);
      // بررسی وجود کاربر تکراری
      $check = $this->conn->prepare("SELECT id FROM users WHERE username = :username LIMIT 1");
      $check->execute([':username' => $data['username']]);
      if ($check->fetch()) {
          http_response_code(409); // Conflict
          return errorResponse("نام کاربری قبلاً ثبت شده است!");


      }
      $check1 = $this->conn->prepare("SELECT id FROM users WHERE email = :email LIMIT 1");
      $check1->execute([':email' => $data['email']]);
      if ($check1->fetch()) {
          http_response_code(409); // Conflict
          return errorResponse("ایمیل قبلاً ثبت شده است!");

      }
        // فیلدهای اختیاری: اگر وجود نداشتند، NULL قرار بده
        $fields = [
            'phone_number' => $data['phone_number'] ?? null,
            'status'       => $data['status'] ?? 1,
            'name'         => $data['name'] ?? null,
            'role'         => $data['role'] ?? 2 ,
            'address'      => $data['address'] ?? null,
            'adress'       => $data['adress'] ?? null,
            'avatar'       => $data['avatar'] ?? null
        ];
    
        // هش کردن رمز عبور برای امنیت
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
    
        // ساخت کوئری
        $sql = "INSERT INTO users 
            (username, email, password, phone_number, status, name, role, address, adress, avatar)
            VALUES 
            (:username, :email, :password, :phone_number, :status, :name, :role, :address, :adress, :avatar)";
        
        $stmt = $this->conn->prepare($sql);
    
        // اجرای کوئری با مقادیر
        $stmt->execute([
            ':username'     => $data['username'],
            ':email'        => $data['email'],
            ':password'     => $hashedPassword,
            ':phone_number' => $fields['phone_number'],
            ':status'       => $fields['status'],
            ':name'         => $fields['name'],
            ':role'         => $fields['role'],
            ':address'      => $fields['address'],
            ':adress'       => $fields['adress'],
            ':avatar'       => $fields['avatar']
        ]);

        return successResponse("کاربر با موفقیت ایجاد شد.", ["id" => $this->conn->lastInsertId()]);
    }
    
    

    public function update($id, $name, $email) {
        $stmt = $this->conn->prepare("UPDATE users SET name=:name, email=:email WHERE id=:id");
        $stmt->execute([':id' => $id, ':name' => $name, ':email' => $email]);
        return ['updated' => $stmt->rowCount()];
    }

    public function delete($id) {
        $stmt = $this->conn->prepare("DELETE FROM users WHERE id=:id");
        $stmt->execute([':id' => $id]);
        return ['deleted' => $stmt->rowCount()];
    }
}
?>