<?php
require_once __DIR__ . '/../models/product.php';

class ProductController {
    private $db;
    private $product;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
        $this->product = new Product($this->db);
    }

    public function getAll() {
        $stmt = $this->product->getAll();
        $num = $stmt->rowCount();

        if($num > 0) {
            $products_arr = array();
            $products_arr["records"] = array();

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

                $product_item = array(
                    "id" => $id,
                    "name" => $name,
                    "description" => $description,
                    "price" => $price,
                    "image" => $image,
                    "category_name" => $category_name,
                    "stock_quantity" => $stock_quantity
                );

                array_push($products_arr["records"], $product_item);
            }

            http_response_code(200);
            echo json_encode($products_arr);
        } else {
            http_response_code(404);
            echo json_encode(array("message" => "No products found."));
        }
    }

    public function getOne($params) {
        $this->product->id = $params['id'];

        if($this->product->getOne()) {
            $product_arr = array(
                "id" => $this->product->id,
                "name" => $this->product->name,
                "description" => $this->product->description,
                "price" => $this->product->price,
                "image" => $this->product->image,
                "category_name" => $this->product->category_name,
                "stock_quantity" => $this->product->stock_quantity
            );

            http_response_code(200);
            echo json_encode($product_arr);
        } else {
            http_response_code(404);
            echo json_encode(array("message" => "Product not found."));
        }
    }
}
?>