<?php

namespace App\Http\Controllers\User;

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

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }

    public function index(Request $request, $stage = null)
    {
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $data['orders'] = Order::with(['store:id,name', 'gateway:id,name'])
            ->where('status', 1)
            ->where('user_id', $this->user->id)
            ->when($stage == 'new-arrivals', function ($query) {
                return $query->where("stage", 0);
            })
            ->when($stage == 'in-process', function ($query) {
                return $query->where("stage", 2);
            })
            ->when($stage == 'out-for-delivery', function ($query) {
                return $query->where("stage", 3);
            })
            ->when($stage == 'delivered', function ($query) {
                return $query->where("stage", 1);
            })
            ->when($stage == 'cancel', function ($query) {
                return $query->where("stage", 4);
            })
            ->when(isset($search['orderNumber']), function ($query) use ($search) {
                return $query->where("order_number", 'LIKE', '%' . $search['orderNumber'] . '%');
            })
            ->when(isset($search['store_name']), function ($query) use ($search) {
                return $query->whereHas('store', function ($query) use ($search) {
                    return $query->where('name', 'LIKE', '%' . $search['store_name'] . '%');
                });
            })
            ->when(isset($search['email']), function ($query) use ($search) {
                return $query->where("email", 'LIKE', '%' . $search['email'] . '%');
            })
            ->when(isset($search['amount']), function ($query) use ($search) {
                return $query->where("total_amount", 'LIKE', '%' . $search['amount'] . '%');
            })
            ->when(isset($search['stage']), function ($query) use ($search) {
                return $query->where("stage", $search['stage']);
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->orderBy('id', 'desc')->paginate(basicControl()->paginate);

        $statistics = Order::where('user_id', $this->user->id)
            ->selectRaw('COUNT(id) AS totalOrders')
            ->selectRaw('COUNT((CASE WHEN stage = 0  THEN id END)) AS newArrivals')
            ->selectRaw('COUNT((CASE WHEN stage = 1  THEN id END)) AS delivered')
            ->selectRaw('COUNT((CASE WHEN stage = 2 OR stage = 3  THEN id END)) AS pending')
            ->get()->toArray();

        $data['orderRecords'] = collect($statistics)->collapse();
        $data['remainingOrders'] = optional($this->user->plan)->order_num - $data['orderRecords']['totalOrders'];
        return view($this->theme . 'user.orders.index', $data);
    }

    public function details($orderNumber)
    {
        $order = Order::own($this->user->id)->with('shipping', 'details', 'details.product')->where('status', 1)->where('order_number', $orderNumber)->firstOrFail();
        return view($this->theme . 'user.orders.details', compact('order'));
    }

    public function singleStageChange(Request $request, $orderId)
    {
        $stageMapping = [
            'Delivered' => 1,
            'In Process' => 2,
            'Out For Delivery' => 3,
            'Cancel' => 4
        ];
        if (!isset($stageMapping[$request->stage])) {
            session()->flash('error', 'Invalid stage.');
            return back();
        }

        $order = Order::own($this->user->id)->where('id', $orderId)->firstOrFail();

        if ($request->stage == 'Delivered' && $order->gateway_id == 0 && $order->is_transaction == 0) {
            $transaction = new Transaction();
            $transaction->user_id = $order->user_id;
            $transaction->amount = $order->payment_amount;
            $transaction->charge = 0;
            $transaction->trx_type = '+';
            $transaction->trx_id = $order->utr;
            $order->transactional()->save($transaction);
            $order->is_transaction = 1;
        }
        $order->stage = $stageMapping[$request->stage];
        $order->save();
        session()->flash('success', 'Stage Has Been Changed To ' . $request->stage);
        return back();
    }


    public function multipleStageChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select any ID');
            return response()->json(['error' => 1]);
        } else {
            $stageMapping = [
                'Delivered' => 1,
                'In Process' => 2,
                'Out For Delivery' => 3,
                'Cancel' => 4
            ];

            $orders = Order::own($this->user->id)->whereIn('id', $request->strIds)->get();
            foreach ($orders as $order) {
                if ($request->stage == 'Delivered' && $order->gateway_id == 0 && $order->is_transaction == 0) {
                    $transaction = new Transaction();
                    $transaction->user_id = $order->user_id;
                    $transaction->amount = $order->payment_amount;
                    $transaction->charge = 0;
                    $transaction->trx_type = '+';
                    $transaction->trx_id = $order->utr;
                    $order->transactional()->save($transaction);
                    $order->is_transaction = 1;
                }
                $order->stage = $stageMapping[$request->stage];
                $order->save();
            }
            session()->flash('success', 'Stage Has Been Changed To ' . $request->stage);
            return back();
        }
    }
}
