<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Hisa;
use App\Models\Akiba;
use App\Models\User;
use App\Models\Mikopo;
use App\Models\PaymentMethod;
use App\Models\PaymentType;
use App\Models\Durationinmonths;
use App\Models\Interest;
use App\Models\LoanPayment;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
class MikopoController extends Controller
{
    //
    //
    public function addMkopo() {

        $allusers = User::all();
        $pmethod = PaymentMethod::all();
        $ptype = PaymentType::all();
        $allhisas = Hisa::all()->where('member_id','member_id')->sum('amount');
        $period = Durationinmonths::all();
        $inte = Interest::all();

        return view('admin.mikopo.mikopo_add',compact('allusers','pmethod','ptype','allhisas','period'));
        
    }

    //
    public function paymentMkopo() {

        $allusers = User::all();
        $pmethod = PaymentMethod::all();
        $ptype = PaymentType::all();

        return view('admin.mikopo.mikopo_payment',compact('allusers','pmethod','ptype'));
        
    }
    // End of method

    public function paidMkopo(Request $request) {

        $allusers = User::all();
        $pmethod = PaymentMethod::all();
        $ptype = PaymentType::all();

        if($request->file('risit_image')) {
            $manager = new ImageManager(new Driver());
            $name_gen = hexdec(uniqid()).'.'.$request->file('risit_image')->getClientOriginalExtension();
            $img = $manager->read($request->file('risit_image'));
            $img = $img->resize(1029,519);
            $img->toJpeg(100)->save('upload/hisa/risit/'.$name_gen);
            $save_url = 'upload/hisa/risit/'.$name_gen;
        

        LoanPayment::insert([
            'member_id' => $request->member_id,
            'paymentmethod_id' => $request->paymentmethod_id,
            'paymenttype_id' => $request->paymenttype_id,
            'amount' => $request->amount,
            'pdate' => $request->pdate,
            'risiti' => $save_url,
            'created_by' => Auth::user()->id,
            'created_at' => Carbon::now(),
        ]);
    }

        $notification = array(
            'message' => 'Mkopo record stored successfully',
            'alert-type' => 'success',
        );
        
        return redirect()->route('allmikopo')->with($notification);
        
    }
    // End of method

    public function GetLoanAmount(Request $request) {

      $member_id = $request->member_id;
        $loanAmount = Mikopo::select('amount_given')->where('member_id',$member_id)->max('created_at');
        $allAkibaAmount = Akiba::where('member_id',$member_id)->sum('amount');
        //$total_hisa_akiba = $allHisaAmount + $allAkibaAmount;
        //dd(allHisaAmount);
        $total_paid = LoanPayment::select('amount')->where('member_id',$member_id)->sum('amount');
        $total_paid_interest = LoanPayment::select('interest_amount')->where('member_id',$member_id)->sum('interest_amount');
        $current_loan = Mikopo::select('amount_given')->where('member_id',$member_id)->where('status',1)->latest()->first();
        $current_interest = Mikopo::select('total_interest_tsh')->where('member_id',$member_id)->where('status',1)->latest()->first();
        $current_balance = $current_loan->amount_given - $total_paid;
        $current_i_balance = $current_interest->total_interest_tsh - $total_paid_interest;
        return response()->json([
            'loanAmount' => $loanAmount,
            'current_loan' => $current_loan,
            'current_balance' => $current_balance,
            'current_interest' => $current_interest,
            'current_i_balance' => $current_i_balance
        ]);
     }
    // End of method

    public function GetUser(Request $request) {

      // dd($member_id)
      $member_id = $request->member_id;
      // dd(member_id);
        $allHisaAmount = Hisa::where('member_id',$member_id)->sum('amount');
        $allAkibaAmount = Akiba::where('member_id',$member_id)->sum('amount');
        $total_hisa_akiba = $allHisaAmount + $allAkibaAmount;
        //dd(allHisaAmount);
        return response()->json([
            'total_hisa_akiba' => $total_hisa_akiba
        ]);
     }
    // End of method

     public function GetCalculator(Request $request) {

        $period_id = $request->period_id;
        $amount_entered = $request->entered_amount;
        $interest = Interest::first()->interest;
        $total_interest = (($interest * $period_id) + 1) / 100;
        $interest_tsh = $amount_entered * $total_interest;
        $monthly_loan = $amount_entered / $period_id;
        $monthy_interest = $interest_tsh / $period_id;
        $total_monthly = $monthly_loan + $monthy_interest;
        $total_repaid_loan = $total_monthly * $period_id;

         return response()->json([
            'total_interest' => $total_interest,
            'interest_tsh' => $interest_tsh,
            'monthly_loan' => $monthly_loan,
            'monthy_interest' => $monthy_interest,
            'total_monthly' => $total_monthly,
            'total_repaid_loan' => $total_repaid_loan
         ]);
     }

    public function getHisa(Request $request)
    {
        $hisa_total = Hisa::where('id', $member_id)->sum('amount');

        if ($hisa_total) {
            return response()->json([
                'member_id' => $hisa_total->member_id,
                'total_hisa' => $hisa_total->total_hisa
            ]);
            return view('admin.mikopo.mikopo_add',compact('hisa_total'));
        }

        // return response()->json([
        //     'member_id' => '',
        //     'total_hisa' => ''
        // ]);
    }

    public function allMikopo() {
        $all_info = User::query()
        ->leftJoin('mikopos', function ($join) {
            $join->on('users.id', '=', 'mikopos.member_id')
                 ->where('mikopos.status', '=', 1);
        })
        ->leftJoin('akibas', function ($join) {
            $join->on('users.id', '=', 'akibas.member_id')
                 ->where('akibas.status', '=', 1);
        })
        ->select(
            'users.id',
            'users.name',
            'users.sname',
            'users.lname',
            'users.membership_no',
            'users.mobile_no',
            'users.address',
            DB::raw('COALESCE(SUM(mikopos.amount_given), 0) as amount_given'),
            DB::raw('COALESCE(COUNT(mikopos.amount_given), 0) as no_of_loans'),
            DB::raw('COALESCE(COUNT(mikopos.amount_given), 0) as current_loan_no'),
            DB::raw('COALESCE((SELECT m2.amount_given 
                      FROM mikopos m2 
                      WHERE m2.member_id = users.id 
                        AND m2.status = 1
                      ORDER BY m2.created_at DESC 
                      LIMIT 1), 0) as current_amount')
        )
        ->groupBy('users.id', 'users.name', 'users.sname', 'users.lname')
        ->get();



        return view('admin.mikopo.mikopo_all', compact('all_info'));

        return view('admin.mikopo.mikopo_all',compact('allusers','pmethod','ptype','allhisas','period'));
    }
    
    // End of method

     public function StoreMkopo(Request $request) {

         $amount_check = $request->entered_amount <= $request->total_hisa_plus_akiba;
        $request->merge([
            't_interest_tsh' => str_replace(',', '', $request->t_interest_tsh),
            'm_loan' => str_replace(',', '', $request->m_loan),
            'm_interest_tsh' => str_replace(',', '', $request->m_interest_tsh),
            't_monthly_tsh' => str_replace(',', '', $request->m_interest_tsh),
            't_repaid_tsh' => str_replace(',', '', $request->t_repaid_tsh),
            't_amount_m1' => str_replace(',', '', $request->t_amount_m1),
            't_amount_m2' => str_replace(',', '', $request->t_amount_m2),
            't_amount' => str_replace(',', '', $request->t_amount),
        ]);

        // $validateData = $request->validate([
        //     'member_id' => 'required',
        //     'e_amount' => 'required',
        //    // 'entered_amount' => 'required|numeric|lte:e_amount',
        //     'period_id' => 'required',
        //     't_interest' => 'required',
        //     't_interest_tsh' => 'required|numeric',
        //     'm_loan' => 'required|numeric',
        //     'm_interest_tsh' => 'required|numeric',
        //     't_monthly_tsh' => 'required|numeric',
        //     't_repaid_tsh' => 'required|numeric',
        //     'm1_id' => 'required',
        //     't_amount_m1' => 'required|numeric',
        //     'm2_id' => 'required',
        //     't_amount_m2' => 'required|numeric',
        //     'amount_check' => 'required',
        //     'pdate' => 'required',
        // ], [
        //     'entered_amount.lte' => 'Entered amount is greater than eligible amount',
        // ]);

        //  if($validateData->fails()) {
        //     $notification = array(
        //     'message' => 'All fields are mandatory',
        //     'alert-type' => 'error',
        // );}
        Mikopo::insert([
            'member_id' => $request->member_id,
            'total_hisa_plus_akiba' => $request->t_amount,
            'amount_given' => $request->entered_amount,
            'period' => $request->period,
            'total_interest_percent' => $request->t_interest,
            'total_interest_tsh' => $request->t_interest_tsh,
            'monthly_payment' => $request->m_loan,
            'monthly_interest_tsh' => $request->m_interest_tsh,
            'total_monthly_tsh' => $request->t_monthly_tsh,
            'total_repaid_loan_tsh' => $request->t_repaid_tsh,
            'm1_member_id' => $request->m1_id,
            'm1_total_hisa_plus_akiba' => $request->t_amount_m1,
            'm2_member_id' => $request->m2_id,
            'm2_total_hisa_plus_akiba' => $request->t_amount_m2,
            'pdate' => $request->pdate,
            'status' => 0,
            'created_by' => Auth::user()->id,
            'created_at' => Carbon::now(),
        ]);


        $notification = array(
            'message' => 'Mkopo record stored successfully',
            'alert-type' => 'success',
        );
        return redirect()->route('addmkopo')->with($notification);

    // } else {

    //     $notification = array(
    //         'message' => 'All fields are mandatory',
    //         'alert-type' => 'error',
    //     );
    //     return view('admin.mikopo.mikopo_add',compact('$validateData'));
    // }

        
        
     }
    // // End of method

    public function pendingmkopo() {
        $pending = Mikopo::where('status',0)
        ->where('amount_given', '!=', 0)
        ->with(['user:id,name,sname,lname'])
        ->get(['id','member_id','amount_given']);
        return view('admin.mikopo.mikopo_pending', compact('pending'));
    }

    // public function reviewhisa($id) {
    //     $h_review = Hisa::findOrFail($id);
    //     $all_users = User::where('id', $h_review->member_id)->get();
    //     $p_type = PaymentType::where('id', $h_review->paymenttype_id)->get();
    //     return view('admin.hisa.hisa_payment_approval', compact('h_review','all_users','p_type'));
    // }
    // // End of method

    // public function approvedhisa(Request $request) {
    //     $request_id = $request->id;
    //     $h_approved = Hisa::findOrFail($request_id)->update([
    //         'status' => 1,
    //         'updated_by' => Auth::user()->id,
    //         'updated_at' => Carbon::now(),
    //     ]);

    //     $notification = array(
    //         'message' => 'Hisa approved successfully',
    //         'alert-type' => 'success',
    //     );
    //     return redirect()->route('pendinghisa')->with($notification);
    // }
    // // End of method

    // public function rejecthisa(Request $request) {
    //     $request_id = $request->id;
    //     $h_rejected = Hisa::findOrFail($request_id)->update([
    //         'status' => '2',
    //         'reason' => $request->reason,
    //         'updated_by' => Auth::user()->id,
    //         'updated_at' => Carbon::now(),
    //     ]);
    // }

    // // view hisa

    public function view_mikopo(Request $request) {
        $view_mikopo = Mikopo::where('member_id', Auth::user()->id)->where('status',1)->get();
        $total_mikopo = Mikopo::where('member_id', Auth::user()->id)->where('status',1)->sum('amount');
        $all_users = User::where('id',Auth::user()->id)->get();
        return view('admin.hisa.all_hisa', compact('view_hisa','all_users','total_hisa'));
    }

    public function userMkopo($id) {

        $userData = User::findOrFail($id);
        $total_mkopo_paid = LoanPayment::where('member_id', $userData->id)->where('status',1)->get();
        $all_users = User::where('id', $userData->id)->get();

        $total_akiba = Akiba::where('member_id', $userData->id)->where('status',1)->get();

        return view('admin/users/users_view_mikopo',compact('userData','all_users','total_mkopo_paid','total_akiba'));
    }
    // End of method

}
