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

    public $id;
    public $name;
    public $email;
    public $password_hash;
    public $role;
    public $phone;
    public $email_verified;
    public $created_at;
    public $updated_at;

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

    // Register user
    public function register() {
        try {
            // Check if email already exists
            if ($this->emailExists()) {
                error_log("Email already exists: " . $this->email);
                return false;
            }

            // Generate UUID for the user
            $userId = $this->generateUUID();

            $query = "INSERT INTO " . $this->table_name . "
                      SET id = :id, name = :name, email = :email, password_hash = :password_hash,
                          phone = :phone, created_at = NOW(), updated_at = NOW()";

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

            // Sanitize
            $this->name = htmlspecialchars(strip_tags($this->name));
            $this->email = htmlspecialchars(strip_tags($this->email));
            $this->phone = htmlspecialchars(strip_tags($this->phone));
            $this->password_hash = password_hash($this->password_hash, PASSWORD_DEFAULT);

            // Bind values
            $stmt->bindParam(':id', $userId);
            $stmt->bindParam(':name', $this->name);
            $stmt->bindParam(':email', $this->email);
            $stmt->bindParam(':password_hash', $this->password_hash);
            $stmt->bindParam(':phone', $this->phone);

            if ($stmt->execute()) {
                error_log("User registered successfully with ID: " . $userId);
                return $userId;
            } else {
                error_log("Failed to execute insert statement");
                return false;
            }
        } catch (Exception $e) {
            error_log("Registration error in User model: " . $e->getMessage());
            throw $e;
        }
    }

    // Generate UUID
    private function generateUUID() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    // Login user
    public function login($email, $password) {
        $query = "SELECT id, name, email, password_hash, role, phone, email_verified
                  FROM " . $this->table_name . "
                  WHERE email = :email";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':email', $email);
        $stmt->execute();

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

        if ($user && password_verify($password, $user['password_hash'])) {
            unset($user['password_hash']); // Remove password from response
            return $user;
        }

        return false;
    }

    // Check if email exists
    public function emailExists() {
        $query = "SELECT id FROM " . $this->table_name . " WHERE email = :email";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':email', $this->email);
        $stmt->execute();

        return $stmt->rowCount() > 0;
    }

    // Get user by ID
    public function getUserById($id) {
        $query = "SELECT id, name, email, role, phone, email_verified, created_at
                  FROM " . $this->table_name . "
                  WHERE id = :id";

        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update user profile
    public function updateProfile() {
        $query = "UPDATE " . $this->table_name . "
                  SET name = :name, phone = :phone, updated_at = NOW()
                  WHERE id = :id";

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

        // Sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->phone = htmlspecialchars(strip_tags($this->phone));
        $this->id = htmlspecialchars(strip_tags($this->id));

        // Bind values
        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':phone', $this->phone);
        $stmt->bindParam(':id', $this->id);

        return $stmt->execute();
    }

    // Change password
    public function changePassword($oldPassword, $newPassword) {
        // First verify old password
        $query = "SELECT password_hash FROM " . $this->table_name . " WHERE id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $this->id);
        $stmt->execute();

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

        if (!$user || !password_verify($oldPassword, $user['password_hash'])) {
            return false;
        }

        // Update password
        $updateQuery = "UPDATE " . $this->table_name . "
                        SET password_hash = :password_hash, updated_at = NOW()
                        WHERE id = :id";

        $updateStmt = $this->conn->prepare($updateQuery);
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        $updateStmt->bindParam(':password_hash', $hashedPassword);
        $updateStmt->bindParam(':id', $this->id);

        return $updateStmt->execute();
    }
}
?>