<?php

namespace Modules\Refund\App\Http\Controllers\API\Buyer;

use Illuminate\Support\Facades\Auth;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Modules\Refund\App\Models\RefundRequest;
use Modules\Refund\App\Http\Requests\RefundValidateRequest;

class RefundController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        $user = Auth::guard('api')->user();

        $refunds = RefundRequest::with('order')->where('buyer_id', $user->id)->latest()->get();

        return response()->json([
            'refunds' => $refunds
        ]);
    }

    public function show($id)
    {

        $user = Auth::guard('api')->user();

        $refund = RefundRequest::with('order')->where('buyer_id', $user->id)->where('id', $id)->first();

        return response()->json([
            'refund' => $refund
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(RefundValidateRequest $request)
    {

        
        $user = Auth::guard('api')->user();

        $order = Order::where('buyer_id', $user->id)->where('id', $request->order_id)->first();

        if(!$order){
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }


        if($order->order_status == 'cancel_by_seller' || $order->order_status == 'cancel_by_buyer' || $order->approved_by_seller == 'rejected'){
            
            $is_exist = RefundRequest::where('order_id', $request->order_id)->first();
            if($is_exist){
                $notify_message = trans('translate.Refund request already send to admin');
                return response()->json([
                    'message' => $notify_message 
                ], 403);
            }

            $refund = new RefundRequest();
            $refund->buyer_id = $order->buyer_id;
            $refund->seller_id = $order->seller_id;
            $refund->order_id = $order->id;
            $refund->refund_amount = $order->total_amount;
            $refund->note = $request->note;
            $refund->save();

            $notify_message = trans('translate.Refund request send to admin. please wait for admin approval');
            return response()->json([
                'message' => $notify_message 
            ]);
        }else{
            $notify_message = trans('translate.Unable to refund request');
            return response()->json([
                'message' => $notify_message 
            ], 403);
        }
        
    }

}
