<?php

namespace App\Controllers;

use App\Models\RewarderCityModel;

class Home extends BaseController
{
    
    public function index()
    {
        $cityId = get('city_id') ? (int) get('city_id') : 0;
        $cityQuery = trim((string) (get('city') ?? ''));
        $qText = trim((string) (get('q') ?? ''));
        $selectedCategoryId = get('category_id') ? (int) get('category_id') : 0;
        $page = get('page') ? (int) get('page') : 1;
        if ($page < 1) {
            $page = 1;
        }

        if ($cityId < 1 && $cityQuery === '' && function_exists('is_logged') && is_logged()) {
            $pref = db_connect()->table('users')->select('preferred_city_id')->where('id', logged('id'))->get()->getRow();
            if ($pref && !empty($pref->preferred_city_id)) {
                $cityId = (int) $pref->preferred_city_id;
            }
        }

        $perPage = 24;
        $offset = ($page - 1) * $perPage;

        $cities = (new RewarderCityModel())->activeOptionList();
        $popularCityRows = db_connect()->table('rewarder_cities')
            ->select('id, name')
            ->where('status', 1)
            ->where('populercity', 1)
            ->orderBy('name', 'ASC')
            ->limit(12)
            ->get()
            ->getResult();
        $popularCities = array_values(array_map(static function($r) {
            return (object)['id' => (int)$r->id, 'label' => (string)$r->name];
        }, $popularCityRows));
        $categoryRows = db_connect()->table('rewarder_shop_categories')
            ->select('id, name, img_type')
            ->where('status', 1)
            ->orderBy('name', 'ASC')
            ->limit(100)
            ->get()
            ->getResult();
        $shopCategories = array_values(array_map(static function ($r) {
            $iconUrl = !empty($r->img_type)
                ? urlUpload('shop_categories/' . (int) $r->id . '.' . $r->img_type, true)
                : admin_assets('img/default-150x150.png');

            return (object) [
                'id' => (int) $r->id,
                'name' => (string) $r->name,
                'img_type' => (string) ($r->img_type ?? ''),
                'icon_url' => (string) $iconUrl,
            ];
        }, $categoryRows));
        $categories = array_values(array_map(static fn($r) => (string) $r->name, $shopCategories));

        $filterCityIds = [];
        if ($cityId > 0) {
            $filterCityIds = [$cityId];
        } elseif ($cityQuery !== '') {
            $searchCityTerm = $cityQuery;
            if (strpos($searchCityTerm, '-') !== false) {
                $searchCityTerm = trim((string) explode('-', $searchCityTerm, 2)[0]);
            }
            if (strpos($searchCityTerm, ',') !== false) {
                $searchCityTerm = trim((string) explode(',', $searchCityTerm, 2)[0]);
            }
            if ($searchCityTerm === '') {
                $searchCityTerm = $cityQuery;
            }
            $rows = db_connect()->table('rewarder_cities')
                ->select('id')
                ->where('status', 1)
                ->like('name', $searchCityTerm)
                ->limit(200)
                ->get()
                ->getResult();
            $filterCityIds = array_values(array_map(static fn ($r) => (int) $r->id, $rows));
        }

        $countQ = db_connect()->table('rewarder_shops sh')
            ->join('rewarder_shop_categories cat', 'cat.id = sh.category_id', 'left')
            ->where('sh.status', 1);
        if (!empty($filterCityIds)) {
            $countQ->whereIn('sh.city_id', $filterCityIds);
        } elseif ($cityQuery !== '') {
            $countQ->where('1=0', null, false);
        }
        if ($selectedCategoryId > 0) {
            $countQ->where('sh.category_id', $selectedCategoryId);
        }
        if ($qText !== '') {
            $countQ->groupStart()
                ->like('sh.name', $qText)
                ->orLike('sh.address', $qText)
                ->orLike('cat.name', $qText)
            ->groupEnd();
        }
        $total = (int) $countQ->countAllResults();

        $q = db_connect()->table('rewarder_shops sh')
            ->select('sh.*, c.name AS city_name, cat.name AS category_name')
            ->join('rewarder_cities c', 'c.id = sh.city_id', 'left')
            ->join('rewarder_shop_categories cat', 'cat.id = sh.category_id', 'left')
            ->where('sh.status', 1);

        if (!empty($filterCityIds)) {
            $q->whereIn('sh.city_id', $filterCityIds);
        } elseif ($cityQuery !== '') {
            $q->where('1=0', null, false);
        }
        if ($selectedCategoryId > 0) {
            $q->where('sh.category_id', $selectedCategoryId);
        }
        if ($qText !== '') {
            $q->groupStart()
                ->like('sh.name', $qText)
                ->orLike('sh.address', $qText)
                ->orLike('cat.name', $qText)
            ->groupEnd();
        }

        $shops = $q->orderBy('RAND()', '', false)
            ->limit($perPage, $offset)
            ->get()
            ->getResult();

        // Load active discounts for the listed shops
        $shopDiscounts = [];
        if (!empty($shops)) {
            $shopIds = array_values(array_map(static fn($r) => (int) $r->id, $shops));
            $now = date('Y-m-d H:i:s');
            $drows = db_connect()->table('rewarder_discounts d')
                ->select('d.*')
                ->whereIn('d.shop_id', $shopIds)
                ->where('d.status', 1)
                ->groupStart()
                    ->where('d.start_at', null)->orWhere('d.start_at <=', $now)
                ->groupEnd()
                ->groupStart()
                    ->where('d.end_at', null)->orWhere('d.end_at >=', $now)
                ->groupEnd()
                ->orderBy('d.id', 'desc')
                ->get()
                ->getResult();
            // Build target name lookups for scoped discounts
            $idBuckets = [
                'PRODUCT' => [],
                'PRODUCT_CATEGORY' => [],
                'SERVICE' => [],
                'SERVICE_CATEGORY' => [],
            ];
            foreach ($drows as $dr) {
                $scope = (string) ($dr->applies_to ?? '');
                $tid = $dr->target_id ?? null;
                if ($tid && isset($idBuckets[$scope])) {
                    $idBuckets[$scope][] = (int) $tid;
                }
            }
            $lookups = [
                'PRODUCT' => [],
                'PRODUCT_CATEGORY' => [],
                'SERVICE' => [],
                'SERVICE_CATEGORY' => [],
            ];
            if (!empty($idBuckets['PRODUCT'])) {
                $rows = db_connect()->table('rewarder_products')
                    ->select('id, name')
                    ->whereIn('id', array_unique($idBuckets['PRODUCT']))
                    ->get()->getResult();
                $lookups['PRODUCT'] = array_column($rows, 'name', 'id');
            }
            if (!empty($idBuckets['PRODUCT_CATEGORY'])) {
                $rows = db_connect()->table('rewarder_product_categories')
                    ->select('id, name')
                    ->whereIn('id', array_unique($idBuckets['PRODUCT_CATEGORY']))
                    ->get()->getResult();
                $lookups['PRODUCT_CATEGORY'] = array_column($rows, 'name', 'id');
            }
            if (!empty($idBuckets['SERVICE'])) {
                $rows = db_connect()->table('rewarder_services')
                    ->select('id, name')
                    ->whereIn('id', array_unique($idBuckets['SERVICE']))
                    ->get()->getResult();
                $lookups['SERVICE'] = array_column($rows, 'name', 'id');
            }
            if (!empty($idBuckets['SERVICE_CATEGORY'])) {
                $rows = db_connect()->table('rewarder_service_categories')
                    ->select('id, name')
                    ->whereIn('id', array_unique($idBuckets['SERVICE_CATEGORY']))
                    ->get()->getResult();
                $lookups['SERVICE_CATEGORY'] = array_column($rows, 'name', 'id');
            }
            foreach ($drows as $dr) {
                $sid = (int) $dr->shop_id;
                if (!isset($shopDiscounts[$sid])) $shopDiscounts[$sid] = [];
                // Human-friendly scope label
                $scope = (string) ($dr->applies_to ?? 'ALL');
                if ($scope === 'ALL') {
                    $dr->scope_label = 'All items/services';
                } else {
                    $tid = $dr->target_id ?? null;
                    $name = ($tid && isset($lookups[$scope])) ? ($lookups[$scope][(int) $tid] ?? null) : null;
                    $dr->scope_label = $name ? (string) $name : ('#' . (string) ($tid ?: ''));
                }
                // Limit to first 3 discounts per shop for overview
                if (count($shopDiscounts[$sid]) < 3) {
                    $shopDiscounts[$sid][] = $dr;
                }
            }
        }

        $totalPages = (int) ceil($total / $perPage);
        if ($totalPages < 1) {
            $totalPages = 1;
        }
        if ($page > $totalPages) {
            $page = $totalPages;
        }

        $selectedCityLabel = '';
        if ($cityId > 0) {
            foreach ($cities as $c) {
                if ((int) $c->id === $cityId) {
                    $selectedCityLabel = (string) $c->label;
                    break;
                }
            }
        } elseif ($cityQuery !== '') {
            $selectedCityLabel = $cityQuery;
        }

        return view('frontend/home', [
            'cities' => $cities,
            'shops' => $shops,
            'cityId' => $cityId,
            'cityQuery' => $cityQuery,
            'qText' => $qText,
            'selectedCityLabel' => $selectedCityLabel,
            'selectedCategoryId' => $selectedCategoryId,
            'page' => $page,
            'perPage' => $perPage,
            'total' => $total,
            'totalPages' => $totalPages,
            'categories' => $categories,
            'shopCategories' => $shopCategories,
            'popularCities' => $popularCities,
            'shopDiscounts' => $shopDiscounts,
        ]);
    }

}
