<?php

namespace App\Http\Controllers\BMControllers;
use EloquentBuilder;
use Illuminate\Http\Request;
use Auth;
use Hash;
use App\Models\bmmodels\ClientBatch;
use App\Models\bmmodels\CustomerGroup;
use App\Models\bmmodels\AuditLog;
use App\Models\bmmodels\CustomerClientPayment;
use Exception;
use ErrorException;
use App\Imports\BMImports\ClientsBatchImport;
use Maatwebsite\Excel\Facades\Excel;

class ClientBatchController extends Controller
{
    //return view
    public function index(Request $request)
    {
        // try
        // {
            if(Auth::user()->user_type == 'organization_user')
            {
                //get logged in customer id
                $id = Auth::user()->customer_cust_id;/*latest('client_batch_id')->*/
                $batches = ClientBatch::where('client_batch_customer_id',$id)->get();
                $mygroups = CustomerGroup::where('customer_cust_id',$id)->get();
                $latest_batch = ClientBatch::where('client_batch_customer_id',$id)->where('client_batch_status',0)->pluck('client_batch_id');
                // dd($latest_batch);
                $query = ClientBatch::whereIn('client_batch_id',$latest_batch)->where('client_batch_status',0);
                $batches = EloquentBuilder::to($query, $request->all())->get();
                return view('bmviews.batch.index', compact('batches','id','mygroups'));
            }
            else
            {
                return redirect('/login')->with('failure','Access Denied. Please login to continue!');
            }

        // }
        // catch(Exception $e)
        // {
        //     abort(500, $e->getMessage());   
            
        // }
    }
    //get my batches
    public function getBatch()
    {
        if(Auth::user()->user_type == 'organization_user'){
             $id = Auth::user()->customer_cust_id;
            $data = ClientBatch::where('client_batch_customer_id',$id)->get();
        }
        elseif(Auth::user()->user_type == 'organization'){
             $id = Auth::user()->bulk_cust_id;
            $data = ClientBatch::where('client_batch_customer_id',$id)->get();
            
        }
        else {
            
            $data = ClientBatch::all();
            
        }
       
        return $data;
    }
    //impoort
    public function import(Request $request,$id) 
    {
        request()->validate([
            'file' => 'required|max:5000|mimes:xlsx,xls,csv'
        ]);
        $path = $request->file;
        //get the id of the loggedin user
        if(Auth::user()->user_type == 'organization_user'){
             $customer_user_id = Auth::user()->cust_user_id;
            
        }
        
        Excel::import(new ClientsBatchImport($id,$customer_user_id), $path);
        
        return redirect()->route('batch.index');
    }
    //pay batch
    public function payBatch(Request $request)
    {
        if(isset($_POST['batch']))
        {
            //get phone numbers to pay
            $batchclients = $request->client_batch_id;
            
            //pay
            $client_arr = [];
            foreach($batchclients as $batchclient)
            {
                $client = ClientBatch::find($batchclient);
                
                $pay = new CustomerClientPayment();
                $pay->customer_client_batch_id = $batchclient;
                $pay->client_pay_amount = $client->transfer_amount;
                $pay->client_type="B2C";
                $pay->client_pay_batch_id = $client->client_batch_id;
                $pay->customer_cust_id = $client->client_batch_customer_id;
                //update batch status
                $client->client_batch_status = 1;
                //log data
                $payLog = new AuditLog();
                $payLog->audit_module = "User";
                $payLog->audit_activity = "Batch payment of batch ID#: ".$client->client_batch_id ." initiated to batch payee ID# ".$pay->customer_client_batch_id." by user ID# " .Auth::user()->cust_user_id;
                $payLog->user_category = "User";
                $payLog->user_id = Auth::user()->cust_user_id;
                //write to csv
                $module="User";$activity=$payLog->audit_activity;$user_category='user';$user_id=$payLog->user_id;$datetime=date('Y-m-d h:i:s');
                $list = array (
                array($module, $activity,  $user_category,$user_id, $datetime),
                );
                
                $file = fopen("csvs/Audit.csv","a+");
                
                foreach ($list as $line) {
                fputcsv($file, $line);
                }
                
                fclose($file);
                // end write to csv
                $pay->save();
                $client->save();
                $payLog->save();
                array_push($client_arr,$pay);
            }
            // return response()->json($client_arr);
            return redirect()->back()->
            with('success',"Payment forwarded for approval");
        }

        else if(isset($_POST['selected']))
        {
            $request->validate([
                'client_batch_id'=>'required',
                ],
                [
                    'client_batch_id.required'=>'Please select atleast one field',
                    ]
                );
            //get phone numbers to pay
            $batchclients = $request->client_batch_id;
            
            //pay
            $client_arr = [];
            foreach($batchclients as $batchclient)
            {
                $client = ClientBatch::find($batchclient);

                $pay = new CustomerClientPayment();
                $pay->customer_client_batch_id = $batchclient;
                $pay->client_pay_amount = $client->transfer_amount;
                $pay->client_pay_batch_id = $client->client_batch_id;
                $pay->client_type="B2C";
                $pay->customer_cust_id = $client->client_batch_customer_id;
                //update batch status
                $client->client_batch_status = 1;
                //log data
                $payLog = new AuditLog();
                $payLog->audit_module = "User";
                $payLog->audit_activity = "Batch payment of batch ID#: ".$client->client_batch_id ." initiated to batch payee ID# ".$pay->customer_client_batch_id." by user ID# " .Auth::user()->cust_user_id;
                $payLog->user_category = "User";
                $payLog->user_id = Auth::user()->cust_user_id;
                //write to csv
                $module="User";$activity=$payLog->audit_activity;$user_category='user';$user_id=$payLog->user_id;$datetime=date('Y-m-d h:i:s');
                $list = array (
                array($module, $activity,  $user_category,$user_id, $datetime),
                );
                
                $file = fopen("csvs/Audit.csv","a+");
                
                foreach ($list as $line) {
                fputcsv($file, $line);
                }
                
                fclose($file);
                // end write to csv
                $pay->save();
                $client->save();
                $payLog->save();
                array_push($client_arr,$pay);
            }
            // return response()->json($client_arr);
            return redirect()->back()->
            with('success',"Payment forwarded for approval");
        }
    
    }
    //add to batch
    public function store(Request $request)
    {
        request()->validate([
            'client_phone' => 'required',
            'client_idno' => 'required',
            'client_name' => 'required',
            'transfer_amount' => 'required',
            'batch' =>'required',
        ]);
        //insert
        $batch = new ClientBatch();
        $batch->client_phone = $request->client_phone;
        $batch->client_idno = $request->client_idno;
        $batch->client_name = $request->client_name;
        $batch->transfer_amount = $request->transfer_amount;
        $batch->client_batch_id = $request->batch['client_batch_id'];
        $batch->client_batch_status = 0;
        $batch->client_batch_customer_id = $request->client_batch_customer_id;
        $batch->client_batch_customer_user_id = Auth::user()->cust_user_id;
        
        //log
        $batchLog = new AuditLog();
        $batchLog->audit_module = "User";
        $batchLog->audit_activity = "Batch payee of details: ".$batch ."added by user ID# " .Auth::user()->cust_user_id;
        $batchLog->user_category = "User";
        $batchLog->user_id = Auth::user()->cust_user_id;
        //write to csv
        $module="User";$activity=$batchLog->audit_activity;$user_category='user';$user_id=$batchLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv
        $batch->save();
        $batchLog->save();
        return $batch;
    }
    //edit  batch payee
    public function update(Request $request)
    {
        request()->validate([
            'client_phone' => 'required',
            'client_idno' => 'required',
            'client_name' => 'required',
            'transfer_amount' => 'required',
            'batch' =>'required',
        ]);
        //insert
        $batch = ClientBatch::find($request->id);
        $batch->client_phone = $request->client_phone;
        $batch->client_idno = $request->client_idno;
        $batch->client_name = $request->client_name;
        $batch->transfer_amount = $request->transfer_amount;
        $batch->client_batch_id = $request->batch['client_batch_id'];
        $batch->client_batch_status = $batch->client_batch_status;
        $batch->client_batch_customer_id = $request->client_batch_customer_id;
        //log
        $batchLog = new AuditLog();
        $batchLog->audit_module = "User";
        $batchLog->audit_activity = "Batch payee of details: ".$batch ."updated to " .$request. " by user ID# " .Auth::user()->cust_user_id;
        $batchLog->user_category = "User";
        $batchLog->user_id = Auth::user()->cust_user_id;
        //write to csv
        $module="User";$activity=$batchLog->audit_activity;$user_category='user';$user_id=$batchLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv
        
        $batch->save();
        $batchLog->save();
        return $batch;        
    }
    //delete from batch
    public function destroy($id)
    {
        $batch = ClientBatch::find($id);
        //log
        $batchLog = new AuditLog();
        $batchLog->audit_module = "User";
        $batchLog->audit_activity = "Batch payee of details: ".$batch ."deleted by user ID# " .Auth::user()->cust_user_id;
        $batchLog->user_category = "User";
        $batchLog->user_id = Auth::user()->cust_user_id;
        $batch->delete();
        $batchLog->save();
        //write to csv
        $module="User";$activity=$batchLog->audit_activity;$user_category='user';$user_id=$batchLog->user_id;$datetime=date('Y-m-d h:i:s');
        $list = array (
        array($module, $activity,  $user_category,$user_id, $datetime),
        );
        
        $file = fopen("csvs/Audit.csv","a+");
        
        foreach ($list as $line) {
        fputcsv($file, $line);
        }
        
        fclose($file);
        // end write to csv
        return $batch;   
    }
    //get my batches
    public function getMyBatch()
    {
        $id = Auth::user()->bulk_cust_id;
        $batches = ClientBatch::where('client_batch_customer_id',$id)->get();
        return view('bmviews.partials.filter-supervise',compact('batches'));
    }
}
