<?php
//dealers are not using the OrgUsers like SRWB
namespace App\Http\Controllers;
use App\Models;
use Illuminate\Http\Request;
use App\Libs\Smsgateway; 
use Session;
use App\ActivityLog;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;


class OrganisationsController extends Controller
{
    public function index(){
        $org_user = session('current_org_user');
        // dd($org_user);
        $merchants = Models\Merchant::where('org_id', $org_user['org_id'])->latest()->paginate(20);
        $data = [
            'merchants_list' => $merchants,
            'merchants' => $merchants,
            'page_title' => 'Merchants',
            'org_user' => $org_user,
        ];
        return view('organisation.merchants',$data);
    }
    public function landing(){
        $org_user = session('current_org_user');
        $merchants = Models\Merchant::get(); // to be used for tops in the dropdown
        $dealer = Models\OrgUser::find($org_user['org_id']);
        $merchant_ids = $merchants->pluck('id');
        $merchant_topups = Models\MerchantTopUp::with('merchantInfo')->where('org_user_id', $org_user['id'])->orderBy('id', 'DESC')->get();
        $data = [
            'transaction_count' => $merchant_topups->count(),
            'merchants' => $merchants,
            'merchant_topups' => $merchant_topups->take(5),
            'organisation' => $dealer,
            'page_title' => 'Dashboard'
        ];
        return view('organisation.landing',$data);
    }
    public function transactions(){   
        $org_user = session('current_org_user');
        $data = [
            // 'merchant_topups' => $merchant_topups,
            'org_user' => $org_user,
            'page_title' => 'Dealer Transactions'
        ];
        return view('organisation.transactions', $data);
    }
    public function getTransactionsJson(Request $request){
        $dealer_id = session('current_org_user.id');
        $transactions_arr = \DB::table('merchant_top_ups')
            ->join('org_users', 'merchant_top_ups.org_user_id', '=', 'org_users.id')
            ->join('merchants', 'merchant_top_ups.merchant_id', '=', 'merchants.id')
            ->select('merchant_top_ups.id', 'merchant_top_ups.status', 'merchants.phone', 'merchants.fullname', 'merchant_top_ups.payment_method', 'merchant_top_ups.org_user_id', 'merchant_top_ups.amount', 'merchant_top_ups.created_at')
            ->whereRaw('merchant_top_ups.org_user_id = '. $dealer_id)
            ->orderBy('merchant_top_ups.created_at', 'DESC')
            ->paginate(10);

        if($request->has('keyword')){
            $queries = [];
            $keyword = $request->keyword;
            $queries['keyword'] = $keyword;
            $transactions_arr = \DB::table('merchant_top_ups')
                ->join('org_users', 'merchant_top_ups.org_user_id', '=', 'org_users.id')
                ->join('merchants', 'merchant_top_ups.merchant_id', '=', 'merchants.id')
                ->select('merchant_top_ups.id', 'merchant_top_ups.status', 'merchants.phone', 'merchants.fullname', 'merchant_top_ups.payment_method', 'merchant_top_ups.org_user_id', 'merchant_top_ups.amount', 'merchant_top_ups.created_at')
                ->whereRaw("merchants.fullname LIKE '%$keyword%' OR merchants.phone LIKE '%$keyword%' OR merchant_top_ups.status LIKE '%$keyword%' OR merchant_top_ups.payment_method LIKE '%$keyword%' OR merchant_top_ups.amount LIKE '%$keyword%' OR merchant_top_ups.created_at LIKE '%$keyword%'")
                ->whereRaw('merchant_top_ups.org_user_id = '. $dealer_id)
                ->orderBy('merchant_top_ups.created_at', 'DESC')
                ->paginate(10)->appends($queries);
        }
        return response()->json($transactions_arr);
    }
    public function mytopups(){   
        $org_user = session('current_org_user');
        $data = [
            'org_user' => $org_user,
            'page_title' => 'My Top Ups'
        ];
        return view('organisation.mytopups', $data);
    }
    public function getMyTopUpsJson(Request $request){
        $dealer_id = session('current_org_user.id');
        $transactions_arr = \DB::table('organisation_top_ups')
            ->join('org_users', 'organisation_top_ups.org_id', '=', 'org_users.org_id')
            ->join('users', 'organisation_top_ups.user_id', '=', 'users.id')
            ->select('organisation_top_ups.id', 'organisation_top_ups.status', 'org_users.phone', 'users.name', 'organisation_top_ups.payment_method', 'organisation_top_ups.org_id', 'organisation_top_ups.amount', 'organisation_top_ups.created_at')
            ->whereRaw('organisation_top_ups.org_user_id = '. $dealer_id)
            ->orderBy('organisation_top_ups.created_at', 'DESC')
            ->paginate(10);

        if($request->has('keyword')){
            $queries = [];
            $keyword = $request->keyword;
            $queries['keyword'] = $keyword;
            $transactions_arr = \DB::table('organisation_top_ups')
                ->join('org_users', 'organisation_top_ups.org_user_id', '=', 'org_users.id')
                ->join('users', 'organisation_top_ups.user_id', '=', 'users.id')
                ->select('organisation_top_ups.id', 'organisation_top_ups.status', 'org_users.phone', 'users.name', 'organisation_top_ups.payment_method', 'organisation_top_ups.org_id', 'organisation_top_ups.amount', 'organisation_top_ups.created_at')
                ->whereRaw("org_users.name LIKE '%$keyword%' OR org_users.phone LIKE '%$keyword%' OR organisation_top_ups.status LIKE '%$keyword%' OR organisation_top_ups.payment_method LIKE '%$keyword%' OR organisation_top_ups.amount LIKE '%$keyword%' OR organisation_top_ups.created_at LIKE '%$keyword%'")
                ->whereRaw('organisation_top_ups.org_user_id = '. $dealer_id)
                ->orderBy('organisation_top_ups.created_at', 'DESC')
                ->paginate(10)->appends($queries);
        }
        return response()->json($transactions_arr);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       
        $merchant = Merchant::where('id',$id)->with('transactions')->get()[0];
        $data = [
            'merchant'=>$merchant,
        ];
        return view('merchant.show',$data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $merchant = Merchant::findorfail($id);
        $countries = Countries::all();

        $data = [
            'countries'=>$countries,
            'merchant'=>$merchant,
        ];
        return \view('merchant.update',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'fullname' => 'required',
            'phone_number'=> 'required',
            'language' => 'required'
        ]);
        $check_phone = $this->validatePhoneNumber($request->phone_number);
        if ($check_phone == false) {
            return redirect()->back()->withInput()->with('admin-error', 'Invalid phone number!');
        }


        Merchant::where('id', $id)->update([
            'fullname'=> $request->fullname,
            'phone'=> $check_phone,
            'language' => $request->language
        ]);

        $desc = [
            'title' =>'updated a merchant',
            'data' => $request->fullname,
            'type' => 'merchant',
        ];

        $activity = new ActivityLog;
        $activity->user_id = $request->session()->get('current_org_user.id');
        $activity->user_type =  'dealer'; 
        $activity->description = json_encode($desc);
        $activity->save();

        return redirect()->to('/admin/merchant')->with('admin-sucsess', 'Successfully Updated Merchant');

    }
    public function merchantTopupOtpStore(Request $request){
        
        $org_id = $request->session()->get('current_org_user.org_id');
        $org_otp = random_int(1000, 9999);
        $dealer = Models\OrgUser::where('org_id', $org_id)->first();
        $smsgateway = new Smsgateway; 
        $request->session()->put('current_org_user.otp', $org_otp);
        $msg = "Hello $dealer->name, your one time PIN is $org_otp. Enter this on the form to complete the top up.";
        
        if(env('APP_ENV') !== 'local'){
            $message_result = $smsgateway->sendSmsNew($dealer->phone, $msg);
        }
        \Log::info($msg);
        //$this->sendNtfy($msg);
        $lastThree = substr($dealer->phone, -3);
        return response()->json([
            'code' => 1,
            'status' => 'success',
            'message' => "An OTP has been sent to your phone number ending ... $lastThree. Enter this on the form to complete the top up."
        ]);

    }
    
    public function merchantTopupStore(Request $request)
    {
        $request->validate([
            'merchant' => 'required|exists:merchants,id',
            'amount'   => 'required|numeric|min:1',
        ]);

        $currentUser = $request->session()->get('current_org_user');

        $orgId = $currentUser['org_id'];
        $userId = $currentUser['id'];
        $amount = (float) $request->amount;

        $dealer = Models\OrgUser::findOrFail($orgId);
        $merchant = Models\Merchant::findOrFail($request->merchant);

        if ($amount > $dealer->balance) {
            if ($request->expectsJson()) {
                return response()->json([
                    'code' => 3,
                    'status' => 'failed',
                    'message' => 'Insufficient Balance.'
                ]);
            }
            Session::flash('success_message', 'Insufficient Balance!!');
            return back()->withInput()->withErrors(['amount' => 'Insufficient Balance.']);
        }

        DB::beginTransaction();

        try {
            $topup = Models\MerchantTopUp::create([
                'merchant_id'      => $merchant->id,
                // 'org_id'           => $orgId,
                'amount'           => $amount,
                'transaction_id'   => 'MCH-' . Str::uuid(),
                'org_user_id'      => $userId,
                'created_by'       => $userId,
                'payment_method'   => 'cash'
            ]);

            $merchant->increment('balance', $amount);
            $dealer->decrement('balance', $amount);

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error($e);

            if ($request->expectsJson()) {
                return response()->json([
                    'code' => 3,
                    'status' => 'failed',
                    'message' => 'Merchant Top Up failed.'
                ]);
            }
            Session::flash('error_message', 'Merchant Top Up failed!!');
            return back()->withInput()->with('error', 'Merchant Top Up failed.');
        }

        ActivityLog::create([
            'user_id' => $userId,
            'user_type' => 'dealer',
            'description' => json_encode([
                'title' => 'dealer Added new Top Up',
                'data'  => 'MWK ' . number_format($amount, 2) . ' for ' . $merchant->fullname,
                'type'  => 'Dealer topup'
            ])
        ]);

        $merchant->refresh();

        try {
            if (!app()->environment('local')) {
                (new Smsgateway())->sendSmsNew(
                    $merchant->phone,
                    "Hello {$merchant->fullname}, your account has been credited with MWK {$amount}. Your new balance is MWK {$merchant->balance}."
                );
            }
        } catch (\Exception $e) {
            \Log::error($e);
        }
        
        if ($request->expectsJson()) {
            return response()->json([
                'code' => 1,
                'status' => 'success',
                'message' => 'Merchant Top Up Successfully completed.'
            ]);
        }
        Session::flash('success_message', 'Merchant Top Up Successfully completed!!');
        return back()->with('success', 'Merchant Top Up Successfully completed.');
    }

    public function getActivity()
    {
        //
        $org_user = session('current_org_user');
        $activities = ActivityLog::with('admin')->where('user_type', 'dealer')
                ->where('user_id', $org_user['id'])
                ->orderBy('created_at', 'desc')
                ->paginate(20);

        $data = [
            'activities' => $activities,
            'org_user' => $org_user,
            'page_title' => 'Dealer Activity Log'
        ];
        return view('organisation.activity', $data);
    }
}
