<?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;
use Illuminate\Support\Facades\Storage;
use Exception;
use Ramsey\Uuid\Uuid;

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;
        $ordersSummary = $this->getOrdersQuickSummary($clonedOrdersQuery);

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

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

    private function getOrdersQuickSummary($storeOrderQuery){
        $qryClone = clone $storeOrderQuery;

        $records = $storeOrderQuery->get();
        $ordersTotalAmount = 0;
        foreach($records as $record){
            $ordersTotalAmount = $ordersTotalAmount + $record->total();
        }

        $ids = $qryClone->pluck('id')->toArray();
        $trxs = FinancialTransaction::whereIn('order_id', $ids)->where('charge_or_refund', 'CHARGE')->get();
        $totalAmountCharged = 0;
        foreach($trxs as $trx){
            $totalAmountCharged = $totalAmountCharged + floatval($trx->amount);
        }

        $summary = [
            'orders_total_amount' => $ordersTotalAmount,
            'total_amount_charged' => $totalAmountCharged,
        ];
        return $summary;
    }

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

    public function orderPreviewInvoice(StoreOrder $order)
    {
        return view('app.my-account.admin.orders.sub.preview-invoice', 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::whereHas('storeOrdersAsClient', function($qry){
                    return $qry->whereRaw('(store_order.id NOT IN (SELECT financial_transaction.order_id FROM financial_transaction))');
                })->orderBy('created_at', 'DESC')->paginate(30);
                break;
            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')
        ];

        $storeOrderUid = $request->get('orderUid');
        $storeOrder = StoreOrder::where('uid', $storeOrderUid)->first();

        $response = $this->callJava('/api/financialTransaction/createCharge', $data, $this->sessionKey);
        if (!@$response['success']) {
            if($storeOrder){
               $this->emailService->notifyUserOnFailedTransaction($storeOrder->user, $storeOrder);
            }

            return $this->fail($response['message'] ?? 'Failed!');
        }

        $message = $response['message'];
        if ($message == 'ORDER_NOT_CHARGED') {
            $message = 'Your order has been submitted but not charged.';
            $this->emailService->notifyUserOnFailedTransaction($storeOrder->user, $storeOrder);
            return $this->fail($message);
        }
        
        if($storeOrder){
            $user = $storeOrder->user;
            $this->emailService->sendUserOrderChargeSuccessful($user, $storeOrder);
        }

        return $this->pass();
    }

    public function userEmails(Request $request, User $user){
        $detailJson = $user->detailJson();
        $emailsSent = @$detailJson->emails_sent ?? [];
        return view('app.my-account.admin.users.sub.emails', compact('user', 'emailsSent'));
    }

    public function userSmses(Request $request, User $user){
        $detailJson = $user->detailJson();
        $smsesSent = @$detailJson->smses_sent ?? [];
        return view('app.my-account.admin.users.sub.smses', compact('user', 'smsesSent'));
    }

    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);
    }

    public function orderCreate(Request $request){
        $userUid = $request->get('userUid');
        $allTests = config('constants.tests');
        $selectedTests = $request->get('tests', []);
        if(!count($selectedTests)){
            return $this->fail('Please select a test!');
        }
        $tests = [];
        foreach($allTests as $key=>$title){
            $tests[$key] = in_array($key, $selectedTests) ? 1 : 0;
        }
        $data = [
            'tests' => $tests,
            'tests_total' => $request->get('total'),
            'tests_lab_id' => $request->get('tests_lab_id')
        ];

        $detailJson = [
            'selected_options' => json_encode($data)
        ];

        $javaResponse = $this->callJava('/api/customerStore/submitOrderAsAdmin', ['userUid' => $userUid, 'detailJson' => json_encode($detailJson)], $this->sessionKey);
        if (!@$javaResponse['success']) {
            return $this->fail($javaResponse['message']);
        }
        return $this->pass();
    }

    public function createNewUser(Request $request){
        $email = $request->get('email');
        $existingUser = User::where('email', $email)->first();
        if ($existingUser) {
        return $this->fail('This email account is in use!');
        }
        $nameFirst = $request->get('fname');
        $nameLast = $request->get('lname');
        $name = $nameFirst . ' ' . $nameLast;
        //call java
        $temporaryPassword = generate_password(10);

        $userCreateAccountResponse = $this->callJava('/api/auth/signUpWithEmail', [
        'fullName' => $name,
        'nameFirst' => $nameFirst,
        'nameLast' => $nameLast,
        'email' => $request->get('email'),
        'phoneNumber' => $request->get('phoneNumber'),
        'password' => $temporaryPassword,
        'passwordConfirmation' => $temporaryPassword,
        ], null);

        if (!@$userCreateAccountResponse['success']) {
            return $this->fail($userCreateAccountResponse['message']);
        }

        $newUser = User::where('uid', $userCreateAccountResponse['data'])->first();

        //Send email via java
        if ($newUser) {
          $this->emailService->sendUserWelcomeEmail($newUser, $temporaryPassword);
        }
        $this->storeUserDetailJson($request, $newUser);

        return $this->pass($userCreateAccountResponse['data']);
    }

    public function createNewEmail(Request $request){
        $userUid = $request->get('userUid');
        $user = User::where('uid', $userUid)->first();
        if (!$user) {
        return $this->fail('Invalid user!');
        }
        $content = $request->get('content');
        $subject = $request->get('subject');

        $detailJson = $user->detailJson();
        $detailJson->emails_sent = @$detailJson->emails_sent ?? [];

        $emailData = [
            'created_at' => date('Y-m-d h:m:s'),
            'to' => $user->getEmail(),
            'subject' => $subject,
            'content' => $content
        ];

        array_unshift($detailJson->emails_sent, $emailData);

        $this->emailService->sendUserCustomEmail($user, $emailData);

        $user->detail_json = json_encode($detailJson);
        $user->save();

        return $this->pass($user->uid);
    }

    public function createNewSms(Request $request){
        $userUid = $request->get('userUid');
        $user = User::where('uid', $userUid)->first();
        if (!$user) {
        return $this->fail('Invalid user!');
        }
        $content = $request->get('content');
        $fromNumber = $request->get('fromNumber');
        $toNumber = $request->get('toNumber');

        $response = $this->sendSmsToUser($user, [
            'fromNumber' => $fromNumber,
            'toNumber' => $toNumber,
            'content' => $content
        ]);

        return $this->pass($user->uid);
    }

    protected function sendSmsToUser($user, $params){
        $detailJson = $user->detailJson();
        $detailJson->smses_sent = @$detailJson->smses_sent ?? [];

        $smsData = [
            'created_at' => date('Y-m-d h:m:s'),
            'from' => $params['fromNumber'],
            'to' => $params['toNumber'],
            'content' => $params['content']
        ];

        array_unshift($detailJson->smses_sent, $smsData);

        $data = [
            'fromNumber' => $params['fromNumber'],
            'toNumber' => $params['toNumber'],
            'message' => $params['content'],
            'secret' => 'Superman2022@'
        ];
        $response = $this->callJava('/api/sms/send', $data, $this->sessionKey);
        if (!@$response['success']) {
            return $this->fail($response['message'] ?? 'Failed!');
        }

        $user->detail_json = json_encode($detailJson);
        $user->save();
        return;
    }

    public function storeUserDetailJson(Request $request, User $user)
    {
        $data = [
        'uid' => $user->uid,
        'phone_number' => $request->get('phoneNumber'),
        'notification_option' => $request->get('notificationOption'),
        'request_change_password' => 1,
        ];

        $res = $this->callJava('/api/user/upsertDetailJson', $data, $this->sessionKey);
    }

  public function uploadFile(Request $request, StoreOrder $order){
    $fileRef = $request->get('file_name', 'file');
    $accessToken = (string) Uuid::uuid6();
    $storageResponse = $this->storeFileAs($request, $fileRef, StoreOrder::FILE_PATH, $accessToken);
       
    $detailJson = json_decode($order->detail_json ?? '{}', true);
    $detailJson[$fileRef] = $storageResponse;
    $order->detail_json = json_encode($detailJson);
    $order->save();

    return $this->pass();    
  }

  public function emailReport(Request $request, StoreOrder $order){
    $results_attachment = $order->getDetailJsonValue('results_attachment');
    $params = [
        'to' => [
            ['email' => $order->user->getEmail(), 'name' => $order->user->displayName()]
        ],
        'template' => 'results-report',
        'subject' => 'Test Results for Order #' . $order->iid,
        'template_params' => [
            'user' => $order->user,
            'order' => $order,
            'message_body' => $request->get('message')
        ],
        'file' => $results_attachment['path']
    ];

    try{
        $this->sendEmailNotification($params);
        return $this->pass();
    }catch(Exception $e){
        return $this->fail($e->getMessage());
    }
  }

  public function smsReport(Request $request, StoreOrder $order){
    $results_attachment = $order->getDetailJsonValue('results_attachment');
    $user = $order->user;
    
    $response = $this->sendSmsToUser($user, [
        'fromNumber' => $request->get('fromNumber'),
        'toNumber' => $request->get('toNumber'),
        'content' => $request->get('message')
    ]);

    return $this->pass();
  }
}
