<?php
class Product extends Model {
    
    public function addProduct($data) {
        $stmt = $this->db->prepare("
            INSERT INTO products (user_id, name, description, price, created_at)
            VALUES (:user_id, :name, :description, :price, NOW())
        ");
        return $stmt->execute([
            'user_id' => $data['user_id'],
            'name' => $data['name'],
            'description' => $data['description'],
            'price' => $data['price']
        ]);
    }


public function getAllProduct()
{
    $stmt = $this->db->query("SELECT * FROM products ORDER BY name");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

    public function getAllProducts($userId, $role) {
        if (strtolower($role) === 'admin') {
            $stmt = $this->db->query("SELECT * FROM products");
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $stmt = $this->db->prepare("SELECT * FROM products WHERE user_id = ?");
            $stmt->execute([$userId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
    
    public function getProductById($id) {
        $stmt = $this->db->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    public function updateProduct($id, $data) {
        $stmt = $this->db->prepare("UPDATE products SET name = ?, description = ?, price = ? WHERE id = ?");
        return $stmt->execute([
            $data['name'],
            $data['description'],
            $data['price'],
            $id
        ]);
    }
    
    public function deleteProduct($id) {
        $stmt = $this->db->prepare("DELETE FROM products WHERE id = ?");
        return $stmt->execute([$id]);
    }
    
    public function getProductsPaginated($userId, $role, $limit, $offset) {
    if (strtolower($role) === 'admin') {
        $stmt = $this->db->prepare("
            SELECT * FROM products
            ORDER BY created_at DESC
            LIMIT :limit OFFSET :offset
        ");
    } else {
        $stmt = $this->db->prepare("
            SELECT * FROM products
            WHERE user_id = :user_id
            ORDER BY created_at DESC
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
    }

    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->execute();

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

    public function countProducts($userId, $role) {
    if (strtolower($role) === 'admin') {
        $stmt = $this->db->query("SELECT COUNT(*) FROM products");
    } else {
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM products WHERE user_id = ?");
        $stmt->execute([$userId]);
    }
    return $stmt->fetchColumn();
}

}
