<?php
	
	namespace Main\Controllers\Store;
	
	use Main\Core\Controller;
	use Main\Services\ProductService;
	use Main\Services\SeoService;
	use Main\Services\SubscriptionService;
	use PDO;
	
	class CategoryController extends Controller
	{
		protected string $route_type = 'store';
		
		public function __construct()
		{
			if (modules('store')->settings('redirect') != '') {
				redirect(modules('store')->settings('redirect'));
			}
		}
		
		public function show($slug)
		{
			$category = db()->prepare("SELECT * FROM ProductCategories WHERE slug = ? AND isActive = ?");
			$category->execute(array($slug, 1));
			$category = $category->fetch(PDO::FETCH_ASSOC);
			
			if (!$category) abort_404();
			
			SeoService::set('store.categories.show', [
				'category_name' => $category['name'],
			]);
			
			$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();
			}
			
			$subscription = SubscriptionService::getSubscriptionByCategory($category);
			$communityGoalProgress = modules('store')->settings('communityGoalStatus') == '1' ? intval((100 * modules('store')->settings('communityGoalCurrent')) / modules('store')->settings('communityGoalTarget')) : 0;
			
			$categories = db()->prepare("SELECT * FROM ProductCategories WHERE parentID = ? AND isActive = ? ORDER BY priority DESC");
			$categories->execute([0, 1]);
			$categories = array_map(function ($category) use ($purchasedProductsIDs) {
				$category["image"] = '/assets/core/images/store/categories/' . $category["imageID"] . '.' . $category["imageType"];
				
				$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)))) {
					return null;
				}
				
				return $category;
			}, $categories->fetchAll(PDO::FETCH_ASSOC));
			$categories = array_filter($categories);
			
			$parent = db()->prepare("SELECT * FROM ProductCategories WHERE id = ?");
			$parent->execute(array($category["parentID"]));
			$parent = $parent->fetch(PDO::FETCH_ASSOC);
			$category["parent"] = $parent;
			
			$tierList = db()->prepare("SELECT * FROM VIPTables WHERE categoryID = ?");
			$tierList->execute(array($category["id"]));
			$tierList = $tierList->fetch(PDO::FETCH_ASSOC);
			
			if ($tierList) {
				$tiers = db()->prepare("SELECT V.*, P.* FROM VIPs V INNER JOIN Products P ON V.vipID = P.id WHERE V.tableID = ? AND P.isActive = ? ORDER BY P.priority DESC");
				$tiers->execute(array($tierList["id"], 1));
				$tiers = $tiers->fetchAll(PDO::FETCH_ASSOC);
				$tierList["tiers"] = ProductService::listing($tiers, $subscription);
				
				$tierTitles = db()->prepare("SELECT * FROM VIPTitles WHERE tableID = ? ORDER BY priority ASC");
				$tierTitles->execute(array($tierList["id"]));
				$tierList["titles"] = array_map(function ($title) {
					$tierDescriptions = db()->prepare("SELECT D.description FROM VIPDesc D INNER JOIN Products P ON P.id = D.vipID WHERE D.titleID = ? AND P.isActive = ? ORDER BY P.priority DESC");
					$tierDescriptions->execute(array($title["id"], 1));
					$tierDescriptions = $tierDescriptions->fetchAll(PDO::FETCH_ASSOC);
					$title["descriptions"] = array_column($tierDescriptions, "description");
					
					$tierExplain = db()->prepare("SELECT name FROM VIPExplain WHERE titleID = ?");
					$tierExplain->execute(array($title["id"]));
					$tierExplain = $tierExplain->fetch(PDO::FETCH_ASSOC);
					$title["explain"] = ($tierExplain) ? $tierExplain["name"] : null;
					
					return $title;
				}, $tierTitles->fetchAll(PDO::FETCH_ASSOC));
				
				return $this->view('store.tiers', compact('category', 'categories', 'tierList', 'subscription', 'communityGoalProgress'));
			}
			
			$subcategories = db()->prepare("SELECT * FROM ProductCategories WHERE parentID = ? AND isActive = ? ORDER BY priority DESC");
			$subcategories->execute(array($category["id"], 1));
			$subcategories = array_map(function ($category) use ($purchasedProductsIDs) {
				$category["image"] = '/assets/core/images/store/categories/' . $category["imageID"] . '.' . $category["imageType"];
				
				$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)))) {
					return null;
				}
				
				return $category;
			}, $subcategories->fetchAll(PDO::FETCH_ASSOC));
			$subcategories = array_filter($subcategories);
			$category["subcategories"] = $subcategories;
			
			$topSales = db()->prepare("SELECT P.*, COUNT(*) AS productCount FROM OrderProducts OP INNER JOIN Products P ON OP.productID = P.id WHERE P.isActive = ? AND P.categoryID = ? GROUP BY P.id ORDER BY productCount DESC LIMIT 4");
			$topSales->execute(array(1, $category["id"]));
			$topSales = $topSales->fetchAll(PDO::FETCH_ASSOC);
			$topSales = ProductService::listing($topSales, $subscription);
			$category["topSales"] = $topSales;
			
			$products = db()->prepare("SELECT * FROM Products WHERE isActive = ? AND categoryID = ? ORDER BY priority DESC");
			$products->execute(array(1, $category["id"]));
			$products = $products->fetchAll(PDO::FETCH_ASSOC);
			$products = ProductService::listing($products, $subscription);
			$category["products"] = $products;
			
			return $this->view('store.category', compact('category', 'subcategories', 'categories', 'subscription', 'topSales', 'products', 'communityGoalProgress'));
		}
	}