<?php

namespace App\Http\Controllers;

use App\Mail\BasicMail;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use App\PayoutRequest;
use App\Helpers\FlashMsg;
use App\Order;
use Illuminate\Support\Facades\Mail;

class PayoutRequestController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:payout-list|payout-edit|payout-view|payout-delete',['only' => ['payout_request_all']]);
        $this->middleware('permission:payout-edit',['only' => ['payout_request_update']]);
        $this->middleware('permission:payout-view',['only' => ['view_request']]);
        $this->middleware('permission:payout-delete',['only' => ['delete_payout_request','bulk_action_payout']]);
    }

    public function payout_request_all(){
        $all_payout_request = PayoutRequest::paginate(10);
        return view('backend.pages.payout-request.all-payout-request',compact('all_payout_request'));
    }

    public function payout_request_update(Request $request){
        $request->validate([
            'status'=> 'required',
        ]);

        PayoutRequest::where('id',$request->payout_request_id)
        ->update([
            'status'=>$request->status,
            'payment_receipt'=>$request->payment_receipt,
            'admin_note'=>$request->admin_note,
        ]);

        $seller_payout_details = PayoutRequest::where('id',$request->payout_request_id)->first();
        $seller_email =  optional($seller_payout_details->seller)->email;
        $seller_name =  optional($seller_payout_details->seller)->name;
        try {
            $message = get_static_option('admin_withdraw_amount_send_message') ?? '';
            $message = str_replace(["@name","@withdraw_amount"],[$seller_name,float_amount_with_currency_symbol($seller_payout_details->amount)],$message);
            Mail::to( $seller_email)->send(new BasicMail([
                'subject' =>get_static_option('admin_withdraw_amount_send_subject') ?? __('Payment Success'),
                'message' => $message
            ]));
        } catch (\Exception $e) {
            return redirect()->back()->with(FlashMsg::item_new($e->getMessage()));
        }
        return redirect()->back()->with(FlashMsg::item_new(__('Payment Request Update Success...')));
    }

    public function view_request($id=null){
        $request_details = PayoutRequest::where('id',$id)->first();
        $seller_id = $request_details->seller_id;

        $get_sum = Order::with('extraSevices')->where(['status' => 2, 'seller_id' => $seller_id])->get();
        $total_order_amount = $get_sum->sum('total');

        $extra_service_total = 0;
        $extra_service_total_tax = 0;
        $extra_service_total_commission_amount = 0;
        // seller total order amount & total extra service amount sum
        foreach ($get_sum as $order) {
            if ($order->extraSevices) {
                foreach ($order->extraSevices as $extraService) {
                    if ($extraService->payment_status == 'complete') {
                        $extra_service_total += $extraService->total;
                        $extra_service_total_tax += $extraService->tax;
                        $extra_service_total_commission_amount += $extraService->commission_amount;
                    }
                }
            }
        }

        $complete_order_balance_with_tax = $total_order_amount + $extra_service_total;
        $complete_order_tax = Order::where(['status'=>2,'seller_id'=>$seller_id])->sum('tax') + $extra_service_total_tax;
        $complete_order_balance_without_tax = $complete_order_balance_with_tax - $complete_order_tax;
        $admin_commission_amount = Order::where(['status'=>2,'seller_id' => $seller_id ])->sum('commission_amount') + $extra_service_total_commission_amount;

        $remaining_balance_total = $complete_order_balance_without_tax - $admin_commission_amount;
        $total_earnings = PayoutRequest::where('seller_id',$request_details->seller_id)->sum('amount');
        $remaining_balance = float_amount_with_currency_symbol($remaining_balance_total - $total_earnings);

        return view('backend.pages.payout-request.payout-request-details',compact('request_details','remaining_balance'));
    }

    //delete 
    public function delete_payout_request($id)
    {
        PayoutRequest::find($id)->delete();
        return redirect()->back()->with(FlashMsg::item_new(__('Payout Request Delete Success...')));
    }

    public function bulk_action_payout(Request $request){
        PayoutRequest::whereIn('id',$request->ids)->delete();
        return response()->json(['status' => 'ok']);
    }
    
    public function payout_request_report_download()
    {
        // Fetch pending payout requests with seller details
        $payout_requests = PayoutRequest::where('status', 0)
            ->with(['seller' => function ($query) {
                $query->where('user_type', 0)->select('id', 'name', 'email');
            }])
            ->get();

        // Load the view and pass the data
        $pdf = Pdf::loadView('backend.pages.payout-request.report-download', compact('payout_requests'));

        // Download the PDF
        return $pdf->download('pending_payout_requests_' . time() . '.pdf');
    }
}
