<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\MemberRegistration;
use App\MemberPayment;
use Validator;
use Image;
use Auth;

class MemberPaymentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $result = Auth::check();

        if($result){
            //getting data
        $payments = MemberPayment::leftJoin('member_registrations','member_registrations.id','=','member_payments.member_id')
        ->orderBy('member_payments.payment_date','desc')
        ->get(['member_payments.*','member_registrations.first_name','member_registrations.middle_name','member_registrations.last_name','member_registrations.phone']);
        return view('backend.member_payment',compact(['payments']));
        }
        
        else{
            return redirect('/');
        }
        
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //general requirement
        $rules = [
            'payment_method' => 'required',
            'payment_date' => 'required',
            'membership_number' => 'required',
            'joined' => 'required',
        ];

        $error = Validator::make($request->all(),$rules);

        if($error->fails()){
            return response()->json(['errors'=>"Crosscheck The Required Fields"]);
        }

        //getting the payment method first
        $payment_method = $request->payment_method;
        
        if($payment_method == "mobile"){
            $other_rules = [
                'reference_mobile' => 'required',
            ];
        }
        else{
            $other_rules = [
                'reference_bank' => 'required',
                'photo' => 'mimes::png,tiff,jpeg,jpg|max:2048',
            ];
        }

        //validating other rules
        $error = Validator::make($request->all(),$other_rules);

        if($error->fails()){
            return response()->json(['errors'=>"Crosscheck The Fields, if you use Bank the system accept JPG, PNG, TIFF, JPEG format not More than 2MB size."]);
        }

        else{
            //everything is clear continue with obtaining values
            $membership_number = $request->membership_number;

            //getting member id 
            $member = MemberRegistration::where('membership_number',$membership_number)->get();

            if($member->isEmpty()){
                return response()->json(['errors'=>"The Membership Number $membership_number Doesn't Exists in our Database Crosscheck the Number or contact TPHA for support."]);
            }
            else{
                foreach($member as $row){
                    $member_id = $row->id;
                }
            }


            if($payment_method == "mobile"){
                $data_save = [
                    'membership_number' => $membership_number,
                    'joined' => $request->joined,
                    'reference' => $request->reference_mobile,
                    'payment_date' => $request->payment_date,
                    'payment_method' => $payment_method,
                    'member_id' => $member_id,
                ];
            }
            else{
                if($photo = $request->file('photo')){
                    $photo_image = Image::make($photo);
                    $photo_destination = public_path('/uploads/payments/');
                    $photo_file = time().uniqid().".".$photo->getClientOriginalExtension();//to save in db
                    $resized = $photo_image->resize(400,300);
                    $resized->save($photo_destination.$photo_file);
                }

                if($photo == ""){
                    $data_save = [
                        'membership_number' => $membership_number,
                        'joined' => $request->joined,
                        'reference' => $request->reference_bank,
                        'payment_date' => $request->payment_date,
                        'payment_method' => $payment_method,
                        'member_id' => $member_id,
                    ];
                }
                else{
                    $data_save = [
                        'membership_number' => $membership_number,
                        'joined' => $request->joined,
                        'reference' => $request->reference_bank,
                        'payment_date' => $request->payment_date,
                        'payment_method' => $payment_method,
                        'image_attachment' => $photo_file,
                        'member_id' => $member_id,
                    ];
                }
            }
    
            //saving data
            $data_proccess = MemberPayment::create($data_save);
                
            if($data_proccess){
                return response()->json(['success'=>"Annual Payment received Successfully."]);
            }
            else{
                return response()->json(['success'=>"An Error occured while Proccessing your request Please try again later."]);
            }  
        }
    }

    /**
     * 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)
    {
        //
        $data = MemberPayment::findOrFail($id);
        return response()->json(['result'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, MemberPayment $model)
    {
        //getting the required fields
        $rules = [
            'reference' => 'required',
            'membership_number' => 'required',
            'payment_date' => 'required',
            'payment_method' => 'required',
        ];

        $error = Validator::make($request->all(),$rules);

        if($error->fails()){
            return response()->json(['errors'=>"Crosscheck the Fields."]);
        }
        else{
            //getting data
            $data_update = [
                'reference' => $request->reference,
                'membership_number' => $request->membership_number,
                'payment_date' => $request->payment_date,
                'payment_method' => $request->payment_method,
            ];

            //updating data
            $id = $request->hidden_data;
            
            $data = $model::whereId($id)->update($data_update);

            if($data){
                return response()->json(['success'=>"Member Payment updated Successfully."]);
            }

            else{
                return response()->json(['errors'=>"Unable to update Member Payment."]);
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //deletion
        $data = MemberPayment::findOrFail($id);

        if($data->delete()){
            return response()->json(['success'=>"Member Payment Deleted Successfully."]);
        }
        else{
            return response()->json(['errors'=>"Unable to Delete Members Payment Record."]);
        }
    }

    public function approve($id){
        
        $data = MemberPayment::whereId($id)->update(['status'=>"active"]);

        if($data){
            return response()->json(['success'=>"Member Payment Approved Successfully."]);
        }
        else{
            return response()->json(['errors'=>"Unable to Approve Members Payment Record."]);
        }
        
    }
}
