<?php

namespace Main\Controllers\Store;

use Main\Core\Controller;
use Main\Services\ProductService;
use Main\Services\SeoService;
use Main\Services\SubscriptionService;
use PDO;

class ProductController extends Controller
{
		protected string $route_type = 'store';
	
		public function __construct()
		{
			if (modules('store')->settings('redirect') != '') {
				redirect(modules('store')->settings('redirect'));
			}
		}
	
    public function show($id)
    {
        $product = db()->prepare("SELECT * FROM Products WHERE id = ?");
        $product->execute(array($id));
        $product = $product->fetch();

        if (!$product) abort_404();
	    
		    SeoService::set('store.products.show', [
			    'product_name' => $product['name'],
		    ]);

        $category = db()->prepare("SELECT * FROM ProductCategories WHERE id = ?");
		    $category->execute(array($product["categoryID"]));
		    $category = $category->fetch();
				
				if (!$category) abort_404();
				
				$product["category"] = $category;
	    
	      $subscription = SubscriptionService::getSubscriptionByCategory($category);
				$product = ProductService::product($product, $subscription);
	    
		    $purchasedProductsIDs = [];
		    if (auth()->check()) {
			    $purchasedProductsIDs = db()->prepare("SELECT productID FROM PurchasedProducts WHERE accountID = ? AND (expiresAt > ? OR expiresAt IS NULL)");
			    $purchasedProductsIDs->execute(array(auth()->user()->id(), datetime()));
			    $purchasedProductsIDs = $purchasedProductsIDs->fetchAll(PDO::FETCH_COLUMN);
		    }
		    $categoryRequiredProducts = db()->prepare("SELECT productID FROM ProductCategoryRequiredProducts WHERE categoryID = ?");
		    $categoryRequiredProducts->execute(array($category["id"]));
		    $categoryRequiredProducts = $categoryRequiredProducts->fetchAll(PDO::FETCH_COLUMN);
		    if ($categoryRequiredProducts && (!auth()->check() || empty(array_intersect($purchasedProductsIDs, $categoryRequiredProducts)))) {
			    abort_404();
		    }
	    
	      $communityGoalProgress = modules('store')->settings('communityGoalStatus') == '1' ? intval((100 * modules('store')->settings('communityGoalCurrent')) / modules('store')->settings('communityGoalTarget')) : 0;
				
				if (request()->isAjax() || request()->isFormatAccepted('json')) {
					response()->json([
						'status' => true,
						'html' => template()->render('modals/store-product', compact('product', 'communityGoalProgress'))
					]);
				}

        return $this->view('store.product', compact('product', 'communityGoalProgress'));
    }
}