<?php

namespace App\Controllers\Frontend;

use App\Controllers\FrontendBaseController;
use App\Models\RewarderCityModel;

class Shop extends FrontendBaseController
{
    public $title = 'Shop';
    public $menu = '';
    public $submenu = '';

    public function view($id)
    {
        $id = (int) $id;
        if ($id < 1) {
            return redirect()->to(url('/'));
        }

        $shop = 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.id', $id)
            ->where('sh.status', 1)
            ->get()
            ->getRow();

        if (!$shop) {
            return redirect()->to(url('/'));
        }

        $now = date('Y-m-d H:i:s');
        $discounts = db_connect()->table('rewarder_discounts d')
            ->select('d.*')
            ->where('d.shop_id', (int) $shop->id)
            ->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();
        // Resolve target names for scoped discounts
        if (!empty($discounts)) {
            $idBuckets = [
                'PRODUCT' => [],
                'PRODUCT_CATEGORY' => [],
                'SERVICE' => [],
                'SERVICE_CATEGORY' => [],
            ];
            foreach ($discounts 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 ($discounts as $dr) {
                $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 ?: ''));
                }
            }
        }

        $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('name')
            ->where('status', 1)
            ->orderBy('name', 'ASC')
            ->limit(100)
            ->get()
            ->getResult();
        $categories = array_values(array_map(static fn($r) => (string) $r->name, $categoryRows));

        $cityId = 0;
        $selectedCityLabel = '';
        if (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;
                foreach ($cities as $c) {
                    if ((int) $c->id === $cityId) {
                        $selectedCityLabel = (string) $c->label;
                        break;
                    }
                }
            }
        }
        $page = null;
        $qText = '';

        return view('frontend/shop/view', [
            'shop' => $shop,
            'discounts' => $discounts,
            'cities' => $cities,
            'popularCities' => $popularCities,
            'categories' => $categories,
            'cityId' => $cityId,
            'selectedCityLabel' => $selectedCityLabel,
            'page' => $page,
            'qText' => $qText,
        ]);
    }

    public function bill($id)
    {
        $id = (int) $id;
        if ($id < 1) {
            return redirect()->to(url('/'));
        }
        if (!is_logged()) {
            $redirectUrl = url('shop/' . $id . '/bill' . (get('discount') ? ('?discount=' . (int) get('discount')) : ''));
            return redirect()->to(url('auth/otp') . '?redirect=' . urlencode($redirectUrl));
        }
        $shop = 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.id', $id)
            ->where('sh.status', 1)
            ->get()
            ->getRow();
        if (!$shop) {
            return redirect()->to(url('/'));
        }
        $discountId = (int) (get('discount') ?? 0);
        $now = date('Y-m-d H:i:s');
        $discount = null;
        if ($discountId > 0) {
            $row = db_connect()->table('rewarder_discounts d')
                ->select('d.*')
                ->where('d.id', $discountId)
                ->where('d.shop_id', (int) $shop->id)
                ->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()
                ->get()
                ->getRow();
            if ($row) {
                $discount = $row;
                $scope = (string) ($discount->applies_to ?? 'ALL');
                if ($scope === 'ALL') {
                    $discount->scope_label = 'All items/services';
                } else {
                    $tid = $discount->target_id ?? null;
                    $name = null;
                    if ($scope === 'PRODUCT') {
                        $r = db_connect()->table('rewarder_products')->select('name')->where('id', $tid)->get()->getRow();
                        $name = $r ? (string) $r->name : null;
                    } elseif ($scope === 'PRODUCT_CATEGORY') {
                        $r = db_connect()->table('rewarder_product_categories')->select('name')->where('id', $tid)->get()->getRow();
                        $name = $r ? (string) $r->name : null;
                    } elseif ($scope === 'SERVICE') {
                        $r = db_connect()->table('rewarder_services')->select('name')->where('id', $tid)->get()->getRow();
                        $name = $r ? (string) $r->name : null;
                    } elseif ($scope === 'SERVICE_CATEGORY') {
                        $r = db_connect()->table('rewarder_service_categories')->select('name')->where('id', $tid)->get()->getRow();
                        $name = $r ? (string) $r->name : null;
                    }
                    $discount->scope_label = $name ? (string) $name : ('#' . (string) ($tid ?: ''));
                }
            }
        }
        $rewardRules = db_connect()->table('rewarder_reward_rules r')
            ->select('r.points_type, r.value')
            ->groupStart()
                ->where('r.shop_id', 0)
                ->orWhere('r.shop_id', (int) $shop->id)
            ->groupEnd()
            ->where('r.status', 1)
            ->where('r.applies_to', 'ALL')
            ->orderBy('r.id', 'desc')
            ->get()->getResult();
        // Navbar preferred city defaults
        $cityId = 0;
        $selectedCityLabel = '';
        $popularCities = [];
        if (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;
                $cityRow = db_connect()->table('rewarder_cities')->select('name')->where('id', $cityId)->get()->getRow();
                if ($cityRow) {
                    $selectedCityLabel = (string) $cityRow->name;
                }
            }
        }
        $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));
        return view('frontend/shop/billing', [
            'shop' => $shop,
            'discount' => $discount,
            'rewardRules' => $rewardRules,
            'cityId' => $cityId,
            'selectedCityLabel' => $selectedCityLabel,
            'popularCities' => $popularCities,
            'page' => null,
            'qText' => '',
        ]);
    }
}
