<?php

namespace App\Http\Controllers\Admin;

use App\Models\Order;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Models\BrandPackageOrder;
use App\Http\Controllers\Controller;
use App\Models\BrandPackage;

class OrderController extends Controller
{

    public function index(){
        $pageTitle = 'Order Lists';
        $orders = Order::where('status','!=',5)->with(['service', 'category', 'user'])->orderBy('created_at', 'desc')->paginate(getPaginate(12));
        return view('admin.orders.index',compact('pageTitle','orders'));
    }

    public function edit($id){
        $pageTitle = 'Order Details';
        $order = Order::with(['service', 'user', 'category'])->findOrFail($id);
        return view('admin.orders.edit',compact('pageTitle','order'));
    }

    public function pendingOrder(){
        return $this->getOrder(0, 'Pending Orders');
    }

    public function processingOrder(){
        return $this->getOrder(1, 'Processing Orders');
    }

    public function completeOrder(){
        return $this->getOrder(2, 'Complete Orders');
    }

    public function cancelOrder(){
        return $this->getOrder(3, 'Cancelled Orders');
    }

    public function refundOrder(){
        return $this->getOrder(4, 'Refund Orders');
    }


    public function update(Request $request,$id){

        $order = Order::findOrFail($id);
        if( $order->remains != 0){
            $order->start_count = $request->start_count;
            $order->remains  = ($order->quantity - $request->start_count);
        }
        $order->status = $request->status;
        $user = $order->user;

        if ($request->status == 4 && in_array($order->status, [2, 3])) {
            return back()->withErrors(['error' => 'This order is not refundable']);
        }

        if ($request->filled('reason')) {
            $order->reason = $request->reason;
        }

        $order->save();

        $notifications = [
            0 => 'PENDING_ORDER',
            1 => 'PROCESSING_ORDER',
            2 => 'COMPLETED_ORDER',
            3 => 'CANCELLED_ORDER',
            4 => 'REFUNDED_ORDER',
        ];

        if ($request->status == 4) {
            $user->balance += $order->price;
            $user->save();

          //Create Transaction
          $transaction               = new Transaction();
          $transaction->user_id      = $user->id;
          $transaction->amount       = $order->price;
          $transaction->post_balance = $user->balance;
          $transaction->trx_type     = '+';
          $transaction->remark       = "refund_order";
          $transaction->details      = 'Refund for Order ' . @$order->service->name;
          $transaction->trx          = getTrx();
          $transaction->save();

            notify($user, $notifications[$request->status], [
                'service_name' => @$order->service->name,
                'price'        => showAmount($order->price),
                'currency'     => gs()->cur_text,
                'post_balance' => showAmount($user->balance),
                'trx'          => $transaction->trx,
            ]);

        } else {
            notify($user, $notifications[$request->status], [
                'service_name' => @$order->service->name,
                'username'     => $user->username,
                'price'        => $order->price,
            ]);
        }

        $notify[] = ['success', 'Oder has been updated successfully'];
        return back()->withNotify($notify);
    }

    public function filter(Request $request)
    {
        $pageTitle = 'Search Orders';

        $query =  Order::with(['service', 'category', 'user']);

        if($request->filled('service')) {
            $query->whereHas('service', function($query) use ($request) {
                $query->where('name', 'LIKE', '%' . $request->input('service') . '%');
            });
        }

        if($request->filled('order_no')) {
           $ab =  $query->where('order_no', 'LIKE', '%' . $request->input('order_no') . '%')->get();
        }

        if($request->filled('username')) {
            $query->whereHas('user', function($query) use ($request) {
                $query->where('username', 'LIKE', '%' . $request->input('username') . '%');
            });
        }

        if($request->filled('status')) {
            $status = $request->input('status');
            if(is_numeric($status)) {
                $query->where('status', $status);
            }
        }
        $orders = $query->latest()->paginate(getPaginate());

        return view('admin.orders.index',compact('pageTitle','orders'));
    }

    //brand package order
    public function getBrandPackage(){
        $pageTitle = 'Order Lists';
        $orders = BrandPackageOrder::where('status','!=',5)->with('user')->orderBy('created_at','desc')->paginate(getPaginate(12));
        return view('admin.brandOrders.index',compact('pageTitle','orders'));
    }

    public function bPedit($id){
        $pageTitle = 'Order Details';
        $order = BrandPackageOrder::with('user')->findOrFail($id);
        return view('admin.brandOrders.edit',compact('pageTitle','order'));
    }

    public function bPpendingOrder(){
        return $this->getBrandPackageOrder(0, 'Pending Orders');
    }

    public function bPprocessingOrder(){
        return $this->getBrandPackageOrder(1, 'Processing Orders');
    }

    public function bPcompleteOrder(){
        return $this->getBrandPackageOrder(2, 'Complete Orders');
    }

    public function bPcancelOrder(){
        return $this->getBrandPackageOrder(3, 'Cancelled Orders');
    }

    public function bPrefundOrder(){
        return $this->getBrandPackageOrder(4, 'Refund Orders');
    }

    public function updateBrandPackage(Request $request,$id){

        $order = BrandPackageOrder::findOrFail($id);
        $order->status = $request->status;
        $user = $order->user;

        if ($request->status == 4 && in_array($order->status, [2, 3])) {
            return back()->withErrors(['error' => 'This order is not refundable']);
        }

        if ($request->filled('reason')) {
            $order->reason = $request->reason;
        }

        $order->save();

        $notifications = [
            0 => 'PENDING_ORDER',
            1 => 'PROCESSING_ORDER',
            2 => 'COMPLETED_ORDER',
            3 => 'CANCELLED_ORDER',
            4 => 'REFUNDED_ORDER',
        ];

        if ($request->status == 4) {
            $user->balance += $order->price;
            $user->save();

          //Create Transaction
          $transaction               = new Transaction();
          $transaction->user_id      = $user->id;
          $transaction->amount       = $order->price;
          $transaction->post_balance = $user->balance;
          $transaction->trx_type     = '+';
          $transaction->remark       = "refund_order";
          $transaction->details      = 'Refund for Order ' . @$order->name;
          $transaction->trx          = getTrx();
          $transaction->save();

            notify($user, $notifications[$request->status], [
                'service_name' => @$order->name,
                'price'        => showAmount($order->price),
                'currency'     => gs()->cur_text,
                'post_balance' => showAmount($user->balance),
                'trx'          => $transaction->trx,
            ]);

        } else {
            notify($user, $notifications[$request->status], [
                'service_name' => @$order->name,
                'username'     => $user->username,
                'price'        => $order->price,
            ]);
        }

        $notify[] = ['success', 'Brand Package has been updated successfully'];
        return back()->withNotify($notify);
    }

    public function bPfilter(Request $request)
    {
        $pageTitle = 'Search Orders';

        $query =  BrandPackageOrder::with('user');

        if ($request->filled('service')) {
           $query->where('name', 'LIKE', '%' . $request->input('service') . '%');
        }


        if ($request->filled('username')) {
            $query->whereHas('user', function($query) use ($request) {
                $query->where('username', 'LIKE', '%' . $request->input('username') . '%');
            });
        }

        if ($request->filled('status')) {
            $status = $request->input('status');
            if(is_numeric($status)) {
                $query->where('status', $status);
            }
        }
        $orders = $query->latest()->paginate(getPaginate());

        return view('admin.brandOrders.index',compact('pageTitle','orders'));
    }

    //end bp orders


    public function getOrder($status, $pageTitle){
        $orders = Order::where('status', $status)
                       ->with(['service', 'user', 'category'])
                       ->latest()
                       ->paginate(getPaginate(12));
        return view('admin.orders.index', compact('pageTitle', 'orders'));
    }

    public function getBrandPackageOrder($status, $pageTitle){
        $orders = BrandPackageOrder::where('status', $status)
                                    ->with('user')
                                    ->latest()
                                    ->paginate(getPaginate(12));
        return view('admin.brandOrders.index', compact('pageTitle', 'orders'));
    }


}
