<?php
require_once __DIR__ . '/../config/database.php';

class ProductController {

    private $conn;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
    }

    public function getProducts() {
        $result = $this->conn->query("SELECT * FROM products");
        $products = [];
        while ($row = $result->fetch_assoc()) {
            $products[] = $row;
        }
        return $products;
    }

    public function getCategories() {
        $result = $this->conn->query("SELECT * FROM categories");
        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
        return $categories;
    }

    public function createProduct($name, $price, $stock, $category_id) {
        $stmt = $this->conn->prepare("INSERT INTO products (name, price, stock, category_id) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("sdis", $name, $price, $stock, $category_id);
        return $stmt->execute();
    }

    public function updateProduct($id, $name, $price, $stock, $category_id) {
        $stmt = $this->conn->prepare("UPDATE products SET name = ?, price = ?, stock = ?, category_id = ? WHERE id = ?");
        $stmt->bind_param("sdisi", $name, $price, $stock, $category_id, $id);
        return $stmt->execute();
    }

    public function deleteProduct($id) {
        $stmt = $this->conn->prepare("DELETE FROM products WHERE id = ?");
        $stmt->bind_param("i", $id);
        return $stmt->execute();
    }

    public function getTopSellingProducts() {
        $result = $this->conn->query("SELECT p.name, COUNT(s.id) as sale_count FROM sales s JOIN sale_items si ON s.id = si.sale_id JOIN products p ON si.product_id = p.id GROUP BY p.name ORDER BY sale_count DESC LIMIT 5");
        $products = [];
        while ($row = $result->fetch_assoc()) {
            $products[] = $row;
        }
        return $products;
    }
}
?>