<?php

namespace app\api\controller;

use app\common\model\Bank;
use app\common\model\Level;
use app\common\model\User;
use app\common\model\Withdraw;
use think\facade\Db;
use think\facade\Lang;
use think\facade\Log;
use app\common\model\Reg;
use app\common\model\BankSys;

class Account extends Base
{
    //获取用户基本数据
    public function getUserInfo()
    {
        $domain = $this->request->domain();
        $uid = $this->request->user['id'];
        $field = 'username,nickname,level_id,credit_score,invite_code,deal_pass,bind_card,status,balance,trade_status,order_total,commission,is_test,today_profit,deal_date';
        $info = User::field($field)->find($uid)->toArray();
        
        $start = strtotime('today');
        $end = strtotime('tomorrow') - 1;
        $sum_pos = Db::name('Order')
            ->where(['uid' => $uid, 'status' => 2])
            ->where('end_time', '>=', $start)
            ->where('end_time', '<=', $end)
            ->where('commission', '>', 0)
            ->sum('commission');
        $info['today_profit_pos'] = sprintf("%.2f", floatval($sum_pos));
        // Map total commission to today_profit field for frontend display
        $info['today_profit'] = sprintf("%.2f", floatval($info['commission']));
        
        $level_info = Level::find($info['level_id']);
        if ($level_info['img'])
            $level_info['img'] = $domain . $level_info['img'];
        $info['level'] = $level_info;
        $this->result(true, '操作成功', $info);
    }

    //更改密码
    public function changePass()
    {
        $old_pass = $this->request->post('old_pass', '', 'trim');
        $new_pass = $this->request->post('new_pass', '', 'trim');
        $type = $this->request->post('type', 1, 'intval');//类型1-登录密码2-交易密码
        if (!$old_pass || !$new_pass)
            $this->result(false, '参数有误');
        $uid = $this->request->user['id'];
        $user_info = User::field('password,deal_pass')->find($uid);
        if ($type == 1) {
            if ($old_pass != $user_info['password'])
                $this->result(false, '旧密码有误');
            $data['password'] = $new_pass;
        } else {
            if ($old_pass != $user_info['deal_pass'])
                $this->result(false, '旧密码有误');
            $data['deal_pass'] = $new_pass;
        }
        $res = User::update($data, ['id' => $uid]);
        if ($res)
            $this->result(true);
        else
            $this->result(false, '操作失败');
    }

    //获取银行信息
    public function getCard()
    {
        $uid = $this->request->user['id'];
        $info = Bank::where(['uid' => $uid])->select();
        if (!$info)
            $info = ['name' => ''];
        else
            $info = $info->toArray();



        $bank_list = $this->config['system_bank'];


//        foreach ($bank_list as &$item) {
//            if ($info['name'] == $item['name_vi'] || $info['name'] == $item['name_en']) {
//                $item['check'] = true;
//            } else {
//                $item['check'] = false;
//            }
//        }

        $this->result(true, '操作成功', $info, ['bank_list' => $bank_list]);
    }

    //设置银行信息
    public function setCard()
    {
        $name = $this->request->post('name', '', 'trim');
        $card_no = $this->request->post('card_no', '', 'trim');
        $account_name = $this->request->post('account_name', '', 'trim');
        $account_open = $this->request->post('account_open', '', 'trim');
        $mobile = $this->request->post('mobile', '', 'trim');
        $type = $this->request->post('type', 0, 'trim');
        $usdt_type = $this->request->post('usdt_type', 0, 'trim');

        if (!$name || !$card_no || !$account_name)
            $this->result(false, '参数有误');
        $uid = $this->request->user['id'];
        $data['name'] = $name;
        $data['card_no'] = $card_no;
        $data['account_name'] = $account_name;
        $data['account_open_name'] = $account_open;
        $data['mobile'] = $mobile;
        $data['type'] = $type ?? 0;
        $data['usdt_type'] = $usdt_type ?? 0;
        $bank = Bank::where(['uid' => $uid, 'type' => $type])->field('id')->find();

        if ($bank) {
            $res = Bank::update($data, ['id' => $bank['id']]);
        } else {
            $data['uid'] = $uid;
            $data['create_time'] = time();
            $res = Bank::insert($data);
            User::update(['bind_card' => 1], ['id' => $uid]);
        }
        if ($res) {
            $this->result(true);
        } else
            $this->result(false, '操作失败');
    }

    //申请提现
    public function setWithData()
    {
        $price = $this->request->post('price', 0);
        $pass = $this->request->post('pass', '', 'trim');
        $web_time = $this->request->post('web_time', '', 'trim');
        $type = $this->request->post('type', 0, 'trim');
        if (!$price || !$pass || !$web_time)
            $this->result(false, '参数有误');
        if ($web_time) {
            $web_time = strtotime($web_time);
            $diff_time = time() - $web_time;
        } else {
            $web_time = 0;
            $diff_time = 0;
        }
        $open_date = $this->config['system_basic']['with_open_time'] ?? '';
        $close_date = $this->config['system_basic']['with_close_time'] ?? '';
        $start_time = strtotime($open_date);
        $close_time = strtotime($close_date);
        if ($start_time) {
            $start_time -= $diff_time;
            if ($start_time > $web_time)
                $this->result(false, '允许提现时间为：', ['var' => $open_date . ' - ' . $close_date]);
        }
        if ($close_time) {
            $close_time -= $diff_time;
            if ($close_time < $web_time)
                $this->result(false, '允许提现时间为：', ['var' => $open_date . ' - ' . $close_date]);
        }
        $uid = $this->request->user['id'];
        $user_info = User::alias('u')->leftJoin('mod_level l', 'u.level_id=l.id')->where(['u.id' => $uid])
            ->field('u.credit_score,u.deal_pass,u.balance,u.freeze_balance,u.status,u.order_total,l.withdraw_min,l.withdraw_max,l.withdraw_rate,l.order_num')->find();
        if ($user_info['status'] != 1)
            $this->result(false, '该账号被禁用了，请联系客服');
        if ($user_info['deal_pass'] != $pass)
            $this->result(false, '提款密码错误');
        if ($user_info['credit_score'] < 100)
            $this->result(false, '信用分低于100');
        if ($user_info['order_total'] < $user_info['order_num'])
            $this->result(false, '限制-未完成指定单数-进度为', ['var' => $user_info['order_total'] . '/' . $user_info['order_num']]);
        if ($price < $user_info['withdraw_min'])
            $this->result(false, '提现金额小于', ['var' => $user_info['withdraw_min']]);
        if ($price > $user_info['withdraw_max'])
            $this->result(false, '提现金额大于', ['var' => $user_info['withdraw_max']]);
        $fee = round($price * $user_info['withdraw_rate'], 2);//手续费
        $real_price = round($price + $fee, 2);
        if ($real_price > $user_info['balance'])
            $this->result(false, '提现金额大于可用余额');
        $bank_info = Bank::where(['uid' => $uid,'type'=>$type])->field('id')->find();
        if (!$bank_info)
            $this->result(false, '请先完善银行信息');
        Db::startTrans();
        try {
            $data['uid'] = $uid;
            $data['bank_id'] = $bank_info['id'];
            $data['price'] = $price;
            $data['fee'] = $fee;
            $data['price_pre'] = $user_info['balance'];
            Withdraw::create($data);
            User::where(['id' => $uid])->inc('freeze_balance', $real_price)->dec('balance', $real_price)->update();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('提现提交失败-' . $e->getMessage() . ":" . $e->getLine());
            $this->result(false, '系统繁忙，请重试');
        }
        $this->result(true);
    }

    //申请充值
    public function setRegData()
    {
        $price = $this->request->post('price', 0);
        // $pass = $this->request->post('pass', '', 'trim');
        $web_time = $this->request->post('web_time', '', 'trim');
        $bank_id = $this->request->post('bank_id', '', 'trim');
        $proof = $this->request->post('proof', '', 'trim');  // NEW: Accept proof image path
        
        if (!$price || !$web_time || !$bank_id)
            $this->result(false, '参数有误');
        
        // Validate proof is provided
        if (!$proof)
            $this->result(false, '请上传支付凭证');
        
        if ($web_time) {
            $web_time = strtotime($web_time);
            $diff_time = time() - $web_time;
        } else {
            $web_time = 0;
            $diff_time = 0;
        }
        $uid = $this->request->user['id'];
        $user_info = User::alias('u')->leftJoin('mod_level l', 'u.level_id=l.id')->where(['u.id' => $uid])
            ->field('u.credit_score,u.deal_pass,u.balance,u.freeze_balance,u.status,u.order_total,l.withdraw_min,l.withdraw_max,l.withdraw_rate,l.order_num,l.charge_min,l.charge_max')->find();
        if ($user_info['status'] != 1)
            $this->result(false, '该账号被禁用了，请联系客服');


        if($user_info['charge_min']>=1 && $price<$user_info['charge_min']){
            $this->result(false, '充值限制最少是:'.$user_info['charge_min']);
        }
        if($user_info['charge_max']>=1 && $price>$user_info['charge_max']){
            $this->result(false, '充值限制最多是:'.$user_info['charge_max']);
        }

        $bank_info = BankSys::where(['id' => $bank_id])->find();
        if (!$bank_info)
            $this->result(false, '银行信息不存在');
        Db::startTrans();
        try {
            $data['uid'] = $uid;
            $data['bank_id'] = $bank_info['id'];
            $data['price'] = $price;
            $data['fee'] = 0;
            $data['price_pre'] = $user_info['balance'];
            $data['proof'] = $proof;  // NEW: Store proof image path
            Reg::create($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('充值提交失败-' . $e->getMessage() . ":" . $e->getLine());
            $this->result(false, '系统繁忙，请重试');
        }
        $this->result(true);
    }

    //充值列表
    public function getRegList()
    {
        $uid = $this->request->user['id'];
        $web_time = $this->request->post('web_time', '', 'trim');
        if ($web_time) {
            $diff_time = time() - $web_time;
        } else {
            $diff_time = 0;
        }
        $page = $this->request->post('page', 1, 'intval');
        $list = Db::name('Reg')->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', $item['create_time'] - $diff_time);
            if ($item['handle_time'])
                $item['handle_time'] = date('Y-m-d H:i:s', $item['handle_time'] - $diff_time);
        }
        $this->result(true, '操作成功', $list['data'], ['total' => $list['total'], 'last_page' => $list['last_page']]);
    }

    //提现列表
    public function getWithList()
    {
        $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 = Db::name('Withdraw')->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', $item['create_time']);
            if ($item['handle_time'])
                $item['handle_time'] = date('Y-m-d H:i:s', $item['handle_time'] - $diff_time);
        }
        $this->result(true, '操作成功', $list['data'], ['total' => $list['total'], 'last_page' => $list['last_page']]);
    }

    //钱包记录列表
    public function getWalletList()
    {
        $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 = Db::name('WalletLog')->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', $item['create_time'] - $diff_time);
            if ($item['status'] == 2)
                $item['price'] = -$item['price'];
            $item['price_after'] = $item['price_pre'] + $item['price'];
            $item['title'] = '';
            if ($item['type'] == 1) {
                $item['title'] = Lang::get('充值余额');
            } elseif ($item['type'] == 2) {
                $item['title'] = Lang::get('提现');
            } elseif ($item['type'] == 3) {
                $info = Db::name('Goods')->where(['id' => $item['extra_id']])->field('name')->find();
                $item['title'] = Lang::get('生成订单') . $info['name'] ?? '';
            } elseif ($item['type'] == 4) {
                $info = Db::name('Goods')->where(['id' => $item['extra_id']])->field('name')->find();
                $item['title'] = Lang::get('交易佣金') . $info['name'] ?? '';
            } elseif ($item['type'] == 5) {
                if ($item['explain'][0] == 1) {
                    $item['title'] = Lang::get('一级返佣');
                } elseif ($item['explain'][0] == 2) {
                    $item['title'] = Lang::get('二级返佣');
                } elseif ($item['explain'][0] == 2) {
                    $item['title'] = Lang::get('三级返佣');
                } elseif ($item['explain'][0] == 2) {
                    $item['title'] = Lang::get('四级返佣');
                } else {
                    $item['title'] = Lang::get('五级返佣');
                }
            } elseif ($item['type'] == 6) {
                $item['title'] = Lang::get('等级购买升级至') . $item['extra_id'];
            } elseif ($item['type'] == 7) {
                $item['title'] = Lang::get('等级升级奖励');
            } elseif ($item['type'] == 8) {
                $info = Db::name('Goods')->where(['id' => $item['extra_id']])->field('name')->find();
                $item['title'] = Lang::get('返还本金') . $info['name'] ?? '';
            } elseif ($item['type'] == 9) {
                $item['title'] = Lang::get('当前余额');
            }
        }
        $this->result(true, '操作成功', $list['data'], ['total' => $list['total'], 'last_page' => $list['last_page']]);
    }

    //上传支付凭证
    public function uploadProof()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            Log::error('支付凭证上传失败-文件数据为空');
            $this->result(false, '文件数据为空');
            return;
        }
        
        try {
            // Validate file
            try {
                validate(['image' => 'fileSize:10485760|fileExt:jpg,png,gif,jpeg'])
                    ->check(['image' => $file]);
            } catch (\think\exception\ValidateException $ve) {
                Log::error('支付凭证上传失败-验证异常: ' . $ve->getMessage());
                $this->result(false, '验证-' . $ve->getMessage());
                return;
            }
            
            $file_path = '/uploads/' . date('Y/m/');
            $save_path = root_path() . 'public' . $file_path;
            
            // Normalize path separators
            $save_path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $save_path);
            
            // Create directory if not exists
            if (!is_dir($save_path)) {
                $mkdir_result = @mkdir($save_path, 0755, true);
                if (!$mkdir_result && !is_dir($save_path)) {
                    $error_msg = '目录创建失败: ' . $save_path . ' | Error: ' . error_get_last()['message'];
                    Log::error('支付凭证上传失败-' . $error_msg);
                    $this->result(false, '目录创建失败，请联系管理员');
                    return;
                }
            }
            
            // Check if directory is writable
            if (!is_writable($save_path)) {
                $error_msg = '目录不可写: ' . $save_path;
                Log::error('支付凭证上传失败-' . $error_msg);
                $this->result(false, '目录不可写，请联系管理员');
                return;
            }
            
            // Get file name
            try {
                $file_md5 = $file->md5();
                $file_ext = strtolower($file->getOriginalExtension());
                $file_name = $file_md5 . '.' . $file_ext;
            } catch (\Exception $nameE) {
                Log::error('支付凭证上传失败-文件名生成失败: ' . $nameE->getMessage());
                $this->result(false, '文件处理失败: ' . $nameE->getMessage());
                return;
            }
            
            // Upload to local server
            try {
                $info = $file->move($save_path, $file_name);
                if ($info) {
                    $this->result(true, 'Upload successful', ['file' => $file_path . $file_name]);
                } else {
                    $error = method_exists($file, 'getError') ? $file->getError() : null;
                    $error_msg = '文件移动失败: ' . ($error ?: '未知错误');
                    Log::error('支付凭证上传失败-' . $error_msg . ' | Path: ' . $save_path . ' | File: ' . $file_name);
                    $this->result(false, $error_msg);
                }
            } catch (\think\exception\HttpResponseException $httpE) {
                // This is thrown by $this->result() - re-throw it (this is the normal response)
                throw $httpE;
            } catch (\think\file\exception\FileException $fileE) {
                $error_msg = '文件异常: ' . $fileE->getMessage();
                Log::error('支付凭证上传失败-' . $error_msg . ' | Line: ' . $fileE->getLine() . ' | File: ' . $fileE->getFile());
                $this->result(false, '文件保存失败: ' . $fileE->getMessage());
            } catch (\Exception $moveE) {
                $error_msg = '文件移动异常: ' . $moveE->getMessage() . ' | Line: ' . $moveE->getLine() . ' | Class: ' . get_class($moveE);
                Log::error('支付凭证上传失败-' . $error_msg . ' | Trace: ' . $moveE->getTraceAsString());
                $this->result(false, '文件保存失败: ' . ($moveE->getMessage() ?: get_class($moveE)));
            }
        } catch (\think\exception\ValidateException $e) {
            $error_msg = '验证错误: ' . $e->getMessage();
            Log::error('支付凭证上传失败-' . $error_msg);
            $this->result(false, '验证-' . $e->getMessage());
        } catch (\think\exception\HttpResponseException $e) {
            // This is thrown by $this->result() - re-throw it
            throw $e;
        } catch (\Exception $e) {
            $error_msg = $e->getMessage() ?: '未知异常';
            $error_file = $e->getFile();
            $error_line = $e->getLine();
            $error_class = get_class($e);
            Log::error('支付凭证上传失败-' . $error_msg . ' | Line: ' . $error_line . ' | File: ' . basename($error_file) . ' | Class: ' . $error_class);
            // Return actual error for debugging
            $this->result(false, '上传异常: ' . ($error_msg ?: $error_class . ' at line ' . $error_line));
        }
    }

}
