<?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\Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;


class Users extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user();
        $userId = $user->id;
        $usertransaction = UserTransaction::where('userId',$userId)->orderBy('id','desc')->limit(5)->get();  
        $totalTrades = UserTransaction::where('userId',$userId)->count();
        $usersBalances = $user->wallet;
        $today = Carbon::today();
        $status = ['SUCCESS','PENDING','PROCESSING'];


        $todayPayout = PayoutModel::whereDate('created_at', $today)->whereIn('status',$status)->where('userId',$userId)->sum('amount');
        $totalPayout = PayoutModel::whereIn('status',$status)->where('userId',$userId)->where('userId',$userId)->sum('amount');
        $todayTopUp = WalletTopup::whereDate('created_at', $today)->where('userId',$userId)->where('status',"APPROVED")->sum('amount');
        $totalTopUp = WalletTopup::where('status',"APPROVED")->where('userId',$userId)->sum('amount');
        
        return view('user/dashboard',compact('usertransaction','usersBalances','totalTrades','totalTopUp','totalPayout','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();

            //print_r($user);die();

            if (Hash::check($request->oldpassword, $user->password)) {
               // print_r("hello");die();
                $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('user/changepassword',compact('data'));
    }

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

    public function devSetting(){
        return view('user/settingdev');
    }

    function walletReport()
    {
        $user = Auth::user();
        $userId = $user->id;
        //$usertransaction = UserTransaction::where('userId',$userId)->orderBy('id','desc')->paginate(10);   
        $today = Carbon::today(); 
        return view('user/walletreport',compact('today'));
    }
    
    
    public function wallettopup(Request $request){
        if($_POST){
            $request->validate([
                'bankname' => 'required',
                'amount' => ['required', 'numeric', 'min:1'],
                'remark' => 'required',
                'slip' => 'required'
                
            ]); 
            
            $Authuser = Auth::user();

            $bankname = $request['bankname'];
            $amount = $request['amount'];
            $remark = $request['remark'];
           
          
            $file = $request->file('slip');
            $extenstion = $file->getClientOriginalExtension();
            $slip = "amountslip".time().'.'.$extenstion;
            $file->move(public_path('uploads'), $slip);
            
           
            
            WalletTopup::create([
                'bankname' =>$bankname,
                'userId' =>$Authuser->id,
                'paymentslip' => $slip,
                'amount' => $amount,
                'requestedBy' => $Authuser->name,
                'requestedRemark' => $remark,  
                'status' => "PENDING",      
                'created_by' => $Authuser->id,
            ]);

            return redirect()->route('/user/wallet-topup')->with('success','Wallet topup has been submited successfully.');
        }
       
        return view('user/wallet-topup');
    }

    public function walletReportData(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $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,$userId);
        $totalRecords = UserTransaction::where("userId",$userId)->count();//$getData->count(); 
        $Data = $getData->get();
        $response = [
            'draw' => $request['draw'],
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $Data,
        ];
        return response()->json($response);
    }

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

    public function payoutReportData(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $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,$userId);
        $totalRecords = PayoutModel::where("userId",$userId)->count();//$getData->count(); 
        $Data = $getData->get();

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

    public function walletTopupReport()
    {
        $today = Carbon::today();
        return view('user/wallet-topup-request',compact('today'));
    }

    public function walletTopupReportData(Request $request)
    {  
        
      
        $user = Auth::user();
        $userId = $user->id;
        $start = $request['start'];
        $length = $request['length'];
        $date = $request['date'];
        $search_arr = $request['search'];
        $search = $search_arr['value'];
        
        Log::info('Request Data:', [
        'start' => $start,
        'length' => $length,
        'date' => $date,
        'search' => $search,
        'userId' => $userId,
    ]);
        $modelInstance = new WalletTopup();
        $getData = $modelInstance->getWalletDataAjax($start,$length,$date,$search,$userId);
        $totalRecords = $getData->count(); 
        $Data = $getData->get();
        
       



        
         $response = [
            'draw' => $request['draw'],
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $totalRecords,
            'data' => $Data,
            
            
        ];
          //Log::info("Data fetched".$time);
       
        return response()->json($response);
    }

    public function walletReportDataExport(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];
        $data = UserTransaction::whereDate('created_at', $date)->where('userId',$userId)->orderBy('id','desc')->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", "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;   
            $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, $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();        							
    }

    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();

        // $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","Transaction Id","UTR","Name", "Account Number", "Ifsc","Amount","Charge","Gst","Net Amount","Status","Date"); 				
        // fputcsv($file,$header); 

        // foreach($data as $row){
        //     $OrderId = $row->orderId;
        //     $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, $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();     

        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];

        $formattedDate = $date . '%';

     
       
        $data = PayoutModel::where('created_at', 'LIKE', $formattedDate)
        ->where('userId', $userId)
        ->orderBy('id', 'desc')
        ->get();


   
        $directory = storage_path('app/reports');
        if (!File::exists($directory)) {
            File::makeDirectory($directory, 0755, true);
        }
    
        $filename = 'Payout_txn_'.$date.'.csv';
        $filePath = $directory . '/' . $filename;
        $file = fopen($filePath, "w");
    
        // Header row
        $header = array("OrderId", "Transaction Id", "UTR", "Name", "Account Number", "Ifsc", "Amount", "Charge", "Gst", "Net Amount", "Status", "Date");
        fputcsv($file, $header);
    
        foreach ($data as $row) {
            $OrderId = $row->orderId;
            $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, $txnid, $utr, $beneName, $beneAccount, $beneIfsc, $amount, $charge, $gst, $totalAmount, $status, $created_at);
            fputcsv($file, $users_arr);
        }
    
        fclose($file);
    
        return response()->download($filePath)->deleteFileAfterSend(true);
    }

    public function topupReportDataExport(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $date = $request['txndate'];
        $data = WalletTopup::whereDate('created_at', $date)->where('userId',$userId)->orderBy('id','desc')->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","Amount","Charge","Gst","Net Amount", "Utr","Status"); 									
        fputcsv($file,$header); 

        foreach($data as $row){
            $created_at = $row->created_at;
            $amount = $row->amount;   
            $charge = $row->charge;
            $gst = $row->gst;   
            $totalAmount = $row->totalAmount;
            $utr = $row->utr;   
            $status = "SUCCESS";

            // Write to file 
            $users_arr = array($created_at,$amount,$charge,$gst,$totalAmount,$utr,$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();     
    }

    public function apiDocs()
    {
        return view('user/apidocs');
    }

    public function addBankAccount(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        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' =>$user->id,
                'beneName' => $request['benename'],
                'beneAccount' => $request['beneaccount'],
                'beneIfsc' => $request['ifsccode'],
                'pancard' => $pancard,
                'addhaarFront' => $aadhaarfront,
                'addhaarBank' => $aadhaarback,
                'cancelCheque' => $cancelcheque,          
            ]);

            return redirect()->route('/user/add-bank-account')->with('success','bank added successfully.');
        }
        $bankdata = BankAccount::where('userId',$user->id)->get();
        return view('user/addbankaccount',compact('bankdata'));
    }

    public function userPayin()
    {
        return view('user/userpayin');
    }

    public function generatePaymentLink(Request $request)
    {
        $amount = $request['amount'];
        $txn_id = "SSPNP".rand(123121,990999).Carbon::now()->timestamp;

        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.seospay.in/api/new/v1/payin/genratePaymentLink',
        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 =>'{
            "Name": "payment",
            "referenceNumber": "'.$txn_id.'",
            "Email": "tt@gmail.com",
            "Phone": "9888888591",
            "Amount": "'.$amount.'"
        }
        ',
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiODU1OGZiM2I1MjQ1ZDQ1YzgyZjczNGI5NGZiY2QxZjM3YzM5NzM3ODk4OTMzNGE4MGRlMzM2ZWE0Y2ZlN2I0NDIwYjljZGY5MDI4NjJkYzkiLCJpYXQiOjE3MTAxNDI0NzMuNDUyNjQxOTYzOTU4NzQwMjM0Mzc1LCJuYmYiOjE3MTAxNDI0NzMuNDUyNjQ1MDYzNDAwMjY4NTU0Njg3NSwiZXhwIjoxNzEwNzQ3MjczLjQ1MDcxOTExODExODI4NjEzMjgxMjUsInN1YiI6IjIiLCJzY29wZXMiOltdfQ.dDks0CsLzspI-pcWSIBSXhpPG4-Z6en9r96JqVakHd5iqbyIntyNrBZjAGY-jbi4h2AugFwuiJjpDIe17fkJjI3AurOTgAW8oOHKgz87O7DarK-n2rshOXcynghfv35LJXuSr1cOWJWP3x_BkLKG5jSoX-C3amv087Ru0k0QIeMEF_8zDyopdwyE7Ks0XtmufTizvcoYqyJJkzSEgcx-xofDOiwZwOKrMeV0rPnuG1E2FK75_XahV4-plHLCqRPNqE-yn8v4i5xQTni9If-AV2rG87tHe5BlVaBXy-8oW4KFrvq_HNTYd0sk-NzWwYcTsrvhm923ncMecbOuvDSHHgCZcL-m7TaPikqq7N74WV1c0WgHXevVy_c6e9Oj3wSXxZFgRxIhrs9mAE6tXgacWnTYLryS4rLdE80jXJJXi_6XEzF1yAU8kEN9hcus7rzfxPhpxjJuwz-IP6aEvlPX8zco7qqzbMhX15BO7D3OCwOAmRJjgpttFn5ZVcHmWWlwTCIO1A4YGjEGTQqdB3CidbA_BsFz1Hd0GF983iIy1vcCwViYzOhIH2zRXgsdbZc25Mrp-3IvULytkIZ7wJfcYrdEK3gSQOps5ahrjjsyQfqeVZCFAphAt7aYYesmijgRW1pHriyDUV3GNFM7TcT5Gz0XcYFUKEYr2gG2zvvq9ao',
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $responseData = json_decode($response, true);

        if($responseData['responseCode'] == 200)
        {
            echo $responseData['data']['intentLink'];
        }else{
            alert("Please try after some time");
        }

    }

//     public function dmtlite(Request $request)
//     {

//       // Log::info($request);

    
//         if ($request->isMethod('post')) {
//             $validator = Validator::make($request->all(), [
//                 'AuthKey' => 'required|string',
//                 'token' => 'required',
//                 'AuthToken' => 'required|string',
//                 'AuthCode' => 'required|string',
//                 'name' => 'required|string',
//                 'accountNumber' => 'required|string',
//                 'mobileNumber' => 'required|numeric',
//                 'referenceNumber' => 'required|string|unique:payout_transactions,orderId',
//                 'transferAmount' => 'required|numeric',
//                 'transferMode' => 'required|string',
//             ]);
    
//             if ($validator->fails()) {
//                 return redirect()->back()->withErrors($validator)->withInput();
//             }
    
//             $requestData = [
//                 'name' => $request->input('name'),
//                 'accountNumber' => $request->input('accountNumber'),
//                 'mobileNumber' => $request->input('mobileNumber'),
//                 'referenceNumber' => $request->input('referenceNumber'),
//                 'transferAmount' => $request->input('transferAmount'),
//                 'transferMode' => $request->input('transferMode'),
//             ];
    
//                $payload = json_encode($requestData);
//                $token =  $request->input('token');
//                 $AuthKey = $request->input('AuthKey');
//                 $AuthToken = $request->input('AuthToken');
//                 $AuthCode = $request->input('AuthCode');

//                 $header = [
//                     'Authorization: Bearer ' . $token,
//                     'AuthKey: ' . $AuthKey,
//                     'AuthToken: ' . $AuthToken,
//                     'AuthCode: ' . $AuthCode,
//                     'Content-Type: application/json',
//                 ];

                
                

// $curl = curl_init();

// curl_setopt_array($curl, array(
//   CURLOPT_URL => 'https://api.seospay.tech/api/new/v1/payout/docashtransfer',
//   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 => $header,
// ));

// $response = curl_exec($curl);

// curl_close($curl);


//            // echo $response; 
    
//            $response = json_decode($response, true);

//            if (isset($response['status'])) {
//                if ($response['status'] == 'SUCCESS') {
//                    return redirect()->back()->with('success', [
//                        'message' => 'Transaction is Successful',
//                        'payout_ref' => $response['data']['payout_ref'],
//                        'bank_ref' => $response['data']['bank_ref'],
//                    ]);
//                } elseif ($response['status'] == 'FAILED') {
//                    return redirect()->back()->with('error', [
//                        'message' => 'Transaction Failed',
//                        'payout_ref' => $response['data']['payout_ref'],
//                        'bank_ref' => $response['data']['bank_ref'],
//                    ]);
//                } else {
//                    return redirect()->back()->with('pending', [
//                        'message' => 'Transaction is Pending',
//                        'payout_ref' => $response['data']['payout_ref'],
//                    ]);
//                }
//            } else {
//                return redirect()->back()->with('error', 'An error occurred.');
//            }
//        }
    
//         return view('user/dmtlite');
//     }
    
public function dmtlite(Request $request)
{
    if ($request->isMethod('post')) {
        $validator = Validator::make($request->all(), [
            'AuthKey' => 'required|string',
            'token' => 'required',
            'AuthToken' => 'required|string',
            'AuthCode' => 'required|string',
            'name' => 'required|string',
            'accountNumber' => 'required|string',
            'mobileNumber' => 'required|numeric',
            'referenceNumber' => 'required|string|unique:payout_transactions,orderId',
            'transferAmount' => 'required|numeric',
            'transferMode' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $requestData = [
            'name' => $request->input('name'),
            'accountNumber' => $request->input('accountNumber'),
            'mobileNumber' => $request->input('mobileNumber'),
            'referenceNumber' => $request->input('referenceNumber'),
            'transferAmount' => $request->input('transferAmount'),
            'transferMode' => $request->input('transferMode'),
        ];

        $payload = json_encode($requestData);
        $token = $request->input('token');
        $AuthKey = $request->input('AuthKey');
        $AuthToken = $request->input('AuthToken');
        $AuthCode = $request->input('AuthCode');

        $header = [
            'Authorization: Bearer ' . $token,
            'AuthKey: ' . $AuthKey,
            'AuthToken: ' . $AuthToken,
            'AuthCode: ' . $AuthCode,
            'Content-Type: application/json',
        ];

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.seospay.tech/api/new/v1/payout/docashtransfer',
            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 => $header,
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        $responseArray = json_decode($response, true);

        if ($responseArray['status'] == 'SUCCESS') {
            return redirect()->back()->with('success', [
                'message' => 'Transaction is Successful',
                'data' => [
                    'payout_ref' => $responseArray['data']['payout_ref'],
                    'bank_ref' => $responseArray['data']['bank_ref'],
                ]
            ]);
        } elseif ($responseArray['status'] == 'FAILED') {
            return redirect()->back()->with('error', [
                'message' => 'Transaction Failed',
                'data' => [
                    'payout_ref' => $responseArray['data']['payout_ref'] ?? '',
                    'bank_ref' => $responseArray['data']['bank_ref'] ?? '',
                ]
            ]);
        } else {
            return redirect()->back()->with('pending', [
                'message' => 'Transaction is Pending',
                'data' => [
                    'payout_ref' => $responseArray['data']['payout_ref'],
                ]
            ]);
        }
    }

    return view('user/dmtlite');
}
  
}
