<?php
/*
    * Created by VahabDev in Aparat Live
    * Website: https://pourfi.ir
    * Aparat Live: https://www.aparat.com/vahabdev/live
    * Aparat Channel: https://www.aparat.com/vahabdev
    * Rubika Channel: https://rubika.ir/vahabdev
    * Donate: https://reymit.ir/vahabdev
    * Telegram: https://t.me/vahabdev
*/


namespace App\Http\Controllers;

use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class invoiceController extends Controller
{
    public function index(Request $request){
        $uid = Session::get('uid');
        $status = 'all';
        $search = '';
        $q = Order::orderBy('id', 'desc')
            ->where('user_id', $uid)
            ->where('parent_id', '0')
            ->with('products');
        if($request->input('status')){
            if($request->input('status')=='paid'){
                $q->where('status_payment', 'Paid');
                $status = 'paid';
            }
            if($request->input('status')=='unpaid'){
                $q->where('status_payment', 'UnPaid');
                $status = 'unpaid';
            }
        }
        if($request->input('search')){
            $q->where('id', $request->input('search'));
            $search = $request->input('search');
        }
        $list = $q->paginate(10);
        return view('clients.invoices.list',
            compact(
                'list',
                'status',
                'search',
            ));
    }

    public function show($id){
        $uid = Session::get('uid');

        if(!Order::where('id', $id)
            ->where('user_id', $uid)
            ->exists()){
            return redirect()->route('invoice.list')->with('info', 'فاکتور مورد نظر یافت نشد');
        }


        $data = $this->InvoiceDetails($id);
        $details = $data->details;
        $invoices = $data->invoices;
        $totalAmount = $data->totalAmount;
        $totalProductAmount = $data->totalProductAmount;
        $totalDiscount = $data->totalDiscount;



        return view('clients.invoices.view', compact(
            'details',
            'invoices',
            'totalAmount',
            'totalProductAmount',
            'totalDiscount'
        ));
    }

    //vahabonline.ir
    //62.220.112.46



    public function PaymentStart($id){
        $uid = Session::get('uid');

        if(!Order::where('id', $id)
            ->where('user_id', $uid)
            ->where('status_payment', 'UnPaid')
            ->exists()){
            return back()->with('info', 'فاکتور مورد نظر یافت نشد');
        }



        $data = $this->InvoiceDetails($id);
        $details = $data->details;
        $totalAmount = $data->totalAmount;


        $dataSend = array(
            "merchant_id" => settings('ZarinpalToken'),
            "amount" => intval($totalAmount),
            "currency" => 'IRT',
            "callback_url" => route('invoice.callback', $details->id),
            "description" => "InvoicdID : " . $details->id,
        );


        $jsonData = json_encode($dataSend);

        try{
            $ch = curl_init('https://payment.zarinpal.com/pg/v4/payment/request.json');
            curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData)
            ));

            $result = curl_exec($ch);
            $err = curl_error($ch);
            $result = json_decode($result, true, JSON_PRETTY_PRINT);
            curl_close($ch);
            if ($err) {
                return back()->with('warning', 'خطایی در درگاه وجود دارد : ' . $err);
            }

            if(isset($result['errors'])){
                if(isset($result['errors']['message'])){
                    return back()->with('warning', $result['errors']['message']);
                }
                return back()->with('warning', 'مشکلی در پرداخت وجود دارد');
            }

            if(!isset($result['data']['authority'])){
                return back();
            }

            return redirect('https://www.zarinpal.com/pg/StartPay/' . $result['data']['authority']);
        }catch (\Exception $exception){
            return back()->with('info', $exception->getMessage());
        }

    }


    public function CallbackPayment(Request $request, $id){
        $uid = Session::get('uid');

        if(!Order::where('id', $id)
            ->where('user_id', $uid)
            ->where('status_payment', 'UnPaid')
            ->exists()){
            return redirect()
                ->route('invoice.view', $id)
                ->with('info', 'فاکتور مورد نظر یافت نشد');
        }

        $Authority = $request->input('Authority', '');
        if(empty($Authority)){
            return redirect()
                ->route('invoice.view', $id)
                ->with('info', 'شناسه احراز هویت یافت نشد');
        }

        $data = $this->InvoiceDetails($id);
        $totalAmount = $data->totalAmount;


        $dataSend = array(
            "merchant_id" => settings('ZarinpalToken'),
            "authority" => $Authority,
            "amount" => intval($totalAmount)
        );
        $jsonData = json_encode($dataSend);


        try{
            $ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
            curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData)
            ));
            $result = curl_exec($ch);
            $err = curl_error($ch);
            curl_close($ch);
            $result = json_decode($result, true);

            if ($err) {
                return redirect()
                    ->route('invoice.view', $id)
                    ->with('warning', 'خطایی در درگاه وجود دارد : ' . $err);
            }

            if(!isset($result['data']['code'])){
                return redirect()
                    ->route('invoice.view', $id)
                    ->with('warning', 'خطایی وجود دارد . با ما تماس بگیرید');
            }

            if($result['data']['code'] == 100){
                Order::where('user_id', $uid)
                    ->where(function ($query) use ($id) {
                        $query->where('id', $id)
                            ->orWhere('parent_id', $id);
                    })
                    ->update([
                        'status_payment' => 'Paid',
                        'payment_date' => Carbon::now(),
                        'payment_result' => json_encode($result),
                        'updated_at' => Carbon::now(),
                    ]);
            }

            return redirect()
                ->route('invoice.view', $id)
                ->with('warning', 'خطایی وجود دارد . با ما تماس بگیرید');
        }
        catch (\Exception $exception){
            return redirect()->with('info', $exception->getMessage());
        }

    }



    private function InvoiceDetails($invoice_id){
        $uid = Session::get('uid');
        $data = Order::where('user_id', $uid)
            ->where(function ($query) use ($invoice_id) {
                $query->where('id', $invoice_id)
                    ->orWhere('parent_id', $invoice_id);
            })
            ->with('products')
            ->get();

        $totalAmount = Order::where('user_id', $uid)
            ->where(function ($query) use ($invoice_id) {
                $query->where('id', $invoice_id)
                    ->orWhere('parent_id', $invoice_id);
            })
            ->sum('total_price');

        $totalProductAmount = Order::where('user_id', $uid)
            ->where(function ($query) use ($invoice_id) {
                $query->where('id', $invoice_id)
                    ->orWhere('parent_id', $invoice_id);
            })
            ->sum('product_amount');

        return json_decode(json_encode([
            'details' => Order::where('user_id', $uid)->where('id', $invoice_id)->first(),
            'invoices' => $data,
            'totalAmount' => $totalAmount,
            'totalProductAmount' => $totalProductAmount,
            'totalDiscount' => $totalProductAmount-$totalAmount
        ]));
    }
}
