<?php

namespace App\Http\Controllers\Web;

use App\Http\Requests\Web\OrderRequest;
use App\Models\Cart;
use App\Models\Category;
use App\Models\Cobon;
use App\Models\Order;
use App\Models\OrderPayment;
use App\Models\Reservation;
use App\Models\WorkDay;
use App\Services\Integration\Integration\SMS;
use App\Services\Integration\Integration\Connection;
use App\Services\Interfaces\CartRepositoryInterface;
use App\Services\Interfaces\OrderRepositoryInterface;
use App\Services\Interfaces\RoomRepositoryInterface;
use App\Services\Repositories\TableNumberRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\View\View;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    private $view = 'web.pages.carts.';
    private $cartRepository ;
    private $orderRepository ;
    private Connection $connection ;


    public function __construct(
        CartRepositoryInterface $cartRepository,
        OrderRepositoryInterface $orderRepository,
        Connection $connection,
    )
    {
        $this->cartRepository = $cartRepository;
        $this->orderRepository = $orderRepository;
        $this->connection = $connection;
    }


    public function order(OrderRequest $request)
    {
        $request->merge(['url'=>url()->previous()]);
        // if ($request->status == 'room')
        // {
        //     $reservation_id = Session::get('reservation_id');

        //     if (!$reservation_id)
        //     {
        //         Session::put(['order'=>true]);
        //         Session::put(['room_id'=>$request->room_id]);
        //         $response =
        //         [
        //             'status' => 200,
        //             'data' => route('web.reservation'),
        //             'message' => __('web.success'),
        //         ];
        //         return $response;
        //     }
        // }
        $response = $this->orderRepository->pay($request);
        return $response;
    }

    public function paymentStatus(Request $request)
    {
        $lang = getCurrentLocale();
        if (isset($_GET['paymentId'])) {
            // $username=Config::get('app.username');
            // $password= Config::get('app.password');
            // $tokenApi=Config::get('app.tokenApi');
            // $transaction=Config::get('app.transaction');

            // $curl = curl_init();
            // curl_setopt($curl, CURLOPT_URL, $tokenApi);
            // curl_setopt($curl, CURLOPT_POST, 1);
            // curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            // curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('grant_type' => 'password', 'username' => $username, 'password' => $password)));
            // $result = curl_exec($curl);
            // $error = curl_error($curl);
            // $info = curl_getinfo($curl);
            // curl_close($curl);
            // $json = json_decode($result, true);
            // $access_token = $json['access_token'];
            // $token_type = $json['token_type'];
            // if (isset($_GET['paymentId'])) {
            //     $id = $_GET['paymentId'];
            // }
            // $url = $transaction . $id;
            // $soap_do1 = curl_init();
            // curl_setopt($soap_do1, CURLOPT_URL, $url);
            // curl_setopt($soap_do1, CURLOPT_CONNECTTIMEOUT, 10);
            // curl_setopt($soap_do1, CURLOPT_TIMEOUT, 10);
            // curl_setopt($soap_do1, CURLOPT_RETURNTRANSFER, true);
            // curl_setopt($soap_do1, CURLOPT_SSL_VERIFYPEER, false);
            // curl_setopt($soap_do1, CURLOPT_SSL_VERIFYHOST, false);
            // curl_setopt($soap_do1, CURLOPT_POST, false);
            // curl_setopt($soap_do1, CURLOPT_POST, 0);
            // curl_setopt($soap_do1, CURLOPT_HTTPGET, 1);
            // curl_setopt($soap_do1, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Accept: application/json', 'Authorization: Bearer ' . $access_token));
            // $result_in = curl_exec($soap_do1);
            // $err_in = curl_error($soap_do1);
            // $file_contents = htmlspecialchars(curl_exec($soap_do1));
            // curl_close($soap_do1);
            // $getRecorById = json_decode($result_in, true);

            $createPay = config('app.callback');
            $access_token = config('app.accessToken');
            $post_string = '{ 
                "Key": "' . $request->paymentId . '",
                "KeyType": "PaymentId"
            }';
            //$url = $transaction . $id;
            $soap_do1 = curl_init();
            curl_setopt($soap_do1, CURLOPT_URL, $createPay);
            curl_setopt($soap_do1, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($soap_do1, CURLOPT_TIMEOUT, 10);
            curl_setopt($soap_do1, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($soap_do1, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($soap_do1, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($soap_do1, CURLOPT_POST, true);
            curl_setopt($soap_do1, CURLOPT_POSTFIELDS, $post_string);
            curl_setopt($soap_do1, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($post_string), 'Accept: application/json', 'Authorization: Bearer ' . $access_token));
            $result_in = curl_exec($soap_do1);
            $info = curl_getinfo($soap_do1);
            $err_in = curl_error($soap_do1);
            $file_contents = htmlspecialchars(curl_exec($soap_do1));
            curl_close($soap_do1);
            $getRecorById = json_decode($result_in, true);
            // var_dump($getRecorById);exit;
            // dd($getRecorById);
            // var_dump($customFiles);exit;
            if(!is_null($getRecorById['Data']))
            {
                $payment = OrderPayment::where('payment_id',$getRecorById['Data']['InvoiceId'])->first();
                if ($getRecorById['Data']['InvoiceStatus'] == 'Paid' && $payment) {
                    $order = $payment->order;

                    $order->restore();
                    $payment->update
                    ([
                        'payment_log'=>$result_in,
                    ]);
                    $reservation_id = Session::get('reservation_id');
                    $reservation = Reservation::onlyTrashed()->find($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',Auth::user()->id)->delete();
                    Session::forget(['order','room_id','reservation_id']);
                    session()->flash('success', __('web.success'));
                    return redirect($lang.'/profile');
    
    
                }
            }
        }
        session()->flash('error',__('web.failed'));
        return redirect($lang.'/cart');
    }
    //
    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 saveOrderTest($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($data);
        
        
        
        
        
        $order = Order::find($id);
        $url = Config::get('app.baseUrl').'orders';
        $branch_id = Config::get('app.branch_id');
        $products = [];
        foreach($order->products as $row)
        {
            $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, 
                "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, 
            "discount_amount" => '10', 
            'discount_type'=>'1',
            "rounding_amount" => 0, 
            "total_price" => $order->payment->total, 
            "tax_exclusive_discount_amount" => $order->payment->tax_val, 
            "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
        ];
        $data['table_id'] = '9d5c786c-37f8-4820-871a-b24519af4742';
        // 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($url, $body);
    }
    
    
    

}
