<?php

namespace app\api\controller;

use app\common\model\AppRoll;
use app\common\model\Configure;
use app\common\model\Level;
use app\common\model\Message;
use app\common\model\User;
use app\common\model\WalletLog;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use app\common\model\BankSys;
use app\common\model\Goods;
use think\exception\HttpResponseException;

class Index extends Base
{
    //登录
    public function login()
    {
        $username = $this->request->post('username', '', 'trim');
        $password = $this->request->post('pass', '', 'trim');
        if (!$username)
            $this->result(false, '参数有误');
        $info = User::where(['username' => $username])->field('id,username,password,nickname,status,invite_code')->find();
        if (!$info) {
            $this->result(false, '用户名或者密码错误');
        }
        $info = $info->toArray();
        if ($password != $info['password']) {
            $this->result(false, '用户名或者密码错误');
        }
        if ($info['status'] == 2) {
            $this->result(false, '该账号被禁用了，请联系客服');
        }
        $data['login_time'] = time();
        $data['login_ip'] = $this->request->ip();
        User::update($data, ['id' => $info['id']]);
        $auth = md5($info['password'] . $info['id']) . '!' . $info['username'];
        $info['auth'] = $auth;
        Cache::set($auth, $info, 0);
        $this->result(true, '操作成功', ['authorization' => $auth]);
    }

    //注册
    public function doRegister()
    {
        $username = $this->request->post('username', '', 'trim');
        $password = $this->request->post('pass', '', 'trim');
        $deal_pass = $this->request->post('deal_pass', '', 'trim');
        $invite_code = $this->request->post('invite_code', '', 'trim');
        $nickname = $this->request->post('nickname', '', 'trim');
        if (!$username || !$password || !$deal_pass || !$invite_code || !$nickname)
            $this->result(false, '参数有误');
        Db::startTrans();
        try {
            $mod = new User();
            $info = $mod->where(['invite_code' => $invite_code])->field('id,status,sub_num,family,agent_id')->find();
            if (!$info)
                throw new \Exception('邀请码无效');
            if ($info['status'] == 2)
                throw new \Exception('上级被禁用');
            $count = $mod->where(['username' => $username])->count();
            if ($count)
                throw new \Exception('用户名已存在');
            $data['username'] = $username;
            $data['password'] = $password;
            $data['deal_pass'] = $deal_pass;
            $data['pid'] = $info['id'];
            $data['agent_id'] = $info['id'];//$info['agent_id'] ?? $info['id'];
            $data['nickname'] = $nickname;
            $data['balance'] = $this->config['system_basic']['register_reward'] ?? 0;//注册奖励
            $data['invite_code'] = getRandStr(6);
            $data['create_time'] = time();
            if ($info['family']) {
                $family = explode('-', $info['family']);
                if (count($family) == 5) {
                    unset($family[4]);
                }
                array_unshift($family, $info['id']);
                $data['family'] = implode('-', $family);
            } else {
                $data['family'] = $info['id'];
            }
            $mes_data['title_vi'] = $this->config['system_home']['register_title_vi'] ?? '';
            $mes_data['title_en'] = $this->config['system_home']['register_title_vi'] ?? '';
            $mes_data['content_vi'] = $this->config['system_home']['register_vi'] ?? '';
            $mes_data['content_en'] = $this->config['system_home']['register_en'] ?? '';
            $mes_data['content_zh'] = $this->config['system_home']['register_zh'] ?? '';
            $mes_data['create_time'] = time();
            $mod->update(['sub_num' => $info['sub_num'] + 1], ['id' => $info['id']]);
            $res = $mod->insertGetId($data);
            $mes_data['uid'] = $res;
            Message::create($mes_data);
            Db::commit();
            
            // Auto-login after registration: generate auth token and cache user info
            try {
                // Update login_time and login_ip after transaction commit
                $login_data['login_time'] = time();
                $login_data['login_ip'] = $this->request->ip();
                try {
                    User::update($login_data, ['id' => $res]);
                } catch (\Exception $e) {
                    // Log but don't fail registration if login update fails
                    Log::error('Update login info failed after registration: ' . $e->getMessage());
                }
                
                // Build user info array for cache (same fields as login)
                $user_info = [
                    'id' => $res,
                    'username' => $username,
                    'password' => $password,
                    'nickname' => $nickname,
                    'status' => 1, // New users default to status 1
                    'invite_code' => $data['invite_code']
                ];
                
                // Generate auth token (same format as login)
                $auth = md5($password . $res) . '!' . $username;
                $user_info['auth'] = $auth;
                
                // Cache user info (wrap in try-catch in case cache fails)
                try {
                    Cache::set($auth, $user_info, 0);
                } catch (\Exception $e) {
                    Log::error('Cache set failed after registration: ' . $e->getMessage());
                    // Continue even if cache fails
                }
                
                $this->result(true, '注册成功', ['authorization' => $auth]);
            } catch (HttpResponseException $e) {
                // Re-throw HttpResponseException so it can be handled by the framework
                throw $e;
            } catch (\Exception $e) {
                // If auto-login setup fails, still return success but log the error
                Log::error('Auto-login setup failed after registration: ' . $e->getMessage() . ' at line ' . $e->getLine());
                $this->result(true, '注册成功');
            }
        } catch (HttpResponseException $e) {
            // Re-throw HttpResponseException so it can be handled by the framework
            throw $e;
        } catch (\Exception $e) {
            Db::rollback();
            $errorMsg = $e->getMessage();
            if (empty($errorMsg)) {
                $errorMsg = '注册失败，请重试';
            }
            Log::error('添加用户失败-' . $errorMsg . ':' . $e->getLine() . ' | Code: ' . $e->getCode());
            if ($e->getCode() == 0) {
                $this->result(false, $errorMsg);
            } else {
                $this->result(false, '系统繁忙，请重试');
            }
        }
    }
    
    public function bank_sys(){
        $list=BankSys::where('status',1)->select();
        if($list)$list= $list->toArray();
        $this->result(true, '操作成功', $list);
    }

    //退出
    public function logout()
    {
        $auth = $this->request->user['auth'] ?? '';
        Cache::delete($auth);
        $this->result(true, '退出成功');
    }

    //获取首页数据
    public function getIndex()
    {
        $domain = $this->request->domain();
        $uid = $this->request->user['id'] ?? 0;
        if ($uid) {
            $data['no_read_mes'] = Message::where(['uid' => $uid, 'status' => 0])->count();
        }

        $cert_list_vi = explode(',', $this->config['system_home']['cert_list_vi'] ?? '');
        $cert_list_en = explode(',', $this->config['system_home']['cert_list_en'] ?? '');
        $cert_list_zh = explode(',', $this->config['system_home']['cert_list_zh'] ?? '');
        
        $cert_list_de = explode(',', $this->config['system_home']['cert_list_de'] ?? '');
        $cert_list_fa = explode(',', $this->config['system_home']['cert_list_fa'] ?? '');
        $cert_list_ru = explode(',', $this->config['system_home']['cert_list_ru'] ?? '');
        $cert_list_italien = explode(',', $this->config['system_home']['cert_list_italien'] ?? '');
        $cert_list_pt = explode(',', $this->config['system_home']['cert_list_pt'] ?? '');
        $cert_list_es = explode(',', $this->config['system_home']['cert_list_es'] ?? '');
        // $event_list_vi = explode(',', $this->config['system_home']['event_list_vi'] ?? '');
        // $event_list_en = explode(',', $this->config['system_home']['event_list_en'] ?? '');
        // $event_list_zh = explode(',', $this->config['system_home']['event_list_zh'] ?? '');
        array_shift($cert_list_vi);
        array_shift($cert_list_en);
        array_shift($cert_list_zh);
        
        array_shift($cert_list_de);
        array_shift($cert_list_fa);
        array_shift($cert_list_ru);
        array_shift($cert_list_italien);
        array_shift($cert_list_pt);
        array_shift($cert_list_es);
        // array_shift($event_list_vi);
        // array_shift($event_list_en);
        // array_shift($event_list_zh);
        foreach ($cert_list_vi as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_en as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_zh as &$item) {
            $item = $domain . $item;
        }
        
        foreach ($cert_list_de as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_fa as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_ru as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_italien as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_pt as &$item) {
            $item = $domain . $item;
        }
        foreach ($cert_list_es as &$item) {
            $item = $domain . $item;
        }
        // foreach ($event_list_vi as &$item) {
        //     $item = $domain . $item;
        // }
        // foreach ($event_list_en as &$item) {
        //     $item = $domain . $item;
        // }
        // foreach ($event_list_zh as &$item) {
        //     $item = $domain . $item;
        // }
        if (empty($this->config['system_home']['pop_vi']))
            $pop_vi = '';
        else
            $pop_vi = $domain . $this->config['system_home']['pop_vi'];
        if (empty($this->config['system_home']['pop_en']))
            $pop_en = '';
        else
            $pop_en = $domain . $this->config['system_home']['pop_en'];
        if (empty($this->config['system_home']['pop_zh']))
            $pop_zh = '';
        else
            $pop_zh = $domain . $this->config['system_home']['pop_zh'];
            
         if (empty($this->config['system_home']['pop_arab']))
            $pop_arab = '';
        else
            $pop_arab = $domain . $this->config['system_home']['pop_arab'];
         if (empty($this->config['system_home']['pop_fa']))
            $pop_fa = '';
        else
            $pop_fa = $domain . $this->config['system_home']['pop_fa'];
         if (empty($this->config['system_home']['pop_ru']))
            $pop_ru = '';
        else
            $pop_ru = $domain . $this->config['system_home']['pop_ru'];
        
         if (empty($this->config['system_home']['pop_italien']))
            $pop_italien = '';
        else
            $pop_italien = $domain . $this->config['system_home']['pop_italien'];    
        if (empty($this->config['system_home']['pop_es']))
            $pop_es = '';
        else
            $pop_es = $domain . $this->config['system_home']['pop_es'];   
        if (empty($this->config['system_home']['pop_pt']))
            $pop_pt = '';
        else
            $pop_pt = $domain . $this->config['system_home']['pop_pt'];   
            
            
        if (empty($this->config['system_basic']['logo']))
            $logo = '';
        else
            $logo = $domain . $this->config['system_basic']['logo'];
            
        // Get popular products for index page
        try {
            $goodsModel = new Goods();
            $popularProducts = $goodsModel->alias('g')
                ->leftJoin('mod_order o', 'g.id = o.goods_id')
                ->field([
                    'g.id as goods_id',
                    'g.name',
                    'g.price',
                    'g.img',
                    'g.desc as description',
                    'COUNT(o.id) as num'
                ])
                ->group('g.id')
                ->order('num DESC, g.id DESC')
                ->limit(6) // Show top 6 popular products
                ->select()
                ->toArray();

            // If no products found with orders, get latest products
            if (empty($popularProducts)) {
                $popularProducts = $goodsModel
                    ->field([
                        'id as goods_id',
                        'name',
                        'price',
                        'img',
                        'desc as description'
                    ])
                    ->order('id DESC')
                    ->limit(6)
                    ->select()
                    ->each(function($item) {
                        $item['num'] = 0;
                        return $item;
                    })
                    ->toArray();
            }

            // Format product images
            foreach ($popularProducts as &$product) {
                if (!empty($product['img'])) {
                    $product['img'] = $domain . $product['img'];
                }
            }
            
            $data['popular_products'] = $popularProducts;
        } catch (\Exception $e) {
            \think\facade\Log::error('Error getting popular products: ' . $e->getMessage());
            $data['popular_products'] = [];
        }

        $data['config'] = [
            'operation_time' => ($this->config['system_basic']['open_time'] ?? '') . ' - ' . ($this->config['system_basic']['close_time'] ?? ''),
            'withdraw_time' => ($this->config['system_basic']['with_open_time'] ?? '') . ' - ' . ($this->config['system_basic']['with_close_time'] ?? ''),
            'app_name' => $this->config['system_basic']['app_name'] ?? '',
            'app_logo' => $logo,
            'active_vi' => $this->config['system_home']['event_list_vi'] ?? '',
            'active_en' => $this->config['system_home']['event_list_en'] ?? '',
            'active_zh' => $this->config['system_home']['event_list_zh'] ?? '',
            'active_arab' => $this->config['system_home']['event_list_arab'] ?? '',
            'active_ru' => $this->config['system_home']['event_list_ru'] ?? '',
            'active_fa' => $this->config['system_home']['event_list_fa'] ?? '',
            'active_italien' => $this->config['system_home']['event_list_italien'] ?? '',
            'active_pt' => $this->config['system_home']['event_list_pt'] ?? '',
            'active_es' => $this->config['system_home']['event_list_es'] ?? '',
            
            'cert_vi' => $cert_list_vi,
            'cert_en' => $cert_list_en,
            'cert_ezh' => $cert_list_zh,
            
            'cert_de' => $cert_list_de,
            'cert_fa' => $cert_list_fa,
            'cert_ru' => $cert_list_ru,
            'cert_italien' => $cert_list_italien,
            'cert_pt' => $cert_list_pt,
            'cert_es' => $cert_list_es,
            
            'pop_vi' => $pop_vi,
            'pop_en' => $pop_en,
            'pop_zh' => $pop_zh,
            
            'pop_arab' => $pop_arab,
            'pop_ru' => $pop_ru,
            'pop_fa' => $pop_fa,
            'pop_italien' => $pop_italien,
            'pop_pt' => $pop_pt,
            'pop_es' => $pop_es,
            
            'tips_vi' => $this->config['system_home']['system_tips_vi'] ?? '',
            'tips_en' => $this->config['system_home']['system_tips_en'] ?? '',
            'tips_zh' => $this->config['system_home']['system_tips_zh'] ?? '',
            'intro_vi' => $this->config['system_home']['intro_vi'] ?? '',
            'intro_en' => $this->config['system_home']['intro_en'] ?? '',
            'intro_zh' => $this->config['system_home']['intro_zh'] ?? '',
            
            'intro_arab' => $this->config['system_home']['intro_arab'] ?? '',
            'intro_ru' => $this->config['system_home']['intro_ru'] ?? '',
            'intro_fa' => $this->config['system_home']['intro_fa'] ?? '',
            'intro_italien' => $this->config['system_home']['intro_italien'] ?? '',
            'intro_pt' => $this->config['system_home']['intro_pt'] ?? '',
            'intro_es' => $this->config['system_home']['intro_es'] ?? '',
            
            'rule_vi' => $this->config['system_home']['rule_vi'] ?? '',
            'rule_en' => $this->config['system_home']['rule_en'] ?? '',
            'rule_zh' => $this->config['system_home']['rule_zh'] ?? '',
            
            'rule_arab' => $this->config['system_home']['rule_arab'] ?? '',
            'rule_ru' => $this->config['system_home']['rule_ru'] ?? '',
            'rule_fa' => $this->config['system_home']['rule_fa'] ?? '',
            'rule_italien' => $this->config['system_home']['rule_italien'] ?? '',
            'rule_pt' => $this->config['system_home']['rule_pt'] ?? '',
            'rule_es' => $this->config['system_home']['rule_es'] ?? '',
            
            'about_us_vi' => $this->config['system_home']['about_us_vi'] ?? '',
            'about_us_en' => $this->config['system_home']['about_us_en'] ?? '',
            'about_us_zh' => $this->config['system_home']['about_us_zh'] ?? '',
            
            'about_us_arab' => $this->config['system_home']['about_us_arab'] ?? '',
            'about_us_ru' => $this->config['system_home']['about_us_ru'] ?? '',
            'about_us_fa' => $this->config['system_home']['about_us_fa'] ?? '',
            'about_us_italien' => $this->config['system_home']['about_us_italien'] ?? '',
            'about_us_pt' => $this->config['system_home']['about_us_pt'] ?? '',
            'about_us_es' => $this->config['system_home']['about_us_es'] ?? '',
        ];
        if ($uid) {
            $data['vip_list'] = Level::select()->toArray();
            foreach ($data['vip_list'] as &$item) {
                if ($item['img'])
                    $item['img'] = $domain . $item['img'];
                $item['withdraw_rate_txt'] = ($item['withdraw_rate'] * 100) . '%';
                $item['order_rate_txt'] = ($item['order_rate'] * 100) . '%';
            }
        }
        $this->result(true, '操作成功', $data);
    }

    //获取客服列表
    public function getCustomer()
    {
        $list = $this->config['system_link'];
        $this->result(true, '操作成功', $list);
    }

    //获取VIP列表
    public function getVipList()
    {
        $domain = $this->request->domain();
        $list = Level::select()->toArray();
        foreach ($list as &$item) {
            if ($item['img'])
                $item['img'] = $domain . $item['img'];
            $item['withdraw_rate_txt'] = ($item['withdraw_rate'] * 100) . '%';
            $item['order_rate_txt'] = ($item['order_rate'] * 100) . '%';
        }
        $this->result(true, '操作成功', $list);
    }

    //购买会员
    public function buyVip()
    {
        $level_id = $this->request->post('level_id', 0, 'intval');
        if (!$level_id)
            $this->result(false, '参数有误');
        $uid = $this->request->user['id'];
        $user_info = User::field('level_id,balance')->find($uid);
        if (!$user_info)
            $this->result(false, '数据不存在');
        $level_info = Level::field('price,reward_price')->find($level_id);
        if (!$level_info)
            $this->result(false, '数据不存在');
        if ($user_info['level_id'] == $level_id)
            $this->result(false, '您已经是这个等级了');
        if ($user_info['level_id'] > $level_id)
            $this->result(false, '不可降级');
        if ($user_info['balance'] < $level_info['price'])
            $this->result(false, '可用余额不足1');
        Db::startTrans();
        try {
            $data['balance'] = $user_info['balance'] - $level_info['price'] + $level_info['reward_price'];
            $data['level_id'] = $level_id;
            User::update($data, ['id' => $uid]);
            //添加记录
            $log[] = [
                'uid' => $uid,
                'type' => 6,
                'status' => 2,
                'price' => $level_info['price'],
                'price_pre' => $user_info['balance'],
                'explain' => '会员升级到VIP-' . $level_id,
                'create_time' => time(),
                'extra_id' => $level_id,
            ];
            if ($level_info['reward_price'] > 0) {
                $log[] = [
                    'uid' => $uid,
                    'type' => 7,
                    'status' => 1,
                    'price' => $level_info['reward_price'],
                    'price_pre' => $user_info['balance'] - $level_info['price'],
                    'explain' => '会员升级奖励VIP-' . $level_id,
                    'create_time' => time(),
                    'extra_id' => $level_id,
                ];
            }
            WalletLog::insertAll($log);
            Db::commit();
        } catch (\Exception $e) {
            Log::error('会员升级失败-' . $e->getMessage() . ":" . $e->getLine());
            Db::rollback();
            $this->result(false, '系统繁忙，请重试');
        }
        $this->result(true);
    }

    //获取消息列表
    public function getMesList()
    {
        $uid = $this->request->user['id'];
        $web_time = $this->request->post('web_time', '', 'trim');
        if ($web_time)
            $diff_time = time() - strtotime($web_time);
        else
            $diff_time = 0;
        $page = $this->request->post('page', 1, 'intval');
        $list = Message::where(['uid' => $uid])->order('id desc')->paginate(['list_rows' => 10, 'page' => $page])->toArray();
        foreach ($list['data'] as &$item) {
            $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']) - $diff_time);
        }
        $this->result(true, '操作成功', $list['data'], ['total' => $list['total'], 'last_page' => $list['last_page']]);
    }

    //设置消息已读
    public function setMesRead()
    {
        $id = $this->request->post('mes_id', 0, 'intval');
        if (!$id)
            $this->result(false, '参数有误');
        Message::update(['status' => 1], ['id' => $id]);
        $this->result(true);
    }

    //获取app滚动列表
    public function getAppList()
    {
        $domain = $this->request->domain();
        $list = AppRoll::field('id,name,img')->select()->toArray();
        foreach ($list as &$item) {
            if ($item['img'])
                $item['img'] = $domain . $item['img'];
        }
        $this->result(true, '操作成功', $list);
    }

    //获取app滚动详情
    public function getAppInfo()
    {
        $id = $this->request->post('id', 0, 'intval');
        $web_time = $this->request->post('web_time', '', 'trim');
        if ($web_time)
            $diff_time = time() - strtotime($web_time);
        else
            $diff_time = 0;
        if (!$id)
            $this->result(false, '参数有误');
        $info = AppRoll::find($id);
        if (!$info)
            $this->result(false, '数据不存在');
        $info = $info->toArray();
        $info['create_time'] = date('Y-m-d H:i:s', strtotime($info['create_time']) - $diff_time);
        $this->result(true, '操作成功', $info);
    }

    public function getAgreement()
    {
        $sys_info = Configure::find(5);
        $info = json_decode($sys_info['content'], true);
        if (!$info) {
            $info = ['register_vi' => '', 'register_en' => ''];
        }
        $this->result(true, '操作成功', $info);
    }

    public function getConfig(){
        $system_info = Configure::find(1);
        $info = json_decode($system_info['content'], true);
        $this->result(true, '操作成功', $info);
    }
}
