<?php
class User {
    private $conn;
    private $table_name = "users";

    public $id;
    public $username;
    public $password;
    public $email;
    public $full_name;
    public $phone;
    public $postal_code;
    public $role;

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

    public function create() {
        $query = "INSERT INTO " . $this->table_name . " 
                 SET username=:username, password=:password, email=:email, full_name=:full_name,
                     phone=:phone, postal_code=:postal_code";

        $stmt = $this->conn->prepare($query);

        $this->username    = htmlspecialchars(strip_tags($this->username));
        $this->email       = htmlspecialchars(strip_tags($this->email));
        $this->full_name   = htmlspecialchars(strip_tags($this->full_name));
        $this->phone       = htmlspecialchars(strip_tags($this->phone ?? ''));
        $this->postal_code = htmlspecialchars(strip_tags($this->postal_code ?? ''));
        $password_hash = password_hash($this->password, PASSWORD_BCRYPT);

        $stmt->bindParam(":username",    $this->username);
        $stmt->bindParam(":email",       $this->email);
        $stmt->bindParam(":password",    $password_hash);
        $stmt->bindParam(":full_name",   $this->full_name);
        $stmt->bindParam(":phone",       $this->phone);
        $stmt->bindParam(":postal_code", $this->postal_code);

        if($stmt->execute()) {
            return true;
        }
        return false;
    }

    public function login($username, $password) {
        $query = "SELECT id, username, password, email, full_name, phone, postal_code, role 
                  FROM " . $this->table_name . " 
                  WHERE username = ? LIMIT 0,1";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $username);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if($row && password_verify($password, $row['password'])) {
            $this->id          = $row['id'];
            $this->username    = $row['username'];
            $this->email       = $row['email'];
            $this->full_name   = $row['full_name'];
            $this->phone       = $row['phone'];
            $this->postal_code = $row['postal_code'];
            $this->role        = $row['role'];
            return true;
        }
        return false;
    }
}
?>
