<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use App\Models\User;
use App\Models\UserCharge;
use App\Models\UserIp;
use App\Models\UserTransaction;
use App\Models\WalletTopup;
use App\Models\PlatformCharge;
use App\Models\PayoutModel;
use App\Models\BankAccount;
use Illuminate\Support\Facades\Session;
use Illuminate\Session\Store;

class SubAdmin extends Controller
{
    public function index()
    {   
        
        $usertransaction = UserTransaction::with('user')->orderBy('id','desc')->limit(5)->get();  
        $totalUsers = User::where('user_type',1)->count();
        $usersWithBalances = User::where('user_type',1)->sum('wallet');
        $today = Carbon::today();
        $status = ['SUCCESS','PENDING','PROCESSING'];
        $todayPayout = PayoutModel::whereDate('created_at', $today)->whereIn('status',$status)->sum('amount');
        $totalPayout = PayoutModel::whereIn('status',$status)->sum('amount');
        $todayTopUp = WalletTopup::whereDate('created_at', $today)->where('status',"APPROVED")->sum('amount');
        $totalTopUp = WalletTopup::where('status',"APPROVED")->sum('amount');
        return view('subadmin/dashboard',compact('usertransaction','totalUsers','usersWithBalances','todayPayout','totalPayout','todayTopUp','totalTopUp'));
    }

    public function changePassword(Request $request)
    {
        $data['content'] = "";
        if($_POST){
            $request->validate([
                'oldpassword' => 'required',
                'password' => 'required|min:8|confirmed',
                'password_confirmation' => 'required',
            ]);

            $user = Auth::user();

            if (Hash::check($request->oldpassword, $user->password)) {
                $user->update([
                    'password' => Hash::make($request->password)
                ]);

                return redirect()->route('logout')->with('success', 'Password has been changed successfully.Please login');
            } else {
                return redirect()->back()->withErrors(['oldpassword' => 'Current password is incorrect.']);
            }
        }
        return view('subadmin/changepassword',compact('data'));
    }

    function viewProfile()
    {
        return view('subadmin/view-profile');
    }

    function manageUsers()
    {
        $user = User::orderBy('id','desc')->whereNotIn('user_type',[0,2,3,4])->paginate(500);
        return view('subadmin/manage-user',compact('user'));
    }

    function manageUsersStatus(Request $request)
    {
        $id = $_POST['id'];
        $status = $_POST['status'];
        $type = $_POST['type'];

        if($status == "DEACTIVE"){
            $statusnew = 0;
        }else{
            $statusnew = 1;
        }
        $user = User::findOrFail($id);
        if($type == "API"){
            $data = ['api_status'=>$statusnew];
        }else if($type == "status"){
            $data = ['status'=>$statusnew];
        }else if($type == "TECHNICAL"){
            $data = ['tecnical_issue'=>$statusnew];
        }else if($type == "BYBANK"){
            $data = ['bank_deactive'=>$statusnew];
        }else if($type == "flipzik"){
            $data = ['flipzik'=>$statusnew];
        }else if($type == "iserveu"){
            $data = ['iserveu'=>$statusnew];
        }else{
            echo "No data has been updated.";
        die;
        }
        
        $user->update($data);
        echo "Status has been updated successfully";
        die;
    }

    public function payoutReport()
    {
        return view('subadmin/payoutreport');
    }

    public function payoutReportData(Request $request)
    {
        $start = $request['start'];
        $length = $request['length'];
        $date = $request['date'];
        $search_arr = $request['search'];
        $search = $search_arr['value'];
        $modelInstance = new PayoutModel();
        $getData = $modelInstance->getWalletDataAjax($start,$length,$date,$search);
        $totalRecords = PayoutModel::count();//$getData->count(); 
        $Data = $getData->get();

        $response = [
            'draw' => $request['draw'],
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $Data,
        ];
        return response()->json($response);
    }

    public function payoutReportDataExport(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];
        $data = PayoutModel::whereDate('created_at', $date)->where('userId',$userId)->orderBy('id','desc')->get();

        $selectedColumns = ['payout_transactions.orderId','payout_transactions.txnId','payout_transactions.amount','payout_transactions.charge','payout_transactions.gst','payout_transactions.totalAmount','payout_transactions.beneName','payout_transactions.beneAccount','payout_transactions.beneIfsc','payout_transactions.utr','payout_transactions.status','payout_transactions.created_at','users.name'];
        $query = PayoutModel::whereDate('payout_transactions.created_at', $date)->select($selectedColumns)->join('users', 'payout_transactions.userId', '=', 'users.id');
        $data = $query->get();

        $filename = 'Payout_txn_'.$date.'.csv';
        $file = fopen($filename,"w");

        // Header row - Remove this code if you don't want a header row in the export file.
        $header = array("OrderId","User","Transaction Id","UTR","Name", "Account Number", "Ifsc","Amount","Charge","Gst","Net Amount","Status","Date"); 				
        fputcsv($file,$header); 

        foreach($data as $row){
            $OrderId = $row->orderId;
            $name = $row->name;
            $txnid = $row->txnId;
            $utr = $row->utr;   
            $beneName = $row->beneName;
            $beneAccount = $row->beneAccount;
            $beneIfsc = $row->beneIfsc;
            $amount = $row->amount;   
            $charge = $row->charge;
            $gst = $row->gst;   
            $totalAmount = $row->totalAmount;
            $status = $row->status;   
            $created_at = $row->created_at;

            // Write to file 
            $users_arr = array($OrderId,$name,$txnid,$utr, $beneName, $beneAccount, $beneIfsc,$amount,$charge,$gst,$totalAmount,$status,$created_at);
            fputcsv($file,$users_arr); 
        }

        fclose($file);
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/csv; ");

        readfile($filename);

        // deleting file
        unlink($filename);
        exit();     
    }

    function walletReport()
    {
        //$usertransaction = UserTransaction::with('user')->orderBy('id','desc')->paginate(10);    
        return view('subadmin/walletreport');
    }

    public function walletReportData(Request $request)
    {
        $start = $request['start'];
        $length = $request['length'];
        $date = $request['date'];
        $search_arr = $request['search'];
        $search = $search_arr['value'];
        $modelInstance = new UserTransaction();
        $getData = $modelInstance->getWalletDataAjax($start,$length,$date,$search);
        $totalRecords = UserTransaction::count();//$getData->count(); 
        $Data = $getData->get();
        $response = [
            'draw' => $request['draw'],
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $Data,
        ];
        return response()->json($response);
    }

    public function walletReportDataExport(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];        

        $selectedColumns = ['user_transactions.orderId','user_transactions.type','user_transactions.openBalance','user_transactions.amount','user_transactions.walletBalance','user_transactions.remark','user_transactions.created_at','user_transactions.status','users.name'];
        $query = UserTransaction::whereDate('user_transactions.created_at', $date)->select($selectedColumns)->join('users', 'user_transactions.userId', '=', 'users.id');
        $data = $query->get();

        $filename = 'wallet_txn_'.$date.'.csv';
        $file = fopen($filename,"w");

        // Header row - Remove this code if you don't want a header row in the export file.
        $header = array("Type","Date","OrderId","User", "Descrption", "Open Balance","Amount","Wallet balance","Status"); 
        fputcsv($file,$header); 

        foreach($data as $row){
            $type = $row->type;
            $created_at = $row->created_at;
            $orderId = $row->orderId;
            $name = $row->name;   
            $remark = $row->remark;
            $openBalance = $row->openBalance;
            $amount = $row->amount;
            $walletBalance = $row->walletBalance;   
            $status = $row->status;

            // Write to file 
            $users_arr = array($type, $created_at,$orderId, $name,$remark, $openBalance, $amount,$walletBalance,$status);
            fputcsv($file,$users_arr); 
        }

        fclose($file);
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/csv; ");

        readfile($filename);

        // deleting file
        unlink($filename);
        exit();        							
    }
    
     function addUser(Request $request)
    {
        if($_POST)
        {
            $request->validate([
                'name' => 'required',
                'mobile' => 'required|unique:users,mobile|regex:/^[6-9]\d{9}$/',
                'email' => 'required|email|unique:users,email',
                'password' => 'required',
                'pancard' => 'required|unique:users,pancard|regex:/^([A-Z]){5}([0-9]){4}([A-Z]){1}$/',
                'aadhaar' => 'required|unique:users,aadhaar_card|regex:/^\d{12}$/',
                'company' => 'required',
                'address' => 'required',
                'city' => 'required',
                'state' => 'required',
                'pincode' => 'required',
            ]);
            $user = Auth::user();
            $user_key = bin2hex(random_bytes(6));
            $user_token = bin2hex(random_bytes(20));
            User::create([
                'name' => $request['name'],
                'email' => $request['email'],
                'mobile' => $request['mobile'],
                'password' => Hash::make($request['password']),
                'aadhaar_card' => $request['aadhaar'],
                'pancard' => $request['pancard'],
                'address' => $request['address'],
                'city' => $request['city'],
                'state' => $request['state'],
                'pincode' => $request['pincode'],
                'company_name'=>$request['company'],
                'user_key'=>$user_key,
                'user_token'=>$user_token,
                'status' => 1,
                'api_status' => 1,
                'user_type' =>1,
                'agent_id'=>$request['agent'],
                'created_by' => $user->id,            
            ]);
            
            return redirect()->route('subadmin/add-user')->with('success','User has been created successfully.');
        }
        $agent = User::orderBy('id','desc')->whereNotIn('user_type',[0,1,2,4])->get();
        return view('subadmin/add-user',compact('agent'));
    }

}