<?php

namespace App\Http\Controllers;

use App\Models\PaymentMethod;
use App\Models\FinancialTransaction;
use App\Models\PromoCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use App\Models\User;
use App\Models\StoreOrder;
use App\Http\Services\EmailService;
use App\Models\AppSession;
use App\Models\AppUserTransaction;
use App\Models\Message;
use App\Models\UserEvent;
use Barryvdh\DomPDF\Facade\Pdf;
use OpenTok\MediaMode;
use OpenTok\OpenTok;

class AdminController extends Controller
{
    protected $emailService;
    public function __construct(EmailService $emailService)
    {
        parent::__construct();
        $this->emailService = $emailService;
    }

    public function dashboard(Request $request)
    {
        $ordersTotal = $this->getOrdersTotal();
        return view('app.my-account.admin.dashboard', compact('ordersTotal'));
    }

    public function getOrdersTotal(){
        $orders = StoreOrder::all();
        $total = 0;
        foreach($orders as $order){
            $total = $total + $order->total();
        }
        return $total;
    }

    public function users(Request $request)
    {
        $filters = $request->all();
        $users = User::query();

        $query = $request->get('query', null);

        $payment_profile = $request->get('payment_profile');
        if($payment_profile){
            if($payment_profile == 'YES'){
                $users = $users->whereHas('paymentMethods');
            }else{
                $users = $users->whereDoesntHave('paymentMethods');
            }
        }

        $customer_name = $request->get('customer_name');
        if($customer_name){
            $wildCardedCustomer = '%' . $customer_name . '%';
            $users = $users->where(function($qry)use($wildCardedCustomer){
                $qry->where('name_first', 'ilike', $wildCardedCustomer)
                ->orWhere('name_last', 'ilike', $wildCardedCustomer)
                ->orWhere('full_name', 'ilike', $wildCardedCustomer);
            });
        }

        $users = $users->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.index', compact('users', 'filters'));
    }

    public function userDashboard(User $user)
    {
        return view('app.my-account.admin.users.sub.dashboard', compact('user'));
    }

    public function userOrders(User $user)
    {
        $orders = StoreOrder::where('user_id', $user->id)->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.sub.orders', compact('user', 'orders'));
    }
    public function userTransactions(User $user)
    {
        $transactions = FinancialTransaction::where('user_id', $user->id)->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.sub.transactions', compact('transactions', 'user'));
    }

    public function userSessions(User $user)
    {
        $sessions = AppSession::where('user_id', $user->id)->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.sub.sessions', compact('sessions', 'user'));
    }
    public function userUserEvents(User $user)
    {
        $userEvents = UserEvent::where('performer_user_id', $user->id)->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.sub.user-events', compact('userEvents', 'user'));
    }


    public function userPaymentMethods(User $user){
        $userPaymentMethods = PaymentMethod::where('user_id', $user->id)->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.users.sub.payment-methods', compact('user', 'userPaymentMethods'));
    }


    public function paymentMethods(Request $request)
    {
      $filters = $request->all();
      $paymentMethods = PaymentMethod::query();
      $expirationDate = $request->get('expiration_date');
      if($expirationDate){
        $month = date("m",strtotime($expirationDate));
        $year = date("Y",strtotime($expirationDate));
        $paymentMethods = $paymentMethods->whereRaw("((stripe_detail_json)::json->'card'->>'exp_month')::integer <= $month AND ((stripe_detail_json)::json->'card'->>'exp_year')::integer <= $year");
      }
      $paymentMethods = $paymentMethods->orderBy('created_at', 'DESC')->paginate(30);

      return view('app.my-account.admin.payment-methods.index', compact('paymentMethods', 'filters'));
    }

    public function paymentMethodDashboard(PaymentMethod $paymentMethod)
    {
        return view('app.my-account.admin.payment-methods.sub.dashboard', compact('paymentMethod'));
    }

    public function financialTransactions(Request $request)
    {
        $filters = $request->all();
        $transactions = FinancialTransaction::query();

        $this->filterDateMultiQuery($request, $transactions, 'created_at', 'created_at_date_category', 'created_at_date_value_1', 'created_at_date_value_2');

        $customer = $request->get('customer');
        if($customer){
            $wildCardedCustomer = '%' . $customer . '%';
            $transactions = $transactions->whereHas('user', function($query) use($wildCardedCustomer){
                $query->where('name_first', 'ilike', $wildCardedCustomer)
                ->orWhere('name_last', 'ilike', $wildCardedCustomer)
                ->orWhere('full_name', 'ilike', $wildCardedCustomer);
            });
        }


        $transactions = $transactions->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.financial-transactions.index', compact('transactions', 'filters'));
    }

    public function financialTransactionDashboard()
    {
        return view('app.my-account.admin.financial-transactions.sub.dashboard');
    }

    public function orders(Request $request)
    {
        $filters = $request->all();
        $orders = StoreOrder::query();

        $name = $request->get('name', null);
        if ($name) {
            $wildCardedName = '%' . $name . '%';
            $orders = $orders->whereHas('User', function($query) use($wildCardedName){
                return $query->where('name_first', 'ilike', $wildCardedName)
                ->orWhere('name_last', 'ilike', $wildCardedName)
                ->orWhere('full_name', 'ilike', $wildCardedName);
            });
          }

        $orderNumber = $request->get('order_number');
        if($orderNumber){
            $wildCardedOrderNumber = '%' . $orderNumber . '%';
            $orders = $orders->where('iid', 'ilike', $wildCardedOrderNumber);
        }
        $this->filterDateMultiQuery($request, $orders, 'created_at', 'created_at_date_category', 'created_at_date_value_1', 'created_at_date_value_2');


        $orders = $orders->orderBy('created_at', 'DESC');

        $clonedOrdersQuery = clone $orders;

        $orders = $orders->paginate(30);

        return view('app.my-account.admin.orders.index', compact('orders', 'filters'));
    }

    public function orderDashboard(StoreOrder $order)
    {
        return view('app.my-account.admin.orders.sub.dashboard', compact('order'));
    }

    public function orderFinancialTransactions(StoreOrder $order)
    {
        $transactions = FinancialTransaction::where('order_id', $order->id)->orderBy('created_at', 'DESC')->get();
        return view('app.my-account.admin.orders.sub.financial-transactions', compact('order', 'transactions'));
    }

    public function report(Request $request, $report) {
        $rows = [];
        switch ($report) {
            case 'new-orders-pending-processing':
                $rows = User::whereNotNull('upcoming_fill_date')
                    ->whereRaw("(id NOT IN (SELECT store_order.user_id FROM store_order))")
                    ->paginate(30);
                break;
            case 'refills-pending-processing':
                $rows = User::whereRaw("fill2date <= NOW()::date")
                    ->whereRaw("(id IN (SELECT store_order.user_id FROM store_order))")
                    ->paginate(30);
            default:
                break;
        }
        return view('app.my-account.reports.' . $report, compact('rows'));
    }


    public function sessions(Request $request){
        $filters = $request->all();
        $sessions = AppSession::query();
        if($request->get('name')){
            $wildCardedName = '%' . $request->get('name') . '%';
            $sessions = $sessions->whereHas('user', function($qry) use($wildCardedName){
                return $qry->where('name_first', 'ilike', $wildCardedName)
                ->orWhere('name_last', 'ilike', $wildCardedName)
                ->orWhere('full_name', 'ilike', $wildCardedName);
            });
        }
        $this->filterDateMultiQuery($request, $sessions, 'created_at', 'created_at_date_category', 'created_at_date_value_1', 'created_at_date_value_2');
        $sessions = $sessions->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.sessions.index', compact('sessions', 'filters'));
    }

    public function userEvents(Request $request){
        $filters = $request->all();
        $userEvents = UserEvent::query();
        if($request->get('name')){
            $wildCardedName = '%' . $request->get('name') . '%';
            $userEvents = $userEvents->whereHas('user', function($qry) use($wildCardedName){
                return $qry->where('name_first', 'ilike', $wildCardedName)
                ->orWhere('name_last', 'ilike', $wildCardedName)
                ->orWhere('full_name', 'ilike', $wildCardedName);
            });
        }
        $this->filterDateMultiQuery($request, $userEvents, 'created_at', 'created_at_date_category', 'created_at_date_value_1', 'created_at_date_value_2');
        $userEvents = $userEvents->orderBy('created_at', 'DESC')->paginate(30);
        return view('app.my-account.admin.user-events.index', compact('userEvents', 'filters'));
    }

    public function orderCharge(Request $request){
        $data = [
            'orderUid' => $request->get('orderUid'),
            'paymentMethodUid' => $request->get('paymentMethodUid'),
            'amount' => $request->get('amount')
        ];

        $response = $this->callJava('/api/financialTransaction/createCharge', $data, $this->sessionKey);
        if (!@$response['success']) {
            $storeOrder = StoreOrder::where('uid', $request->get('orderUid'))->first();
            if($storeOrder){
               $this->emailService->notifyUserOnFailedTransaction($storeOrder->user);
            }

            return $this->fail($response['message']);
        }
        return $this->pass();
    }

    public function userMessages(Request $request, User $user){
        $messages = Message::where('to_user_id', $user->id)->orWhere('from_user_id', $user->id);
        $messages = $messages->orderBy('created_at', 'ASC')->paginate(25);

        $opentok = null;
        $otSession = null;
        $otSessionId = null;
        $otToken = null;

        try {
            $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
            $otSession = $opentok->createSession(array('mediaMode' => MediaMode::ROUTED));
            $otSessionId = $otSession->getSessionId();
            $otToken = $opentok->generateToken($otSessionId);
          } catch (\Exception $e) {
            return redirect()->back()->with('error', 'OpenTok issue!');
          }

          $toUser = $user;
        return view('app.my-account.admin.users.sub.messages', compact('otSessionId', 'otToken', 'messages', 'toUser', 'user'));
    }
    public function userMessageAttachments(Request $request, User $user, Message $message){
        if(!$message) return '';
        $output = [];
        foreach ($message->attachments as $attachment) {
            $output[] = '<a native target="_blank" ' .
                'href="/api/systemFile/view/' . $attachment->systemFile->uid . '" ' .
                'class="attachment text-sm my-1">' .
                '<i class="fa fa-paperclip"></i>&nbsp;' .
                $attachment->systemFile->file_name .
                '</a>';
        }
        return implode("", $output);
    }
}
