<?php
class ProductController extends Controller {
    public function index()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/login/index");
            exit;
        }

        $userId = $_SESSION['user_id'];
        $role = $_SESSION['user_role'];

        $productModel = $this->model('Product');

        // Pagination setup
        $limit = 10; // items per page
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $offset = ($page - 1) * $limit;

        // Fetch paginated products
        $products = $productModel->getProductsPaginated($userId, $role, $limit, $offset);

        // Count total products for pagination
        $totalProducts = $productModel->countProducts($userId, $role);
        $totalPages = ceil($totalProducts / $limit);

        $this->view('products/index', [
            'products' => $products,
            'role' => $role,
            'currentPage' => $page,
            'totalPages' => $totalPages
        ]);
    }

    public function add() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'user_id' => $_SESSION['user_id'],
                'name' => trim($_POST['name']),
                'description' => trim($_POST['description']),
                'price' => trim($_POST['price'])
            ];

            $productModel = $this->model('Product');
            if ($productModel->addProduct($data)) {
                $_SESSION['success'] = "Product added successfully.";
                header("Location: " . BASE_URL . "/product");
                exit;
            } else {
                $_SESSION['error'] = "Error adding product.";
            }
        }

        $this->view('products/add');
    }

    public function edit($id = null) {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $productModel = $this->model('Product');
        $product = $productModel->getProductById($id);

        if (!$product) {
            $_SESSION['error'] = "Product not found.";
            header("Location: " . BASE_URL . "/product");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = [
                'name' => trim($_POST['name']),
                'description' => trim($_POST['description']),
                'price' => trim($_POST['price'])
            ];

            if ($productModel->updateProduct($id, $data)) {
                $_SESSION['success'] = "Product updated successfully.";
                header("Location: " . BASE_URL . "/product");
                exit;
            } else {
                $_SESSION['error'] = "Error updating product.";
            }
        }

        $this->view('products/edit', ['product' => $product]);
    }

    public function delete($id) {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $productModel = $this->model('Product');
        if ($productModel->deleteProduct($id)) {
            $_SESSION['success'] = "Product deleted successfully.";
        } else {
            $_SESSION['error'] = "Error deleting product.";
        }
        header("Location: " . BASE_URL . "/product");
        exit;
    }
}
