<?php

namespace App\Http\Controllers\Payments;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ConvertNumberToWordsController;
use App\Models\CompanyCurrency;
use App\Models\Payment;
use Illuminate\Http\Request;

class PaymentController extends Controller
{

    /**Show Receipt Page**/
    public function index($id, ConvertNumberToWordsController $numberToWordsController,$module=null){
        $pv = $this->pvDetailsWithStamp($id);
        if($pv){
            $pvs = [];
            if(Payment::where('branch', auth()->user()->branch)->orderBy('pv_id', 'asc')->first()){
                $pvs = Payment::where('branch', auth()->user()->branch)->orderBy('pv_id', 'asc')->get();
            }
            $amountInWords = $numberToWordsController->convert_number_to_words($pv->amount);

            $data = [
                'next' => $this->nextPrevDirectPV($id)['next'],
                'prev' => $this->nextPrevDirectPV($id)['previous']
            ];
            return view('payments.payment',compact('pv','module', 'data','pvs', 'amountInWords'));

        }
        return view('errors.404');
    }

    /**Get Pv Details if Exist**/
    protected function pvDetailsWithStamp($stamp){
        $rct = [];
        if(Payment::firstWhere('stamp', $stamp)){
            $rct = Payment::where('stamp', $stamp)->first();
        }
        return $rct;
    }

    /**NEXT AND PREVIOUS ENTRIES**/
    public function nextPrevDirectPV($stamp){
        $branch = auth()->user()->branch;
        $next = $previous = $previousStamp = $nextStamp = [];
        if($this->pvDetailsWithStamp($stamp)){
            $id = $this->pvDetailsWithStamp($stamp)->pv_id;
            // get previous user id
            $previous = Payment::where('pv_id', '<', $id)->where('branch', $branch)->max('pv_id');

            // get next user id
            $next = Payment::where('pv_id', '>', $id)->where('branch', $branch)->min('pv_id');
        }
        if($previous != null){
            $previousStamp = Payment::where('pv_id', $previous)->first()->stamp;
        }
        if($next != null){
            $nextStamp = Payment::where('pv_id', $next)->first()->stamp;
        }

        //dd($previousStamp);
        return [
            'next' => $nextStamp,
            'previous' => $previousStamp
        ];
    }

    public function showPayments(Request $request){
        $branch = auth()->user()->branch;

        $payments = [];
        if($request->has('search')){
            $payments =  $this->filterPayments($request);
        }
        $insurers = [];
        $currencies = CompanyCurrency::where('status', 1)->get();
        return view('payments.payments', compact('payments', 'insurers', 'currencies'));
    }

    /**Payments Filters**/
    public function filterPayments(Request $request){
        $branch = auth()->user()->branch;
        return Payment::where('branch', $branch)->where([
            [function($query) use ($branch, $request) {
                /**CHECK FOR SELECTED PAYMENT TYPE**/
                if($type = $request['payment-type']){
                    if($request['payment-type'] != 'all'){
                        $query = $query->where('type', $type);
                    }
                }
                /**CHECK FOR SELECTED PAYMENT STATUS**/
                if($status = $request['payment-status']){
                    if($request['payment-status'] != 'all'){
                        $query = $query->where('pv_status', $status);
                    }
                }
                /**CHECK IF CLIENT IS ADDED TO THE FILTER**/
                /*if($request['receipt-type'] == 'premium'){
                    if($request['client'] != ''){
                        $query = $query->where('c_id', Client::where('branch', $branch)->where('nms', $request['client'])->first()->c_id);
                    }
                }*/
                /**CHECK IF INSURER WAS SELECTED AND THE RECEIPT TYPE IS FOR THE COMMISSION**/
                /*if($request['receipt-type'] == 'commission'){
                    if($request['insurer'] != 'all'){
                        $query = $query->where('ins_id', $request['insurer']);
                    }
                }*/
                /**CHECK IF A SPECIFIC RECEIPT NUMBER WAS ENTERED**/
                if($paymentNo = $request['payment-no']){
                    if($request['payment-no'] != ''){
                        $query = $query->where('pv_id', 'like', '%' . $paymentNo . '%');
                    }
                }
                /**CHeck if Date Period is specified **/
                if($request['from'] != null && $request['to'] != null){
                    $query = $query->whereBetween('pv_date', [$request['from']." 00:00:00",$request['to']." 23:59:59"]);
                }
            }]
        ])->orderBy('pv_date', 'desc')->get();
    }

    /**Create a Function that will be used to Update the Payment Ref Number for a particular payment**/
    public function showEditRefNumber($id)
    {
        $payment = Payment::findOrFail($id);

        return view('payments.edit-payment-ref-number', compact('payment'));
    }

    /**Store the Updated Ref Number**/
    public function storeEditRefNumber($id, Request $request)
    {
        $payment = Payment::findOrFail($id);
        $ref = $request['ref'];

        $res = 'empty ref';
        if(!empty($ref)){
            /**At this Point we are sure the payment ref is not empty**/
            $update = $payment->update(['ref' => $ref]);

            $res = 'error';
            if($update){
                $res = 'success';
            }
        }
        return $res;
    }
}
