<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use App\Models\Member;
use App\Helpers\CurrentUser;
use Carbon\Carbon;
use Image;
use Auth;

class MemberController extends Controller
{   

    function __construct()
    {
         $this->middleware('permission:member-list|member-create|member-edit|member-delete', ['only' => ['index','show']]);
         $this->middleware('permission:member-create', ['only' => ['create','store']]);
         $this->middleware('permission:member-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:member-delete', ['only' => ['destroy']]);
    }

     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //To fet userId..
        $userId = CurrentUser::getUserId();
        $memberData = Member::orderBy('id','DESC')->where('user_id', $userId)->paginate(10);
        $allMemberCount = Member::orderBy('id','DESC')->where('user_id', $userId)->count();

        return view('admin.member.index' ,compact('memberData','allMemberCount'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.member.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'member_name'=> 'required',
            'father_name'=> 'required',
            'mother_name'=> 'required',
            'present_address'=> 'required',
            'permanent_address'=> 'required',
            'profession'=> 'required',
            'birth_of_date'=> 'required',
            'nationality'=> 'required',
            'professional_address'=> 'required',
            'member_phone'=> 'required|min:11|unique:members,member_phone',
            'nid_no'=> 'required|unique:members,nid_no',
            'member_photo'=> 'required|mimes:jpeg,png,jpg,gif,svg',
            
            'nomini_name'=> 'required',
            'nomini_father_name'=> 'required',
            'nomini_mother_name'=> 'required',
            'nomini_present_address'=> 'required',
            'nomini_permanent_address'=> 'required',
            'nomini_profession'=> 'required',
            'nomini_birth_of_date'=> 'required',
            'nomini_nationality'=> 'required',
            'nomini_professional_address'=> 'required',
            'nomini_phone'=> 'required|min:11|unique:members,nomini_phone',
            'relation'=> 'required',
            'nomini_nid_no'=> 'required|unique:members,nomini_nid_no',
            'nomini_photo'=> 'required|mimes:jpeg,png,jpg,gif,svg',
        ]);

        //To fet userId..
        $userId = CurrentUser::getUserId();
        $data = $request->all();
        $selectedDate = Carbon::parse($request->birth_of_date)->format('Y-m-d');
        $selectedDate2 = Carbon::parse($request->nomini_birth_of_date)->format('Y-m-d');
        $data['user_id'] = $userId;
        $data['birth_of_date'] = $selectedDate;
        $data['nomini_birth_of_date'] = $selectedDate2;

        if($request->member_photo){
            $file = $request->file('member_photo');
            $fileName = time().rand(100000, 999999).'.'.$file->getClientOriginalExtension();
            $destinationPath = public_path('uploads/member_photo/');
            Image::make($file)->save($destinationPath.$fileName);
            $destinationPath = public_path('uploads/member_photo/thumbnail/');
            Image::make($file)->resize(100,80)->save($destinationPath.$fileName);
            $data['member_photo'] = $fileName;
        }
        
        if($request->nomini_photo){
            $file = $request->file('nomini_photo');
            $fileName = time().rand(100000, 999999).'.'.$file->getClientOriginalExtension();
            $destinationPath = public_path('uploads/nomini_photo/');
            Image::make($file)->save($destinationPath.$fileName);
            $destinationPath = public_path('uploads/nomini_photo/thumbnail/');
            Image::make($file)->resize(100,80)->save($destinationPath.$fileName);
            $data['nomini_photo'] = $fileName;
        }

        if(Member::create($data)){
            Toastr::success('Member Created Successfully.', 'Success', ["progressbar" => true]);
            return redirect()->route('member.index');
        }else{
            Toastr::error('Something Is Wrong.!', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $singleMember = Member::find($id);
        return view('admin.member.edit' , compact('singleMember'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'member_name'=> 'required',
            'father_name'=> 'required',
            'mother_name'=> 'required',
            'present_address'=> 'required',
            'permanent_address'=> 'required',
            'profession'=> 'required',
            'birth_of_date'=> 'required',
            'nationality'=> 'required',
            'professional_address'=> 'required',
            'member_phone'=> 'required|min:11|unique:members,member_phone, '.$id,
            'nid_no'=> 'required|unique:members,nid_no, '.$id,
            'member_photo'=> 'nullable|mimes:jpeg,png,jpg,gif,svg',
            
            'nomini_name'=> 'required',
            'nomini_father_name'=> 'required',
            'nomini_mother_name'=> 'required',
            'nomini_present_address'=> 'required',
            'nomini_permanent_address'=> 'required',
            'nomini_profession'=> 'required',
            'nomini_birth_of_date'=> 'required',
            'nomini_nationality'=> 'required',
            'nomini_professional_address'=> 'required',
            'nomini_phone'=> 'required|min:11|unique:members,nomini_phone, '.$id,
            'relation'=> 'required',
            'nomini_nid_no'=> 'required|unique:members,nomini_nid_no, '.$id,
            'nomini_photo'=> 'nullable|mimes:jpeg,png,jpg,gif,svg',
        ]);

        //To fet userId..
        $userId = CurrentUser::getUserId();
        $data = $request->all();
        $selectedDate = Carbon::parse($request->birth_of_date)->format('Y-m-d');
        $selectedDate2 = Carbon::parse($request->nomini_birth_of_date)->format('Y-m-d');
        $data['user_id'] = $userId;
        $data['birth_of_date'] = $selectedDate;
        $data['nomini_birth_of_date'] = $selectedDate2;

        //To fetch single member data...
        $singleMember = Member::find($id);

        if($request->member_photo != null){
            $file = $request->file('member_photo');
            $fileName = time().rand(100000, 999999).'.'.$file->getClientOriginalExtension();
            $destinationPath = public_path('uploads/member_photo/');
            if(file_exists($destinationPath.$singleMember->member_photo)){
                if($singleMember->member_photo != ''){
                    unlink($destinationPath.$singleMember->member_photo);
                }
            }
            Image::make($file)->save($destinationPath.$fileName);
            //For Thumbnail
            $destinationPath = public_path('uploads/member_photo/thumbnail/');
            if(file_exists($destinationPath.$singleMember->member_photo)){
                if($singleMember->member_photo != ''){
                    unlink($destinationPath.$singleMember->member_photo);
                }
            }
            Image::make($file)->resize(100,80)->save($destinationPath.$fileName);
            $data['member_photo'] = $fileName;
        }
        
        if($request->nomini_photo != null){
            $file = $request->file('nomini_photo');
            $fileName = time().rand(100000, 999999).'.'.$file->getClientOriginalExtension();
            $destinationPath = public_path('uploads/nomini_photo/');
            if(file_exists($destinationPath.$singleMember->nomini_photo)){
                if($singleMember->nomini_photo != ''){
                    unlink($destinationPath.$singleMember->nomini_photo);
                }
            }
            Image::make($file)->save($destinationPath.$fileName);
            //For Thumbnail
            $destinationPath = public_path('uploads/nomini_photo/thumbnail/');
            if(file_exists($destinationPath.$singleMember->nomini_photo)){
                if($singleMember->nomini_photo != ''){
                    unlink($destinationPath.$singleMember->nomini_photo);
                }
            }
            Image::make($file)->resize(100,80)->save($destinationPath.$fileName);
            $data['nomini_photo'] = $fileName;
        }

        if($singleMember->update($data)){
            Toastr::success('Member Updated Successfully.', 'Success', ["progressbar" => true]);
            return redirect()->route('member.index');
        }else{
            Toastr::error('Something Is Wrong.!', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $singleMember = Member::find($id);
        //For Member
        $destinationPath = public_path('uploads/member_photo/');
        if($singleMember->member_photo != ''){
            unlink($destinationPath.$singleMember->member_photo);
            $destinationPath = public_path('uploads/member_photo/thumbnail/');
            unlink($destinationPath.$singleMember->member_photo);
        }
        //For Nomini
        $destinationPath = public_path('uploads/nomini_photo/');
        if($singleMember->nomini_photo != ''){
            unlink($destinationPath.$singleMember->nomini_photo);
            $destinationPath = public_path('uploads/nomini_photo/thumbnail/');
            unlink($destinationPath.$singleMember->nomini_photo);
        }

        if($singleMember->delete()){
            Toastr::success('Member Deleted Successfully.', 'Success', ["progressbar" => true]);
            return redirect()->back();
        }else{
            Toastr::error('Something Is Wrong.!', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    //To active status...
    public function memberActive($id)
    {
        Member::where('id', $id)->update(['status' => true]);
        Toastr::success('Member activated successfull.', 'Success', ["progressbar" => true]);
        return redirect()->back();
    }
    
    //To inactive status...
    public function memberInactive($id)
    {
        Member::where('id', $id)->update(['status' => false]);
        Toastr::success('Member in-activated successfull.', 'Success', ["progressbar" => true]);
        return redirect()->back();
    }


    //To get Supplier profile...
    public function getMemberProfile($id)
    {
        //To get single member...
        $singleSupplierData = Member::where('id', $id)->first();

        //Purchase...
        $purchaseData = Purchase::orderBy('id','desc')->where('purchase_status', true)->where('supplier_id', $id)->paginate(10);
        $purchaseCount = Purchase::orderBy('id','desc')->where('purchase_status', true)->where('supplier_id', $id)->count();
        $purchaseIds = Purchase::where('purchase_status', true)->where('supplier_id', $id)->select('id')->pluck('id')->toArray();

        //Supplier due payment...
        $supplierInvoiceIds = SupplierDuePayment::where('supplier_id', $id)->groupBy('supplier_invoice')
                            ->selectRaw('MAX(id) as id')->orderBy('id', 'desc')->pluck('id')->toArray();
        $supplierInvoiceData = SupplierDuePayment::orderBy('id','desc')->where('supplier_id', $id)
                                ->whereIn('id', $supplierInvoiceIds)->paginate(10);
        $supplierInvoiceCount = SupplierDuePayment::orderBy('id','desc')->where('supplier_id', $id)
                                ->whereIn('id', $supplierInvoiceIds)->count();

        //Total price & discount price...
        $subTotalPrice = PurchaseProduct::whereIn('purchase_id', $purchaseIds)->sum('total_product_price');
        $specialDiscountPrice = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('special_discount');

        //To get total paid,change & due amount...
        $subTotalProductQty = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('total_product');
        $grandTotalProductPrice = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('net_amount');
        $totalPaidPrice = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('paid_amount');
        $totalDuePrice = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('due_amount');
        $totalChangePrice = PurchasePayment::whereIn('purchase_id', $purchaseIds)->sum('change_amount');

        return view('admin.member.profile.index',compact('singleSupplierData','purchaseData','purchaseCount','subTotalPrice','subTotalProductQty'
                    ,'grandTotalProductPrice','specialDiscountPrice','totalPaidPrice','totalDuePrice'
                    ,'totalChangePrice','supplierInvoiceData','supplierInvoiceCount'));
    }

    //To get purchase-product-details...
    public function getPurProDetailsWithId(Request $request)
    {
        $purchaseId = $request->purchase_id;
        //To get purchase service product data...
        $purchaseProductData = PurchaseProduct::where('purchase_id', $purchaseId)->get();

        return view('admin.member.profile.updatePurchaseProductDetails',compact('purchaseProductData'));
    }

}
