<?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;

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

    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('staff/changepassword',compact('data'));
    }

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

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

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

    function WalletTopup(Request $request)
    {
        if($_POST){
            $request->validate([
                'user' => 'required',
                'amount' => ['required', 'numeric', 'min:1'],
                'remark' => 'required',
            ]); 

            $Authuser = Auth::user();

            $userid = $request['user'];
            $amount = $request['amount'];
            $remark = $request['remark'];

            WalletTopup::create([
                'userId' => $userid,
                'amount' => $amount,
                'requestedBy' => $Authuser->name,
                'requestedRemark' => $remark,  
                'status' => "PENDING",      
                'created_by' => $Authuser->id,
                'IpAddress' => $request->ip(),
            ]);

            return redirect()->route('/staff/wallet-topup-request')->with('success','Wallet topup has been submited successfully.');
        }
        $users = User::orderBy('id','desc')->whereNotIn('user_type',[0,2])->get();
        return view('staff/wallet-topup',compact('users'));
    }

    function WalletTopupRequest(Request $request)
    {
        if($_POST){                 
            $Authuser = Auth::user();

            $status = $request['status'];
            $utr = $request['utr'];
            $requestId = $request['requestId'];
            $remark = $request['remark'];
            $mpin = $request['mpin'];

            $getData = WalletTopup::findOrFail($requestId);

            $Authuser = Auth::user();
            if (Hash::check($mpin, $Authuser->lpin)) {

            }else{
                return redirect()->route('/staff/wallet-topup-request')->with('success','Invalid M-PIN. Please enter valid M-PIN');
                die;
            }

            if($status == "DENIED"){

                $data = [
                    'approvedBy'=>$Authuser->name,
                    'approvedRemark'=>$remark,
                    'status'=>$status,
                ];
                $getData->update($data);
                return redirect()->route('/staff/wallet-topup-request')->with('success','Wallet topup has been denied successfully.');
            }
            
            if($status == "APPROVED"){

                $checkutr = WalletTopup::where("utr",$utr)->get();
                
                if(count($checkutr) != 0){
                    return redirect()->route('/staff/wallet-topup-request')->with('success','this utr is already used please check.');
                }
                $userId = $getData->userId;
                $amount = $getData->amount;
                $openBal = $getData->wallet;
                $getCharge = PlatformCharge::where("userId",$userId)->first();

                $charge = $getCharge->charge;
                
               
                $gst = $getCharge->gst;
                if($charge == ""){
                    $charge = 2;
                }
                if($gst == ""){
                    $gst = 18;
                }                               
                $calCharge = $amount*$charge/100;
                $calGst = $calCharge*$gst/100;
                $totalCharge = $calCharge+$calGst;
                $totalAddAmount = $amount-$totalCharge;
                $data = [
                    'charge'=>$calCharge,
                    'gst'=>$calGst,
                    'totalAmount'=>$totalAddAmount,
                    'utr'=>$utr,
                    'approvedBy'=>$Authuser->name,
                    'approvedRemark'=>$remark,
                    'status'=>$status,
                ];
                $getData->update($data);

                $ipAddress = $request->ip();
                $txn_id = rand(12312,99099).Carbon::now()->timestamp;

                $user = User::findOrFail($userId);
                $openBal = $user->wallet;

                $closeBal = $openBal + $totalAddAmount;
                $UserInstance = new User();
                $UserInstance->addFund($userId,$totalAddAmount);
                $remark = "WALLET TOP UP BY AMOUNT ".$amount;
                UserTransaction::create([
                    'userId' => $userId,
                    'txnId' => $txn_id,
                    'orderId' => $txn_id,
                    'type' => "CREDIT",
                    'operator' => "WALLETTOPUP", 
                    'openBalance' =>$openBal,
                    'amount' => $totalAddAmount,
                    'walletBalance' =>$closeBal, 
                    'credit' =>$totalAddAmount, 
                    'debit' =>0,   
                    'remark' => $remark,   
                    'status'=>"SUCCESS", 
                    'requestIp' => $ipAddress,          
                    'created_by' => $Authuser->id,
                ]); 
                return redirect()->route('/staff/wallet-topup-request')->with('success','Wallet topup has been approved successfully.');
            }
        }        
        $today = Carbon::today();
        $WalletTopup = new WalletTopup();        
        $walletTopup = $WalletTopup->getWalletData();   
        $users = User::orderBy('id','desc')->whereNotIn('user_type',[0,2])->get();
        return view('staff/wallet-topup-request',compact('walletTopup','users'));
    }

    public function WalletTopupSearch(Request $request)
    {
        if($_POST){
            $user = $request['user'];
            $status = $request['status'];
            $date = $request['date'];

            $WalletTopup = new WalletTopup();        
            $walletTopup = $WalletTopup->getWalletDataSearch($user,$status,$date); 
            $users = User::orderBy('id','desc')->whereNotIn('user_type',[0,2])->get();
            return view('staff/wallet-topup-request',compact('walletTopup','users'));
        }
    }

    public function WalletTopupReport()
    {
        $today = Carbon::today();
        $walletTopup = WalletTopup::whereDate('created_at', $today)->where('status',"APPROVED")->orderBy('id','desc')->get();
        $todayTopUp = WalletTopup::whereDate('created_at', $today)->where('status',"APPROVED")->sum('totalAmount');
        $totalTopUp = WalletTopup::where('status',"APPROVED")->sum('totalAmount');
        return view('staff/wallet-topup-report',compact('walletTopup','totalTopUp','todayTopUp'));
    }

    public function topupReportDataExport(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];
        $submit = $request['submit'];
        if($submit == "EXPORT"){

            $selectedColumns = ['wallet_topups.amount','wallet_topups.utr','wallet_topups.IpAddress','wallet_topups.created_at','users.name','wallet_topups.approvedBy','wallet_topups.status'];
            $query = WalletTopup::whereDate('wallet_topups.created_at', $date)->select($selectedColumns)->join('users', 'wallet_topups.userId', '=', 'users.id');
            $data = $query->get();

            $filename = 'wallet_topup_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("Date","User","Amount", "Utr","Status","approvedBy","IP"); 									
            fputcsv($file,$header); 

            foreach($data as $row){
                $created_at = $row->created_at;
                $name = $row->name;
                $amount = $row->amount;   
                $charge = $row->charge;
                $gst = $row->gst;   
                $totalAmount = $row->totalAmount;
                $utr = $row->utr;   
                $status = $row->status;
                $approvedBy = $row->approvedBy;
                $ip = $row->IpAddress;

                // Write to file 
                $users_arr = array($created_at,$name,$amount,$utr,$status,$approvedBy,$ip);
                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();     
        }

        if($submit == "VIEW")
        {
            $today = Carbon::today();
            $walletTopup = WalletTopup::whereDate('created_at', $date)->where('status',"APPROVED")->orderBy('id','desc')->get();
            $todayTopUp = WalletTopup::whereDate('created_at', $date)->where('status',"APPROVED")->sum('amount');
            $totalTopUp = WalletTopup::where('status',"APPROVED")->sum('amount');
            return view('staff/wallet-topup-report',compact('walletTopup','totalTopUp','todayTopUp'));
        }
    }

    public function PendingTrancations(Request $request)
    {
        $today = Carbon::today();
        if($_POST){
            $status = "PENDING";
            $date = $request['txndate'];
            $PayoutModel = new PayoutModel();        
            $PayoutData = $PayoutModel->getPendingtDataSearch($status,$date); 
            return view('staff/pendingTxn',compact('PayoutData','today'));
        }

        return view('staff/pendingTxn',compact('today'));
    }

    function PendingTrancationsCheck(Request $request)
    {
        $referenceNumber = $request['txnId'];
        $checkTxn = PayoutModel::where("txnId",$referenceNumber)->get()->toArray();
        //print_r($checkTxn);
        if(count($checkTxn) == 0){
           echo "Transation not found";die("sssw");
        }

        $userID = $checkTxn[0]['userId'];
        $orderId = $checkTxn[0]['orderId'];
        $getUser = User::where("id",$userID)->first();
        $user_token = $getUser->user_token;

        $datasend = ["referenceNumber" => $orderId];
        $payload = json_encode($datasend);

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://dashboard.seospay.in/api/v1/new/checkstatus',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>$payload,
        CURLOPT_HTTPHEADER => array(
            'Authorization:'.$user_token,
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);   
        
        $data = json_decode($response,TRUE);
        echo $data['message'];

    }

    public function checkPendingStatus(Request $request)
    {
        if($_POST)
        {
            $today = $request['txndate'];
            $PayoutData = PayoutModel::whereDate('created_at', $today)->where('status',"PENDING")->limit(100)->orderBy('id', 'ASC')->get();
      
            foreach($PayoutData as $data)
             {
                $sendData['referenceNumber'] = $data->orderId;
                $send = json_encode($sendData);
               
              $this->hitCheckStatus($send);
            }
            
           }

        return view('staff/checkstatus');
    }

    function hitCheckStatus($data){

        $header = array(
            'Content-Type:application/json',
            'Authorization: c584ead917cf964b6fa6145aeff7c0d2f3f98ce1'
        );
    
        $curl = curl_init();
    
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://dashboard.seospay.in/api/new/checkstatus",
            CURLOPT_RETURNTRANSFER => false,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => $header
        ]);
    
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            $error = curl_error($curl);
            echo "cURL Error: " . $error;
        }
        // Close cURL session
        curl_close($curl);
        // Return the response
        echo $response;
    }

    public function whiteListedAccount(Request $request)
    {
        $users = User::orderBy('id','desc')->whereNotIn('user_type',[0,2])->get();
        $BankAccount = [];// BankAccount::where('userId',$userId)->get();
        if($_POST){
            $user = $request['user'];
            $BankAccount = BankAccount::where('userId',$user)->get();
            return view('staff/whitelisted-account',compact('users','BankAccount'));
            die;
        }
        return view('staff/whitelisted-account',compact('users','BankAccount'));
    }

    public function addBankAccount(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $users = User::orderBy('id','desc')->whereNotIn('user_type',[0,2])->get();
        if($_POST)
        {
            $request->validate([
                'benename' => 'required',                
                'beneaccount' => 'required',
                'ifsccode' => 'required',                
                'pancard' => 'required',
                'aadhaarfront' => 'required',                
                'aadhaarback' => 'required',
                'cancelcheque' => 'required',                
            ]);

            $file = $request->file('pancard');
            $extenstion = $file->getClientOriginalExtension();
            $pancard = "PAN".time().'.'.$extenstion;
            $file->move(public_path('uploads'), $pancard);

            $file = $request->file('aadhaarfront');
            $extenstion = $file->getClientOriginalExtension();
            $aadhaarfront = "aaf".time().'.'.$extenstion;
            $file->move(public_path('uploads'), $aadhaarfront);

            $file = $request->file('aadhaarback');
            $extenstion = $file->getClientOriginalExtension();
            $aadhaarback = "aab".time().'.'.$extenstion;
            $file->move(public_path('uploads'), $aadhaarback);

            $file = $request->file('cancelcheque');
            $extenstion = $file->getClientOriginalExtension();
            $cancelcheque = "cccs".time().'.'.$extenstion;
            $file->move(public_path('uploads'), $cancelcheque);

            BankAccount::create([
                'userId' =>$request['user'],
                'beneName' => $request['benename'],
                'beneAccount' => $request['beneaccount'],
                'beneIfsc' => $request['ifsccode'],
                'pancard' => $pancard,
                'addhaarFront' => $aadhaarfront,
                'addhaarBank' => $aadhaarback,
                'cancelCheque' => $cancelcheque,          
            ]);

            return redirect()->route('/staff/add-bank-account')->with('success','bank added successfully.');
        }
        return view('staff/addbankaccount',compact('users'));
    }
    
    public function updateaccountstatus(Request $request){
        
         $accountId = $request->input('accountId');
          $bankAccount = BankAccount::find($accountId);

        if (!$bankAccount) {
            return response()->json(['success' => false, 'message' => 'Bank account not found.'], 404);
        }

      
        $bankAccount->status = 1;
        $bankAccount->save();

        return response()->json(['success' => true, 'message' => 'Status updated successfully.']);
    }
    
}
