<?php
namespace App\Controllers;

use App\Models\ProductDetailsModel;
use App\Models\OrderModel;
use CodeIgniter\Controller;

class ProductDetails extends BaseController
{
    protected $productModel;
    protected $orderModel;
    protected $session;

    public function __construct()
    {
        helper(['url', 'form']);
        $this->session = session();

        // Redirect if user not logged in
        if (!$this->session->get('isLoggedIn')) {
            return redirect()->to(base_url('authController'))->send();
        }

        $this->productModel = new ProductDetailsModel();
        $this->orderModel = new OrderModel();
    }

    // Show product details
    public function index($id = null)
    {
        if (!$id) return redirect()->to(base_url('order'));

        $userId = $this->session->get('user_id');

        // Fetch product with variants
        $product = $this->productModel->getProductWithVariants($id);
        if (!$product) return redirect()->to(base_url('order'));

        // Fetch session data
        $user_apartName = $this->session->get('apartName') ?? 'Select Apartment';

        return view('productsDetails_view', [
            'product'        => $product,
            'cart_count'     => $this->orderModel->getCartCount($userId),
            'user_name'      => $this->session->get('name'),
            'user_phone'     => $this->session->get('phone'),
            'user_apartName' => $user_apartName
        ]);
    }

    // Add product to cart via AJAX
    public function addToCart()
    {
        if (!$this->request->isAJAX()) return $this->response->setStatusCode(400);

        $productId = $this->request->getPost('product_id');
        $variantId = $this->request->getPost('variant_id');
        $quantity  = $this->request->getPost('quantity') ?? 1;
        $userId    = $this->session->get('user_id');

        // Add to cart
        $this->orderModel->addToCartItem($productId, $variantId, $quantity, $userId);

        return $this->response->setJSON([
            'success'    => true,
            'cart_count' => $this->orderModel->getCartCount($userId)
        ]);
    }
}
