<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\InsurancePoint;
use App\Models\Insurer;
use App\Models\Policy;
use App\Models\Product;
use App\Models\Requisition;
use App\Models\SubAgent;
use App\Models\User;
use Illuminate\Http\Request;

class InsurancePointsController extends Controller
{
    /**Function to Display the Insurance Points Page**/
    public function showInsurancePointsReport(Request $request){
        $list = [];
        if($request->has('search')){
            $lists =  $this->filterInsurancePoints($request);
            if($request['from'] != null && $request['to'] != null){
                $from = date('Y-m-d', strtotime($request['from']));
                $to = date('Y-m-d', strtotime($request['to']));
            }

            /**Once I have the List, I can group it per Agent**/
            $agentsListing = array();
            foreach ($lists as $book) {
                $agentsListing[$book['agent_one_id']][] = $book;
            }

            $list = [];
            foreach ($agentsListing as $getAgents){
                $totalItems = count($getAgents);
                $redeemedPoints = 0;
                $totalPoints = 0;
                $redeemedAmount = 0;
                $amountRedeemable = 0;
                $agentStamp = [];
                $batch = null;
                foreach ($getAgents as $points){
                    $batch = $points['batch'];
                    $agentStamp = $points['agent_one_id'];
                    $redeemedPoints += $points['points_redeemed'];
                    $totalPoints += $points['awarded_points'];
                    $redeemedAmount += $points['amount_paid'];
                    $amountRedeemable += $points['amount_redeemable'];
                }

                /**If Agent Details are not Null, then Display the Agent Details**/
                $agentDetails = [];
                if($agentStamp != null){
                    $agentDetails = SubAgent::where('stamp', $agentStamp)->first();
                }
                $list[] = [
                    'batch' => $batch,
                    'agent-details' => $agentDetails,
                    'total-items' => $totalItems,
                    'redeemed-points' => $redeemedPoints,
                    'total-points' => $totalPoints,
                    'redeemed-amount' => $redeemedAmount,
                    'amount-redeemable' => $amountRedeemable
                ];
            }
        }
        $search = [
            'from' => $from ?? null,
            'to' => $to ?? null
        ];

        return view('finance.agents.redeem-insurance-points', compact('list', 'search'));
    }

    /**Filter through Insurance Points**/
    public function filterInsurancePoints(Request $request){
        return InsurancePoint::whereNotNull('batch')
            ->where([
                [function($query) use ($request) {
                    /**CHECK FOR SELECTED INSURER**/
                    if($agent = $request['agent']){
                        if($request['agent'] != 'all'){
                            $query = $query->where('agent_id', $agent);
                        }
                    }

                    /**CHECK IF A SPECIFIC USER WAS ENTERED**/
                    if($status = $request['status']){
                        if($request['status'] != 'all'){
                            if($status == 'pending'){
                                $query = $query->where('points_redeemed', 0);
                            }else{
                                $query = $query->where('points_redeemed', 1);
                            }
                        }
                    }
                    /**Check if Date Period is specified **/
                    if($request['from'] != null && $request['to'] != null){
                        $query = $query->whereBetween('created_at', [$request['from']." 00:00:00",$request['to']." 23:59:59"]);
                    }
                }]
            ])->orderBy('created_at', 'asc')->get();
    }

    /**Update the Redeemed Points Sections**/
    public function updateRedeemedPointsDetails($id, $batch)
    {
        $list = InsurancePoint::where('batch', $batch)->where('agent_one_id', $id)->get();
        $res = 'error';
        if($list){
            /**Loop through the List**/
            foreach ($list as $row){
                $req = Requisition::where('batch', $row->batch)->first();
                if($req){
                    /**We get the Payment Id**/
                    $payment_id = $req->payment ? $req->payment->id : null;
                }
                $row->update(
                    [
                        'amount_paid' => $row->amount_redeemable,
                        'points_redeemed' => $row->awarded_points,
                        'date_redeemed' => now(),
                        'pv_id' => $payment_id ?? null,
                        'paid_by' => auth()->user()->id,

                    ]
                );
            }
            $res = 'success';
        }
        return $res;
    }
}
