<?php

namespace App\Http\Controllers\Restaurant;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Restaurant;
use App\Models\Transaction;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index()
    {
        $pageTitle = 'All Orders';
        $orders = $this->filterOrders();
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function active()
    {
        $pageTitle = 'Active Orders';
        $orders = $this->filterOrders('active');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function processing()
    {
        $pageTitle = 'Processing Orders';
        $orders = $this->filterOrders('processing');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function onDelivery()
    {
        $pageTitle = 'Ongoing Delivery';
        $orders = $this->filterOrders('onDelivery');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function delivered()
    {
        $pageTitle = 'Delivered Orders';
        $orders = $this->filterOrders('delivered');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function completed()
    {
        $pageTitle = 'Completed Orders';
        $orders = $this->filterOrders('completed');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function cancelled()
    {
        $pageTitle = 'Cancelled Orders';
        $orders = $this->filterOrders('cancelled');
        return view('Template::restaurant.order.index', compact('pageTitle', 'orders'));
    }

    public function details($id)
    {
        $pageTitle = 'Order details';
        $order = Order::where('restaurant_id', authRestaurantId())->with('items', 'items.food')->findOrFail($id);
        return view('Template::restaurant.order.details', compact('pageTitle', 'order'));
    }

    public function cancelOrder($id)
    {
        $order = Order::where('restaurant_id', authRestaurantId())
            ->whereNotIn('status', [
                Status::ORDER_INITIATED,
                Status::ORDER_CANCELLED,
                Status::ORDER_DELIVERED,
                Status::ORDER_COMPLETED
            ])
            ->findOrFail($id);

        $user = $order->user;
        $trx  = 'N/A';

        //if payment done refund
        if ($order->payment_status == Status::PAID && $order->total_price > 0) {
            $user->balance += $order->total_price;
            $user->save();
            $trx = getTrx();

            $transaction               = new Transaction();
            $transaction->user_id      = $order->user_id;
            $transaction->amount       = $order->total_price;
            $transaction->post_balance = $user->balance;
            $transaction->charge       = 0;
            $transaction->trx_type     = '+';
            $transaction->details      = "Refund Completed for order cancellation";
            $transaction->trx          = $trx;
            $transaction->remark       = 'order_refund';
            $transaction->save();
        }

        $order->status = Status::ORDER_CANCELLED;
        $order->save();

        notifyUser('user', 'ORDER_CANCELLED_USER', $order, $trx);
        notifyUser('restaurant', 'ORDER_CANCELLED_RESTAURANT', $order, $trx);

        return returnBack('Order cancelled successfully', 'success');
    }

    public function onDeliveryOrder($id)
    {
        $order = Order::where('restaurant_id', authRestaurantId())
            ->where('status', Status::ORDER_PROCESSING)
            ->findOrFail($id);

        $order->status = Status::ORDER_ON_DELIVERY;
        $order->save();

        notifyUser('user', 'ORDER_ON_DELIVERY_USER', $order);
        notifyUser('restaurant', 'ORDER_ON_DELIVERY_RESTAURANT', $order);

        return returnBack('Order is out for delivery', 'success');
    }

public function deliverOrder($id)
{
    $order = Order::where('restaurant_id', authRestaurantId())
        ->where('status', Status::ORDER_ON_DELIVERY)
        ->findOrFail($id);

    // نغير الحالة لـ Delivered
    $order->status = Status::ORDER_DELIVERED;
    $order->save();

    notifyUser('user', 'ORDER_DELIVERED_USER', $order);
    notifyUser('restaurant', 'ORDER_DELIVERED_RESTAURANT', $order);

    // نغير الحالة مباشرة لـ Completed
    $order->status = Status::ORDER_COMPLETED;
    $order->save();

    $restaurant = $order->restaurant;
    $trx = getTrx();

    if ($order->payment_type == Status::PAYMENT_CASH_ON_DELIVERY) {
        // في حالة الدفع كاش، نخصم العمولة من رصيد المطعم
        $codCharge = $order->total_price * (gs('cod_percent_charge') / 100) + gs('cod_fixed_charge');
        $restaurant->balance -= $codCharge;
        $restaurant->save();

        $transaction = new Transaction();
        $transaction->restaurant_id = $restaurant->id;
        $transaction->amount = $codCharge;
        $transaction->post_balance = $restaurant->balance;
        $transaction->charge = 0;
        $transaction->trx_type = '-';
        $transaction->details = "Cash on Delivery charge";
        $transaction->trx = $trx;
        $transaction->remark = 'cod_charge';
        $transaction->save();
    } else {
        // الدفع أونلاين: نضيف المبلغ للمطعم
        $restaurant->balance += $order->total_price;
        $restaurant->save();

        $transaction = new Transaction();
        $transaction->restaurant_id = $order->restaurant_id;
        $transaction->amount = $order->total_price;
        $transaction->post_balance = $restaurant->balance;
        $transaction->charge = 0;
        $transaction->trx_type = '+';
        $transaction->details = "Payment Completed for order";
        $transaction->trx = $trx;
        $transaction->remark = 'order_completed';
        $transaction->save();
    }

    // نرسل إشعارات الإكمال
    notifyUser('user', 'ORDER_COMPLETED_USER', $order, $trx);
    notifyUser('restaurant', 'ORDER_COMPLETED_RESTAURANT', $order, $trx);

    return returnBack('Order is completed', 'success');
}


    protected function filterOrders($scope = null)
    {
        $orders = Order::where('restaurant_id', authRestaurantId())->where('status', '!=', Status::ORDER_INITIATED);
        if ($scope) {
            $orders = $orders->$scope();
        }
        return $orders->with('user', 'address')->latest()->searchable(['user:username'])->paginate(getPaginate());
    }

    public function delivery()
    {
        $pageTitle  = "Delivery Setting";
        $restaurant = authRestaurant();
        return view('Template::restaurant.delivery_setting', compact('pageTitle', 'restaurant'));
    }

    public function storeDeliverySettings(Request $request)
    {
        $request->validate([
            'delivery_time'     => 'required|numeric|gt:0',
            'delivery_charge'   => 'required|numeric|gte:0',
            'vat'               => 'required|numeric|gte:0'
        ]);

        $restaurant = Restaurant::findOrFail(authRestaurantId());
        $restaurant->delivery_time     = $request->delivery_time;
        $restaurant->delivery_charge   = $request->delivery_charge;
        $restaurant->vat               = $request->vat;
        $restaurant->save();

        return returnBack('Delivery settings updated successfully', 'success');
    }
}
