<?php

namespace App\Controllers\Frontend\User;

use App\Controllers\FrontendBaseController;
use App\Models\RewarderLedgerModel;
use App\Models\RewarderWalletModel;
use App\Models\UserModel;

class Wallet extends FrontendBaseController
{
    public $title = 'Wallet';
    public $menu = 'user';
    public $submenu = 'wallet';

    public function index()
    {
        $this->permissionCheck('user_wallet_view');

        $wallet = (new RewarderWalletModel())->where('user_id', logged('id'))->first();
        $balance = $wallet ? (int) $wallet->points_balance : 0;
        $user = (new UserModel())->select('total_reward_point')->where('id', logged('id'))->first();
        $totalRewardPoint = $user ? (int) ($user->total_reward_point ?? 0) : 0;
        $ledger = (new RewarderLedgerModel())->where('user_id', logged('id'))->orderBy('id', 'desc')->findAll();

        if (!empty($ledger)) {
            $payments = db_connect()->table('rewarder_payments')
                ->select('id, user_id, status, created_at')
                ->where('user_id', logged('id'))
                ->where('status', 'SUCCESS')
                ->orderBy('created_at', 'desc')
                ->get()->getResult();
            foreach ($ledger as $l) {
                if ((empty($l->payment_id) || (int) $l->payment_id === 0)
                    && !empty($l->created_at)
                    && is_string($l->description)
                    && strpos(strtolower($l->description), 'online bill payment') !== false
                ) {
                    $t = strtotime($l->created_at);
                    $bestId = null;
                    $bestDiff = 999999;
                    foreach ($payments as $p) {
                        $pt = !empty($p->created_at) ? strtotime($p->created_at) : 0;
                        if ($pt > 0) {
                            $diff = abs($pt - $t);
                            if ($diff < $bestDiff) {
                                $bestDiff = $diff;
                                $bestId = (int) $p->id;
                            }
                        }
                    }
                    if ($bestId !== null && $bestDiff <= 300) {
                        $l->payment_id = $bestId;
                    }
                }
            }
        }

        $db = db_connect();
        $spinLogs = [];
        $spinLogsColumns = [];
        $spinLogsOrderIndex = null;
        if ($db->tableExists('rewarder_spin_logs')) {
            $fields = $db->getFieldNames('rewarder_spin_logs') ?? [];
            $userIdField = null;
            foreach (['user_id', 'customer_id'] as $f) {
                if (in_array($f, $fields, true)) {
                    $userIdField = $f;
                    break;
                }
            }

            $preferredColumns = [
                'id',
                'spinwheel_title',
                'wheel_title',
                'slice_label',
                'label',
                'reward',
                'reward_value',
                'points',
                'points_won',
                'points_awarded',
                'points_earned',
                'spin_cost',
                'cost',
                'created_at',
                'created_on',
                'date',
            ];

            foreach ($preferredColumns as $c) {
                if (in_array($c, $fields, true)) {
                    $spinLogsColumns[] = $c;
                }
            }

            if (empty($spinLogsColumns)) {
                $spinLogsColumns = $fields;
            }

            $spinLogsColumns = array_values(array_filter(
                $spinLogsColumns,
                static fn ($c) => !in_array($c, ['id', 'spinwheel_id', 'slice_id'], true)
            ));

            $builder = $db->table('rewarder_spin_logs');
            if ($userIdField) {
                $builder->where($userIdField, (int) logged('id'));
            }

            $spinTimeField = null;
            foreach (['created_at', 'created_on', 'date'] as $f) {
                if (in_array($f, $fields, true)) {
                    $spinTimeField = $f;
                    break;
                }
            }

            if ($spinTimeField) {
                $builder->orderBy($spinTimeField, 'desc');
                $idx = array_search($spinTimeField, $spinLogsColumns, true);
                if ($idx !== false) {
                    $spinLogsOrderIndex = (int) $idx;
                }
            } elseif (in_array('id', $fields, true)) {
                $builder->orderBy('id', 'desc');
            }
            $spinLogs = $builder->limit(1000)->get()->getResult();
        }

        return view('frontend/user/wallet/front_index', compact('balance', 'totalRewardPoint', 'ledger', 'spinLogs', 'spinLogsColumns', 'spinLogsOrderIndex'));
    }
}

