<?php
namespace apexl\Io\modules\paymentDisplay\components;

use apexl\Config\Singleton;
use apexl\encryption\Encrypt;
use apexl\Io\includes\Hook;
use apexl\Io\includes\Routes;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\BasicTable;
use apexl\Io\modules\display\components\CardEntityFilteredDisplayTable;
use apexl\Io\modules\display\components\Chart;
use apexl\Io\modules\display\components\ColWrapper;
use apexl\Io\modules\display\components\ContentTitle;
use apexl\Io\modules\display\components\DisplayTable;
use apexl\Io\modules\display\components\genericComponents;
use apexl\Io\modules\display\components\SimpleButton;
use apexl\Io\modules\display\components\TableButton;
use apexl\Io\modules\invoice\services\invoiceService;
use apexl\Io\modules\payment\entities\paymentTokenEntity;
use apexl\Io\modules\payment\entities\userCreditEntity;
use apexl\Io\modules\payment\providers\stripeProvider;
use apexl\Io\modules\payment\services\paymentService;
use apexl\Io\modules\user\services\currentUser;
use apexl\Vault\Vault;
use app\module\simcard\entities\simOrderItemEntity;

class viewTiles {

    public static function latestPayments()
    {
        $components = [];

    }

    public static function latestPaymentsTile($userEntity=null, $data=[], $cssClass="col-12")
    {
        $helpComponents = [
            (new ContentTitle())->addClass('text-black text-start help-modal-content-title')->addTitle('A list of recent payments, and their status'),
            (new DisplayTable())->addClass('text-black text-start help-modal-display-table')->addRows([
                ['Date', 'Date of payment attempt'],
                ['Name', 'Customer Name'],
                ['Product', 'Product name(s)'],
                ['Type', 'Payment type - Subscription or Purchase'],
                ['Amount', 'Total payment amount, including VAT'],
                ['Status', 'Payment status (successful, failed, 3D Secure Required)'],
                ['*', "Note - Gocardless Payments aren't known as they are not triggered by the dashboard" ],
            ])
        ];

        if (!$data) $data = [];
        if ($userEntity) $data['userId'] = $userEntity->id;

        $title = Hook::processHook('latest_payments_table_title');
        if (!$title) $title = 'Latest Payments';

        $wrapper = (new ColWrapper())
            ->addClass($cssClass . ' mb-4')
            ->addComponent((new CardEntityFilteredDisplayTable())
                ->addTitle($title)
                ->src(Routes::getRoutePattern('payment-latest.data.basic', $data))
                ->displayPagination(false, false, true)
                ->displayShortTotals(false)
                ->addProperty('refreshButton', '<i class="fa-light fa-arrows-rotate"></i>')
                ->addHeaderModal($title . ' Table', $helpComponents)
                ->hideIdColumn()
            );

        $currentUser = currentUser::getCurrentUser();
        if ($currentUser->isAllowed('administer')) {
            $wrapper->addComponent(
                (new ContentTitle())
                ->addContent('<em>*Note: GoCardless Payments are not shown as they are managed by an external provider</em>')
            );
        }

        return $wrapper;
    }

    public static function paymentCardsAdminPanel($userEntity=null, $cssClass="col-12")
    {
        return (new ColWrapper())
            ->addClass($cssClass)
            ->addComponent((new CardEntityFilteredDisplayTable((new paymentTokenEntity()), [], false, 'dropmenu'))
                ->addTitle('Payment Cards')
                ->src(Routes::getRoutePattern('paymentToken.data.basic', ['userId' => $userEntity->id]))
                ->displayPagination(FALSE)
                ->displayShortTotals(FALSE)
                ->addClass('col-12 col-lg-12 col-xl-12')
                ->hideIdColumn()
                ->addProperty('refreshButton', '<i class="fa-light fa-arrows-rotate"></i>')
            );
    }

    public static function paymentCards()
    {
        $components = [];
        $config = Singleton::getInstance();
        $currentuser = currentUser::getCurrentUser();
        $stripe = new stripeProvider();
        $paymentToken = new paymentTokenEntity();
        $encrypt = new Encrypt();
        $tokens = $paymentToken->getByUser($currentuser->id);
        $paymentService = new paymentService();
        $invoiceService = new invoiceService();

        $data = [];
        foreach ($tokens as $token) {
            if ($token->setup_complete == 1 && $token->deleted == 0) {

                $paymentMethodRefDecrypted = $encrypt->decrypt($token->payment_method_ref, $token->payment_method_ref_iv, $config->app->encryption->key);
                if ($paymentMethod = $stripe->getPaymentMethod($paymentMethodRefDecrypted)) {
                    $data['rows'][] = [
                        'id' => $token->id,
                        'type' => $paymentMethod->card->brand,
                        'name' => $token->ref,
                        'description' => ucfirst($paymentMethod->card->funding) . ' card ending in **** '.$paymentMethod->card->last4 . '<br>expires: '.$paymentMethod->card->exp_month.'/'.$paymentMethod->card->exp_year,
                        'default' => $token->default_token ? '<strong>default</strong>' : '',
                    ];
                }
            }
        }

        $title = new ContentTitle();
        $title->addTitle('Payment Cards');
        if ($invoiceService->getTotalCredit($currentuser->id) > 0) {
        $title->addContent("Available credit: <strong>£{$invoiceService->getTotalCredit($currentuser->id)}</strong>");
        }


        $table = (new BasicTable($data))
            ->addComponent((new TableButton())
                ->addRoute(Routes::getRoutePattern('paymentTokenEntity.display.put', [], FALSE))
                ->addText("edit")
            )->addComponent((new TableButton())
                ->addRoute(Routes::getRoutePattern('paymentTokenEntity.display.delete', [], FALSE))
                ->addText("delete")
            );

        $button = new BasicLink();
        $button->addRoute($paymentService->getCardSetupLink($currentuser));
        $button->addText('Add New Card');
        $button->addClass('add-new-card-button btn btn-primary text-center');

        return genericComponents::dashboardBlockWrapper([$title, $table, $button])->addClass('col-4 col-lg-4 col-xl-4');
    }

    public static function salesBreakdownChart($startTime, $endTime)
    {

        $simOrderItemEntity = new simOrderItemEntity();
        $salesBreakdown = $simOrderItemEntity->getSalesBreakdown($startTime, $endTime);

        return (new ColWrapper())
            ->addComponent(
                (new Chart())
                    ->setChartType('PieChart')
                    ->addDataset($salesBreakdown->quantity)
                    ->setChartLabels($salesBreakdown->labels)
            );
    }

}