<?php
   
namespace App\Http\Controllers\API;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Http\Helpers\MyFatooraHelper;
use App\Http\Requests\API\OrderRequest;
use App\Http\Resources\ProductResource;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Models\Payment;
use App\Models\Post;
use App\Models\Taxonomy;

class OrderController extends BaseController
{
    use MyFatooraHelper;
    /**
     * All Orders 
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, int $categoryId = 13)
    {
        // dump($category);
        // $cat = Taxonomy::where('taxonomy', 'category')->slug($category)->first();
        $cat = Taxonomy::where('taxonomy', 'category')->where('term_id', $categoryId)->first();
        $slugs= getCategories($cat->term_id, 'slug');
        $slugs[]= $cat->slug;
        // dump($slugs);

        $posts= Post::published()
        ->type('post')->newest()
        ->taxonomy('category', $slugs)
        ->get();
        // dd($posts->toArray());

        $posts= ProductResource::collection($posts);
        return $this->sendResponse($posts, '');
        // return $this->sendResponse($request->user()->marketers, '');
    }
    
    /**
     * Create and prepar to pay.
     *
     * @return View
     */
    //===== TEST CARD 4508750015741019 =====//
    public function store(OrderRequest $request) :JsonResponse
    {
        $slugs= getCategories(13);
        // dd($slugs);
        // dd($request->all());
        // Check the post is product
        $postInfo= Post::published()
        ->type('post')->newest()
        ->taxonomy('category', $slugs)
        ->find($request->product_id);

        if(!$postInfo) {
            abort(404);
        }
        // UPLOAD LOGO
        if ($request->logo ?? null) {
            $file= uploadBase64($request->logo, 'portal');
            $logo= str_replace(config('filesystems.disks.portal.root_val'), '', $file);
        }

        $price= $postInfo->price;
        $title= $postInfo->title;
        // dd($price);
        $userInfo= auth()->user();
        $marketer= $request->marketer;
        $commission = (float)round($price * $marketer->commission / 100);
        $marketerDiscount = (float)$marketer->discount;
        $discount = (float)round($price * $marketerDiscount / 100);
        $total = $price - $discount;
        // $postInfo= $post->toArray();
        
        $orderData= [
            "store_id" => $postInfo->store_id,
            "marketer_id" => $marketer->id,
            "title" => $postInfo->title,
            "name" => $request->name,
            "phone" => $request->phone,
            "email" => $request->email,
            "meta" => [
                'post_id'=> $postInfo->ID,
                "logo"=> $logo ?? '',
                "code"=> $marketer->code,
                "commission"=> $commission,
                "marketer_discount"=> $marketerDiscount,
                "discount"=> $discount,
                "price" => $price,
                "total"=> $total,
                "notes"=> $request->notes ?? '',
            ],
        ];
        // dd($orderData);
        if ($total == 0) {
            $order= Order::create($orderData);
            return $this->sendResponse(new OrderResource($order), __('main.done'));
        }
        $token= (string) Str::uuid();
        $data= [
            'user_id'=> $userInfo->id,
            'marketer_id'=> $marketer->id,
            'token'=> $token,
            'amount'=> $total,
            'status'=> 'new',
            'meta'=> [
                'success_url'=> $request->success_url,
                'failed_url'=> $request->failed_url,
                'order_data'=> $orderData,
            ],
        ];
        // dd($data);
        $payment= Payment::create($data);
        // dd($payment->toArray());
        // Init Payment
        
        $data= [
            // 'payment_method_id'=> $paymentMethod,
            'token'=> $token,
            'amount'=> $price,
            'title'=> $title,
            'customer'=> [
                'name'=> $marketer->name,
                'email'=> $marketer->email,
                'phone'=> $marketer->phone,
            ],
            // 'url'=> "http://sehola.net/my_fatoora/?token=".$token,
            'url'=> route('orders.finish_order')."?token=".$token,
        ];
        // dump($data);
        $checkoutInfo = $this->perpareCheckout($data);
        $payment->meta= array_merge($payment->meta, ['payment_info'=> $checkoutInfo]);
        // dd($checkoutInfo);
        if ($checkoutInfo['error'] ?? false) {
            $payment->status = 'error';
            $payment->save();
            return $this->sendError(__('main.faild'), [], 422);
        }
        $payment->status = 'processing';
        $payment->save();
        // dd($payment->toArray());
        // return redirect($checkoutInfo['url']);
        return $this->sendResponse(['url'=> $checkoutInfo['url']], '');
    }

    /**
     * Create and prepar to pay.
     *
     * @return View
     */
    public function finishOrder(Request $request) :RedirectResponse
    {
        // dd($request->all());
        $paymentId= $request->paymentId ?? null;
        if(!$paymentId){
            abort(404);
        }

        $token= $request->token ?? null;
        // dump($token);
        if(!$token){
            abort(404);
        }
        $payment= Payment::where('token', $token)->first();
        if(!$payment) {
            abort(404);
        }
        //
        if ('done' == $payment->status) {
            $url= addParamsToURL($payment->failed_url, ['error_message'=> __('main.done_before') ] );
            return redirect()->to($url);
        }
        
        // GET PAYMENT INFO FROM 
        $paymentInfo= $this->getPaymentInfo($paymentId);
        // dd($paymentInfo, $paymentId);
        
        $payment->payment_id = $paymentId;
        $payment->meta= array_merge($payment->meta, ['response'=> json_decode(json_encode($paymentInfo), true)]);
        if ($paymentInfo->error ?? false) {
            $payment->status = 'error';
            $payment->save();

            $url= addParamsToURL($payment->failed_url, ['error_message'=> __('main.failed') ] );
            return redirect()->to($url);
        }
        $payment->save();
        
        if('Paid' != $paymentInfo->InvoiceStatus){
            $payment->status = 'error';
            $payment->save();

            $url= addParamsToURL($payment->failed_url, ['error_message'=> __('main.failed') ] );
            return redirect()->to($url);
        }
        $payment->status = 'done';
        $payment->save();

        // Saved to System DB
        $orderData= $payment->meta['order_data'];
        // dd($orderData);
        $order= Order::create($orderData);

        $url= addParamsToURL($payment->success_url, ['message'=> __('main.done') ] );
        return redirect()->to($url);
    }
}