<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;
use Excel;
use App\Imports\Senderidimport;
use Illuminate\Support\Facades\File;

class SenderIdController extends Controller
{
    public function index(){
        $senderid_arr = new Models\SenderId;
        // $senderid_arr = $senderid_arr->with('modified_by_info', 'network_info', 'created_by_info')->orderBy('senderid', 'ASC')->paginate(15);
        // dd($senderid_arr); 
        $data = [
            'page_title' => 'Sender IDs',
            // 'senderid_arr' => $senderid_arr,
            'current_user' => session('current_user')
        ];
        return view('senderid.index', $data);
    }
    public function getSenderIdsJson(Request $request)
    {
        #$this->log_query();
        $senderid_arr = \DB::table('sender_ids')
            ->join('staff_members AS staffcreate', 'staffcreate.id', '=', 'sender_ids.created_by')
            ->join('staff_members AS staffmodify', 'staffmodify.id', '=', 'sender_ids.last_modified_by')
            // ->join('network_operators', 'network_operators.id', '=', 'sender_ids.network_id')
            // ->join('clients', 'clients.id', '=', 'sender_ids.client_id')
            ->select('sender_ids.id', 'mno_name', 'supplier_name', 'sender_ids.senderid', 'sender_ids.status', 'sender_ids.remarks', 'staffcreate.name As createdBy','sender_ids.direct_mno', 'staffmodify.name AS modifiedBy')
            ->orderBy('sender_ids.senderid', 'ASC')
            ->paginate(15);

        if($request->has('keyword')){
            $queries = [];
            $keyword = $request->keyword;
            $queries['keyword'] = $keyword;
            $senderid_arr = \DB::table('sender_ids')
            ->join('staff_members AS staffcreate', 'staffcreate.id', '=', 'sender_ids.created_by')
            ->join('staff_members AS staffmodify', 'staffmodify.id', '=', 'sender_ids.last_modified_by')
            // ->join('network_operators', 'network_operators.id', '=', 'sender_ids.network_id')
            // ->join('clients', 'clients.id', '=', 'sender_ids.client_id')
            ->select('sender_ids.id',  'mno_name', 'supplier_name', 'sender_ids.senderid', 'sender_ids.status',  'sender_ids.remarks', 'staffcreate.name As createdBy', 'sender_ids.direct_mno', 'staffmodify.name AS modifiedBy')
            ->whereRaw("sender_ids.senderid LIKE '%$keyword%' OR sender_ids.status LIKE '%$keyword%' OR mno_name LIKE '%$keyword%' OR supplier_name LIKE '%$keyword%' OR staffcreate.name LIKE '%$keyword%' OR staffmodify.name LIKE '%$keyword%' OR sender_ids.direct_mno LIKE '%$keyword%'")
            ->orderBy('sender_ids.senderid', 'ASC')
            ->paginate(15)->appends($queries);
        }
        return response()->json($senderid_arr);
    }
    public function create()
    {
        #$network_arr = Models\NetworkOps::pluck('name','country');

        $networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS networkvalue, concat(name, " (", country, ")") AS network'))->orderBy('network')->get()->toArray();
        $network_arr = array_pluck($networks, 'network', 'networkvalue');
        $direct_mno_arr = ['YES' => 'YES', 'NO' => 'NO'];

        // dd($network_arr);
        #$network_arr = array_combine($network_arr, $network_arr);


        // $clients = Models\Client::pluck('name', 'name');
        $clients = \DB::table('clients')->Select(\DB::raw('concat(name, " (", country, ")") AS clientvalue, concat(name, " (", country, ")") AS client'))->orderBy('client')->get()->toArray();
        $client_arr = array_pluck($clients, 'client', 'clientvalue');
        $staffmembers = Models\StaffMember::pluck('name', 'id');
        #$status = ['Pending' => 'Pending', 'Inactive' => 'Inactive', 'Approved' => 'Approved'];
        #$status = ['Applied to MNO', 'Applied to Aggregator', 'Approved on MNO', 'Approved on Aggregator', 'Active', 'InActive'];
        $status = [
            'Applied to MNO' => 'Applied to MNO', 
            'Applied to Aggregator' => 'Applied to Aggregator', 
            'Approved on MNO' => 'Approved on MNO', 
            'Approved on Aggregator' => 'Approved on Aggregator', 
            'Active' => 'Active', 
            'Inactive' => 'InActive'
        ];

        $data = [
            'page_title' => 'Create Sender ID',
            'network_arr' => $network_arr,
            'status' => $status,
            'clients' => $client_arr,
            'direct_mno_arr' => $direct_mno_arr,
            'staffmembers' => $staffmembers
        ];
        // dd($data);
        return view('senderid.create', $data);
    }
    public function showuploadform(){    
        $data = [
            'page_title' => 'Upload Sender IDs',
        ];
        return view('senderid.uploadbulk', $data);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'senderid' => 'required|max:11',
            'mno_name' => 'required_if:direct_mno,YES',
            'supplier_name' => 'required_if:direct_mno,NO',
            'status' => 'required',
            'remarks' => 'sometimes',
        ]);
        $check_duplicate = Models\SenderId::where('senderid', $request->senderid)                                
                                ->where('mno_name', $request->mno_name)
                                ->first();
       
        if($check_duplicate){
            return redirect()->back()->withInput()->withErrors("Sender ID already exist for " . $request->mno_name );
        }

        $senderid_arr = $request->except('_token');
        $senderid_arr['created_by'] = session('current_user.id');
        $senderid_arr['last_modified_by'] = session('current_user.id');
        $senderid_arr['remarks'] = $request->remarks ?? '';
        $senderid_arr['direct_mno'] = $request->direct_mno;


        // dd($senderid_arr);
        $result = Models\SenderId::create($senderid_arr);

        /*
        if ($request->direct_mno == 'NO') {
            $mno_world_wide = Models\Worldwidemno::find($request->network_id);
            // code... save in the network ops with status as non-direct ... user createOrUpdate method
            $network_ops_arr['name'] = $mno_world_wide->network;
            $network_ops_arr['country'] = $mno_world_wide->country;
            $network_ops_arr['name'] = $mno_world_wide->network;
            $network_ops_arr['direct_business'] = 'NO'; // $mno_world_wide->network;
            $result = Models\NetworkOps::updateOrCreate(['name' =>  $mno_world_wide->network, 'country' => $mno_world_wide->country, 'direct_business' => 'NO'], $network_ops_arr);
            $senderid_arr['network_id'] = $result->id;
        }
        //validate senderid with same client and same network 
        // $result = Models\SenderId::create($senderid_arr);
        $result = Models\SenderId::updateOrCreate([
            'network_id' =>  $senderid_arr['network_id'],
            'client_id' => $senderid_arr['client_id'], 
            'senderid' => $senderid_arr['senderid']
        ], $senderid_arr);
        */

        #save services this has been moved to the main client table
        //$retval = $this->store_services($request->services, $result->id);
        // dd('foo bar');
        Session::flash('success_message', 'Sender ID successfully added');
        return redirect(url('senderids'));
    }
    public function uploadstore(Request $request)
    {
        $request->validate([
            'senderid_file' => 'required|max:6000|mimes:xlx,xlsx',
        ]);


        $request->session()->put('current_user.rejected_rows_filename', '');

        // dump($request->all());
        $networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS networkvalue, concat(name, " (", country, ")") AS network'))->orderBy('network')->get()->toArray();
        
        $network_arr = array_pluck($networks, 'network', 'networkvalue');

        $clients = \DB::table('clients')->Select(\DB::raw('concat(name, " (", country, ")") AS clientvalue, concat(name, " (", country, ")") AS client'))->orderBy('client')->get()->toArray();
        $client_arr = array_pluck($clients, 'client', 'clientvalue');

        if (!$request->hasFile('senderid_file') && !$request->senderid_file->isValid() ) {
            Session::flash('error_message', 'File could not be loaded');
            return redirect()->back();
        }
        $file = $request->senderid_file;
        $filename = "erp_" . time() . str_random(6) . "." . $request->senderid_file->extension();
        $request->senderid_file->storeAs('general_files', $filename, 'public');

        $stored_file = public_path('documents/general_files/'.$filename);
        $extracted_arr = Excel::toArray(new Senderidimport, $stored_file);
        // dd($extracted_arr[0]);
        $row_count = $extracted_arr[0];
        $main = [];
        $count = 0;
        $senderid_arr = [];
        $rejected_rows = [];
        $rejected_rows_filename = public_path('documents/general_files/'. $filename . "_rejected_rows.txt");
        foreach ($extracted_arr[0] as $key => $value) {
            if ($value['senderid'] == null) {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if ($value['direct_mno'] == "YES" && $value['mno_name'] == null) {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if ($value['direct_mno'] == "NO" && $value['supplier_name'] == null) {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if ($value['direct_mno'] == "YES" && in_array($value['mno_name'], $network_arr) == true) {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if ($value['direct_mno'] == "NO" && in_array($value['supplier_name'], $client_arr) == true) {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            $check_duplicate_mno = Models\SenderId::where('senderid', $value['senderid'])                                
                ->where('mno_name', $value['mno_name'])
                ->first();
            $check_duplicate_client = Models\SenderId::where('senderid', $value['senderid'])                                
                ->where('supplier_name', $value['supplier_name'])
                ->first();

            if ($check_duplicate_mno && $value['direct_mno'] == "YES") {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if ($check_duplicate_client && $value['direct_mno'] == "NO") {
                file_put_contents($rejected_rows_filename, json_encode($value) . PHP_EOL, FILE_APPEND);
                continue;
            }
            if (strtoupper($value['direct_mno']) == 'YES') {
                // dd('foo bar');
                $senderid_arr['senderid'] = $value['senderid'];
                $senderid_arr['mno_name'] = $value['mno_name'];
                $senderid_arr['created_by'] = session('current_user.id');
                $senderid_arr['last_modified_by'] = session('current_user.id');
                $senderid_arr['remarks'] = $value['remarks'];
                $senderid_arr['direct_mno'] = 'YES';
            }
            else{
                $senderid_arr['senderid'] = $value['senderid'];
                $senderid_arr['supplier_name'] = $value['supplier_name'];
                $senderid_arr['created_by'] = session('current_user.id');
                $senderid_arr['last_modified_by'] = session('current_user.id');
                $senderid_arr['remarks'] = $value['remarks'];
                $senderid_arr['direct_mno'] = 'NO';
            }
            
            // dd($senderid_arr);
            $result = Models\SenderId::create($senderid_arr);
            // dd($retval);         
             
        }
        
        $request->session()->put('current_user.rejected_rows_filename', $filename . "_rejected_rows.txt");
        $rejected = file($rejected_rows_filename);
        
        // dump(session('current_user.rejected_rows_filename'));
        // dd('the end');
        Session::flash('success_message', 'Bulk Sender ID successfully uploaded, review the report file!');
        return redirect(url('senderids'));
    }
    public function getUploadReport($name){
        $file = public_path('documents/general_files/') . $name;
        $headers = ['Content-Type' => 'text/plain '];
        return \Response::download($file, 'Sender ID Upload Report', $headers);
    }
    public function getSampleFile(){
        $file = public_path('documents/general_files/senderid_sample_file.xlsx');

        #$extension = pathinfo($file, PATHINFO_EXTENSION);
        $headers = ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; 
        return \Response::download($file, 'Sender ID Sample Upload File', $headers);
    }
    public function edit($id){
        $senderid = Models\SenderId::findOrFail($id);
        //dd($senderid);


        $networks = \DB::table('network_operators')->Select(\DB::raw('concat(name, " (", country, ")") AS networkvalue, concat(name, " (", country, ")") AS network'))->orderBy('network')->get()->toArray();
        $network_arr = array_pluck($networks, 'network', 'networkvalue');
        $direct_mno_arr = ['YES' => 'YES', 'NO' => 'NO'];
        // dd($network_arr);

        $clients = \DB::table('clients')->Select(\DB::raw('concat(name, " (", country, ")") AS clientvalue, concat(name, " (", country, ")") AS client'))->orderBy('client')->get()->toArray();
        $client_arr = array_pluck($clients, 'client', 'clientvalue');
        $staffmembers = Models\StaffMember::pluck('name', 'id');
        // $status = ['Pending' => 'Pending', 'Inactive' => 'Inactive', 'Approved' => 'Approved'];
        $status = [
            'Applied to MNO' => 'Applied to MNO', 
            'Applied to Aggregator' => 'Applied to Aggregator', 
            'Approved on MNO' => 'Approved on MNO', 
            'Approved on Aggregator' => 'Approved on Aggregator', 
            'Active' => 'Active', 
            'Inactive' => 'InActive'
        ];

        // $data = [
        //     'page_title' => 'Create Sender ID',
        //     'network_arr' => $network_arr, G*385058081508uq
        //     'status' => $status,
        //     'clients' => $clients,
        //     'senderid' => $senderid,
        //     'direct_mno_arr' => $direct_mno_arr,
        //     'staffmembers' => $staffmembers
        // ];
        $data = [
            'page_title' => 'Edit Sender ID',
            'network_arr' => $network_arr,
            'status' => $status,
            'clients' => $client_arr,
            'senderid' => $senderid,
            'direct_mno_arr' => $direct_mno_arr,
            'staffmembers' => $staffmembers
        ];

        return view('senderid.edit', $data);
    }
    public function update(Request $request, $id)
    {

        $request->validate([
            'senderid' => 'required|max:11',
            'mno_name' => 'required_if:direct_mno,YES',
            'supplier_name' => 'required_if:direct_mno,NO',
            'status' => 'required',
            'remarks' => 'sometimes',
        ]);
        // dd($request->all());
        $senderid = Models\SenderId::findOrFail($id);

        $senderid->senderid = $request->senderid;
        $senderid->mno_name = $request->mno_name ?? '';
        $senderid->status = $request->status;
        $senderid->supplier_name = $request->supplier_name ?? '';
        $senderid->remarks = $request->remarks;
        $senderid->direct_mno = $request->direct_mno;
        $senderid->last_modified_by = session('current_user.id');

        // if ($request->direct_mno == 'NO') {
        //     $mno_world_wide = Models\Worldwidemno::find($request->network_id);
        //     // code... save in the network ops with status as non-direct ... user createOrUpdate method
        //     $network_ops_arr['name'] = $mno_world_wide->network;
        //     $network_ops_arr['country'] = $mno_world_wide->country;
        //     $network_ops_arr['name'] = $mno_world_wide->network;
        //     $network_ops_arr['direct_business'] = 'NO'; // $mno_world_wide->network;
        //     $result = Models\NetworkOps::updateOrCreate(['name' =>  $mno_world_wide->network, 'country' => $mno_world_wide->country, 'direct_business' => 'NO'], $network_ops_arr);
        //     $senderid->network_id = $result->id;
        // }


        $senderid->save();

        Session::flash('success_message', 'Sender ID successfully Updated');
        return redirect(url('senderids'));
    }
    public function direct_store(Request $request)
    {
        $request->validate([
            'senderid' => 'required|max:11',
            'network_id' => 'required',
            'status' => 'required',
            'remarks' => 'sometimes',
        ]);
        $senderid_arr = $request->except('_token');
        $senderid_arr['created_by'] = session('current_user.id');
        $senderid_arr['last_modified_by'] = session('current_user.id');
        $senderid_arr['remarks'] = $request->remarks ?? '';


        $result = Models\SenderId::create($senderid_arr);


        if($result){
          return response()->json([ 'code' => 1, 'result' => 'success']);
        }
        else {
          return response()->json([ 'code' => 3, 'msg' => 'Request could not be handled at this time']);
        }
    }


    public function getMNOList($type){
        if ($type == 'YES') {
            $data_arr = \DB::table('network_operators')->Select(\DB::raw('id, concat(name, " (", country, ")") AS name'))->orderBy('country')->get()->toArray();
        }
        elseif ($type == 'NO') {
            $data_arr = \DB::table('mno_world_wide')->Select(\DB::raw('id, concat(network, " (", country, ")") AS name'))->orderBy('country')->get()->toArray();
        }
        else{
            return response()->json(['code' => 3, 'msg' => 'invalid request']);
        }
        return response()->json(['code' => 1, 'msg' => 'success', 'result' => $data_arr]);
    }
}
