<?php

namespace App\Http\Controllers\WebHook;

use App\Models\Room;
use App\Models\Order;
use App\Models\Product;
use App\Models\Cobon;
use App\Models\Cart;
use App\Models\Group;
use App\Models\GroupProduct;
use App\Models\TableNumber;
use App\Models\ReservationPayment;
use App\Models\Webhook;
use App\Models\Reservation;
use App\Services\Integration\Integration\SMS;
use App\Models\OrderPayment;
use App\Services\Integration\Integration\Connection;
use Illuminate\Support\Facades\Config;
use App\Services\Interfaces\CategoryRepositoryInterface;
use App\Services\Interfaces\ProductRepositoryInterface;
use App\Services\Interfaces\RoomRepositoryInterface;
use App\Http\Controllers\Controller;
use App\Models\OrderProduct;
use App\Services\Interfaces\GroupRepositoryInterface;
use App\Services\Interfaces\TableNumberRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\Response;
use App\Services\Response\ResponseService;

class WebhookController extends Controller
{

    private CategoryRepositoryInterface $categoryRepository ;
    private GroupRepositoryInterface $groupRepository ;
    private ProductRepositoryInterface $productRepository ;
    private TableNumberRepositoryInterface $tableNumberRepository ;
    private Connection $connection ;


    public function __construct(
        CategoryRepositoryInterface $categoryRepository,
        GroupRepositoryInterface $groupRepository,
        ProductRepositoryInterface $productRepository,
        TableNumberRepositoryInterface $tableNumberRepository,
        Connection $connection,
    )
    {
        $this->categoryRepository = $categoryRepository;
        $this->groupRepository = $groupRepository;
        $this->productRepository = $productRepository;
        $this->tableNumberRepository = $tableNumberRepository;
        $this->connection = $connection;
    }
    public function myfatoorah(Request $request)
    {
        $webhook = Webhook::create(['status'=>'myfatoorah','body'=>json_encode($request->all())]);
        $response = json_decode($webhook,true);
        if($response['EventType'] == 1 ?? null)
        {
            if(isset($response['Data']))
            {
                if(isset($response['Data']['InvoiceId']) && ($response['Data']['TransactionStatus'] == 'SUCCESS' ?? false))
                {
                    $payment = OrderPayment::where('payment_id',$response['Data']['InvoiceId'])->first();
                    if($payment)
                    {
                        $order = $payment->order;
                        if($order->deleted_at)
                        {
                            $order->restore();
                            $payment->update
                            ([
                                'payment_log'=>json_encode($request->all()),
                            ]);
                            
                            $reservation = Reservation::onlyTrashed()->find($order->reservation_id);
                            $cobon = Cobon::find($order->cobon_id);
                            if ($cobon)
                            {
                                $cobon->update(['count'=>($cobon->count - 1)]);
                            }
                            if ($reservation)
                            {
                                $reservation->restore();
                            }
                            
                            if($order->room_id)
                            {
                                $message = 'تم تأكيد حجزك رقم ('.$reservation->id.') بنجاح في مطعم The Chord بتاريخ ( '.$reservation->date.') و وقت (وقت الحجز '.$reservation->start_time.'-'.$reservation->end_time.') لغرفة ('.$reservation->room->currentDescription->name.') ';
                                
                            }
                            else
                            {
                                $message = 'تم تأكيد طلبك رقم ('.$order->id.' ) بنجاح في مطعم The Chord بتاريخ ('.$order->date.' )';
                            }
                            
                            $phone = $order->user->phone;
                            
                            $this->saveOrder($order);
                    
                            SMS::sendSMS($phone,$message);
                        
                            Cart::where('user_id',$order->user_id)->delete();
                        }
                    }
                    $payment = ReservationPayment::where('payment_id',$response['Data']['InvoiceId'])->first();
                    if ($payment) 
                    {
                        $reservation = $payment->reservation;
                        if($reservation->deleted_at)
                        {
                            $reservation->restore();
                            $reservation->payment->update
                            ([
                                'payment_log'=>json_encode($request->all()),
                            ]);
                            $message = 'تم تأكيد حجزك رقم ('.$reservation->id.') بنجاح في مطعم The Chord بتاريخ ( '.$reservation->date.') و وقت (وقت الحجز '.$reservation->start_time.'-'.$reservation->end_time.') لغرفة ('.$reservation->room->currentDescription->title.') ';
                            $phone = $reservation->user->phone;
                            SMS::sendSMS($phone,$message);
                        }
                    }
                }
            }
        }
        
        $response = [
            'status'=>Response::HTTP_OK,
            'message'=>'success',
            'data'=>[]
        ];
        return ResponseService::response($response);
    }
    
    
    public function saveOrder(Order $order)
    {
        $url = Config::get('app.baseUrl').'orders';
        $branch_id = Config::get('app.branch_id');
        $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
        ];
        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);
        //dd($url, $body, $data);
    }
    
    
    
    public function webhook(Request $request)
    {
        Webhook::create(['status'=>'foodics','body'=>json_encode($request->all())]);

        if(isset($request['entity']))
        {
            if($request['entity']['type'] == 'product')
            {
                $this->getProducts();
            }
            elseif($request['entity']['type'] == 'group')
            {
                $this->getGroups();
            }
            elseif($request['entity']['type'] == 'table')
            {
                $this->getTables();
            }
            else
            {
                $this->getGroups();
                $this->getProducts();
                $this->getTables();
            }
        }
        $response = [
            'status'=>Response::HTTP_OK,
            'message'=>'success',
            'data'=>[]
        ];
        return ResponseService::response($response);
    }

    public function getCategories($page = 1)
    {
        $url = Config::get('app.baseUrl').'categories';
        $data = $this->connection->get($url,['page'=>$page]);
        if ($data->successful())
        {
            $data = json_decode($data->body());
            foreach ($data->data as $row)
            {
                $checkItem = $this->categoryRepository->checkItem($row->id);
                if ($checkItem)
                {
                    $this->categoryRepository->update($row,$row->id);
                }
                else
                {
                    $this->categoryRepository->create($row);
                }
            }
            if(!is_null($data->links->next))
            {
                $page = last(explode('?page=',$data->links->next));
                
                $this->getCategories($page);
            }
        }
    }
    
    public function getGroups($page = 1)
    {
        if($page == 1)
        {
            Group::query()->delete();
        }
        $url = Config::get('app.baseUrl').'groups';
        // dump($url);
        $data = $this->connection->get($url,['include'=> 'subgroups','filter[is_deleted]'=>false,'page'=>$page]);
        if ($data->successful())
        {
            $data = json_decode($data->body());
            // dd($data);
            foreach ($data->data ?? [] as $row)
            {
                $checkItem = $this->groupRepository->checkItem($row->id);
                // dump($row);
                if ($checkItem)
                {
                    $this->groupRepository->restore($row,$row->id);
                    // Reset parent_foodics_id 
                    $row->parent_foodics_id = null;
                    $this->groupRepository->update($row,$row->id);
                }
                else
                {
                    $this->groupRepository->create($row);
                }
                
            }

            // SET THE PARENT FOODECIS ID
            foreach ($data->data ?? [] as $row)
            {
                foreach ($row->subgroups ?? [] as $subGroup) {
                    $checkItem = $this->groupRepository->checkItem($subGroup->id);
                    if ($checkItem)
                    {
                        $this->groupRepository->restore($subGroup,$subGroup->id);
                        $this->groupRepository->restore($row,$row->id);
                        $this->groupRepository->updateParentGroup($subGroup->id, $row->id);
                    }
                }
            }
            
            if(!is_null($data->links->next))
            {
                $page = last(explode('?page=',$data->links->next));
                
                $this->getGroups($page);
            }
        }
    }

    public function getProducts($page = 1)
    {
        if($page == 1)
        {
            Product::query()->delete();
            GroupProduct::query()->delete();
        }
        $url = Config::get('app.baseUrl').'products';
        $data = $this->connection->get($url,['include'=> 'groups','page'=>$page]);
        // dd($data);
        if ($data->successful())
        {
            $data = json_decode($data->body());
            
            foreach ($data->data as $row)
            {
                $checkItem = $this->productRepository->checkItem($row->id);
                if ($checkItem)
                {
                    $this->productRepository->restore($row,$row->id);
                    $this->productRepository->update($row,$row->id);
                }
                else
                {
                    $this->productRepository->create($row);
                }
            }
            if(!is_null($data->links->next))
            {
                $page = last(explode('?page=',$data->links->next));
                
                $this->getProducts($page);
            }
        }
    }

    public function getTables($page = 1)
    {
        if($page == 1)
        {
            TableNumber::query()->delete();
        }
        $url = Config::get('app.baseUrl').'tables';
        $data = $this->connection->get($url,['page'=>$page]);
        if ($data->successful())
        {
            $data = json_decode($data->body());

            foreach ($data->data as $row)
            {
                $checkItem = $this->tableNumberRepository->checkItem($row->id);
                if ($checkItem)
                {
                    $this->tableNumberRepository->restore($row,$row->id);
                    $this->tableNumberRepository->update($row,$row->id);
                }
                else
                {
                    $this->tableNumberRepository->create($row);
                }
            }
            if(!is_null($data->links->next))
            {
                $page = last(explode('?page=',$data->links->next));
                
                $this->getTables($page);
            }
        }
    }
}
