<?php

namespace App\Services\Repositories;

use App\Models\Cart;
use App\Models\Cobon;
use App\Models\Order;
use App\Models\OrderPayment;
use App\Models\OrderProduct;
use App\Models\Reservation;
use App\Services\Integration\Integration\SMS;
use App\Services\Interfaces\OrderRepositoryInterface;
use App\Services\Payment\MyFatoorahPayment;
use App\Services\Payment\PaymentService;
use App\Services\Integration\Integration\Connection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;

class OrderRepository implements OrderRepositoryInterface
{
    private Connection $connection ;
    
    public function __construct(
        Connection $connection,
    )
    {
        $this->connection = $connection;
    }
    public function get(Request $request)
    {
        $query = Order::orderBy('id', 'DESC');

        if ($request->id) {
            $query->where('id', $request->id);
        }
        if ($request->user_id) {
            $query->where('user_id', $request->user_id);
        }
        if ($request->phone) {
            $query->whereHas('user', function ($q) use ($request){
                $q->where('phone',$request->phone);
            });
        }

        if ($request->cobon_id)
        {
            $query->whereHas('payment', function($q) use($request){
                $q->where('cobon_id', $request->cobon_id);
            });
        }

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        if ($request->paginate ?? null) {
            $clients= $query->paginate(50);
        }else{
            $clients=$query->cursor();
        }

        return $clients;
    }

    public function getItem(Order $order):Order
    {
        $order->with(['products','payment']);
        return $order ;
    }
    //
    public function save(Request $request, ?Order $order): Order
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        // dd($data);
        if (!$order) {
            $order = Order::create($data);
        } else {
            $order->update($data);
        }
        return $order;
    }

    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $client= Order::withTrashed()->find($id);
        if ($client) {
            if ($client->deleted_at) {
                $client->forceDelete();
            } else {
                $client->delete();
            }
            return [ ['message'=> __('dashboard.deletedDone')]];
        } else{
            return [ ['message'=> __('dashboard.noResult')], 400];
        }
    }

    /**
     * Remove several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        $ids= $request->ids;
        $query= Order::whereIn('id', $ids);
        if ($request->force) {
            $deleted= $query->onlyTrashed()->forceDelete();
        } else {
            $deleted= $query->delete();
        }
        if($deleted){
            return [['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

    /**
     * Restore the specified client from storage.
     *
     * @param Request $request
     * @param int $id
     * @return array
     */
    public function restore(Request $request, int $id) :array
    {
        $client= Order::withTrashed()->find($id);
        if ($client) {
            $client->restore();
            return [['message'=> __('dashboard.saveDone')]];
        }
        return [['message'=> __('dashboard.noResult')], 400];

    }

    /**
     * Restore several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function restoreAll(Request $request) :array
    {
        $ids= $request->ids;
        Order::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }


    public function pay(Request $request)
    {
        $cart = new CartRepository();
        $calculate = $cart->calculate($request);
        $carts = $cart->get($request);
        $my_fatoorah_payment = new MyFatoorahPayment();
        $payment = new PaymentService($my_fatoorah_payment);
        $token = bcrypt(rand(11111,99999).time());
        $duration = settings('pickup_hours');
        $date = date('Y-m-d');
        if ('pickup' == $request->status) {
            $dateTime= new \DateTime($request->time);
            $periodInMinutes= 60 * $duration; // In minutes
            $dateTime->add(new \DateInterval('PT'.$periodInMinutes.'M')); // Adds 15 minutes and 10 seconds
            $endDateTime= $dateTime->format('Y-m-d H:i');
            $startDateTimes= explode(' ', $request->time);
            $endDateTimes= explode(' ', $endDateTime);
            // dd($startDateTimes, $dateTime, $endDateTimes);
            $date = $startDateTimes[0] ?? $date;
            $start_time = $startDateTimes[1] ?? '';
            $end_time = $endDateTimes[1] ?? '';
        }
        $reservation_id = $request->status == 'room' ? Session::get('reservation_id') : null;
        if ($reservation_id)
        {
            $reservation = Reservation::withTrashed()->find($reservation_id);
            $date = $reservation->date;
        }
        $data= [
            'token'=>$token,
            'date'=>$date,
            'date'=>$date,
            'start_time'=> $start_time ?? date('H:i:s'),
            'end_time'=> $end_time ?? null,
            'length_time'=>$duration,
            'status'=>$request->status,
            'user_id'=>Auth::user()->id,
            'room_id'=>$request->status == 'room' ? $request->room_id : null ,
            'table_number_id'=>$request->status == 'table' ? $request->table_id : null ,
            'reservation_id'=>$request->status == 'room' ? $reservation_id : null ,
        ];
        // dd($data);
        $order = Order::create($data);
        OrderPayment::create([
            'order_id'=>$order->id,
            'total_products'=>$calculate['total_products'],
            'discount'=>$calculate['discount'],
            'tax'=>$calculate['tax'],
            'tax_val'=>settings('tax'),
            'total'=>$calculate['final_total'],
            'cobon_id'=>$calculate['cobon_id'],
        ]);
        foreach ($carts as $row)
        {
            OrderProduct::create([
                'order_id'=>$order->id,
                'count'=>$row->count,
                'product_cost'=>$row->product->price,
                'total'=>($row->product->price * $row->count),
                'product_id'=>$row->product_id,
            ]);
        }
        if($calculate['total'] > 0)
        {
            $order->delete();
            $content =
                [
                    'id'=>$order->id,
                    'type'=>'order',
                    'total'=>$calculate['final_total'],
                    'token'=>$token,
                    'url'=>$request->url,
                    'status'=>__('web.order'),
                    'payment_status'=>route('web.order.status'),
                ];
            $response = $payment->payment($content);
        }
        else
        {
            Cart::where('user_id',Auth::user()->id)->delete();
            $cobon = Cobon::find($order->cobon_id);
            if ($cobon)
            {
                $cobon->update(['count'=>($cobon->count - 1)]);
            }
            if($order->room_id)
            {
                $message = 'تم تأكيد حجزك رقم ('.$reservation->id.') بنجاح في مطعم The Chord بتاريخ ( '.$reservation->date.') و وقت (وقت الحجز '.$reservation->start_time.'-'.$reservation->end_time.') لغرفة ('.$reservation->room->currentDescription->title.') ';
                
            }
            else
            {
                $message = 'تم تأكيد طلبك رقم ('.$order->id.' ) بنجاح في مطعم The Chord بتاريخ ('.$order->date.' )';
            }
            // dd($order->id);
            $this->postOrder($order->id);
            // $phone = $reservation->user->phone;
            // SMS::sendSMS($phone,$message);
            $response =
            [
                'status' => 200,
                'data'=> route('web.profile'),
                'message' => __('web.success'),
            ];
        }
        return $response;
    }
    
    
    public function postOrder($id)
    {
        $order = Order::find($id);
        $url = Config::get('app.baseUrl').'orders';
        $branch_id = Config::get('app.branch_id');
        $products = [];
        // dd($order->products);
        foreach($order->products as $row)
        {
            // $amountDetails = getAmountDetails($row->total);
            
            $product_item = 
            [
                "product_id" => $row->product_id, 
                "quantity" => $row->count, 
                "discount_quantity" => 0, 
                "unit_price" => $row->product_cost, 
                "discount_amount" => 0, 
                "total_price" => $row->total,
                // "total_price" => $amountDetails['amount'], //NEWLY_ADDED
                "tax_exclusive_discount_amount" => 0, 
                "tax_exclusive_unit_price" => 0, 
                "tax_exclusive_total_price" => 0, 
            ];
            array_push($products,$product_item);
        }
        
        $currentDueAt= $order->date.' '. ($order->start_time ?? '00:00:00');
        $dateTime = new \DateTime($currentDueAt, new \DateTimeZone(config('app.timezone')));
        $openedTime = new \DateTime(date('Y-m-d H:i:s'), new \DateTimeZone(config('app.timezone')));
        // Convert the DateTime to GMT timezone
        $dateTime->setTimezone(new \DateTimeZone('UTC'));
        $openedTime->setTimezone(new \DateTimeZone('UTC'));
        $dueAt= $dateTime->format( 'Y-m-d H:i:s' );
        $openedAt= $openedTime->format( 'Y-m-d H:i:s' );
        // dump($currentDueAt);
        $notes = 'Customer Phone : '.$order->user->phone;
        // if ('table' == $order->status) 
        // {
        //     $notes .= ' | Table : '.$order->table->number;
        // }
        if ('room' == $order->status) 
        {
            $notes .= ' | Reservation Number : '.$order->reservation_id;
        }
        $data = 
        [
            "reference"=> $order->id.'-'.rand(),
            "type" => 1, 
            "source" => 2, 
            "guests" => 2, 
            "status" => 1, 
            "business_date" => date('Y-m-d'), 
            "subtotal_price" => $order->payment->total_products ?? 0, 
            // "discount_amount" => $order->payment->discount ?? 0, 
            "rounding_amount" => 0, 
            "total_price" => $order->payment->total_products ?? 0, 
            "tax_exclusive_discount_amount" => $order->payment->tax_val ?? 0, 
            "branch_id" => $branch_id, 
            "products" => $products, 
            "opened_at" => $openedAt, 
            "due_at" => strtotime($dueAt) < time() ? date('Y-m-d H:i:s') : $dueAt,
            'customer_notes'=>$notes
        ];
        // dd($products);
        if($order->payment->discount)
        {
            $data["discount_amount"] = $order->payment->discount; 
            $data['discount_type'] = '1';
        }
        if ('table' == $order->status) 
        {
            $data["table_id"] = $order->table_number_id;
        }
        // dump($data);
        $response= $this->connection->create($url,$data);
        $body = json_decode($response->body());
        // dd($body);
    }
    
    public function getCobons($cobon_id)
    {
        $orders = Order::$query->whereHas('payment', function($q) use($cobon_id){
                $q->where('cobon_id', $cobon_id);
            })->get();
        return $orders;
    }
}
