<?php

namespace App\DataTables\Admin;

use App\Models\Subscription;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;
use Yajra\DataTables\EloquentDataTable;

class SubscriptionDataTable extends DataTable
{
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addIndexColumn()
            ->addColumn('plan_name', function ($subscription) {
                return view('admin.subscription.column.plan_name', compact('subscription'));
            })->addColumn('date_time', function ($subscription) {
                return view('admin.subscription.column.date', compact('subscription'));
            })->addColumn('next_billing', function ($subscription) {
                return view('admin.subscription.column.next_billing', ['remainingPeriod' => $this->nextBilling($subscription), 'subscription' => $subscription]);
            })->addColumn('status', function ($subscription) {
                return view('admin.subscription.column.status', compact('subscription'));
            })->addColumn('action', function ($subscription) {
                return view('admin.subscription.column.action', compact('subscription'));
            })
            ->addColumn('file', function ($subscription) {
                return view('admin.subscription.column.file', compact('subscription'));
            })
            ->addColumn('payment_method', function ($subscription) {
                return ucwords($subscription->payment_method);
            })->setRowId('id');
    }

    public function query(): QueryBuilder
    {
        return Subscription::when($this->request->search['value'] ?? false, function ($query) {
            $search = $this->request->search['value'];
            $query->where('trx_id', 'like', "%$search%");
        })
            ->latest()
            ->newQuery();
    }

    public function html(): HtmlBuilder
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(1)
            ->selectStyleSingle()
            ->setTableAttribute('style', 'width:99.8%')
            ->footerCallback('function ( row, data, start, end, display ) {

                $(".dataTables_length select").addClass("form-select form-select-lg without_search mb-3");
                selectionFields();
            }')
            ->parameters([
                'dom'        => 'Blfrtip',
                'buttons'    => [
                    [],
                ],
                'lengthMenu' => [[10, 25, 50, 100, 250], [10, 25, 50, 100, 250]],
                'language'   => [
                    'searchPlaceholder' => __('search'),
                    'lengthMenu'        => '_MENU_ ' . __('subscription_per_page'),
                    'search'            => '',
                ],
            ]);
    }

    public function getColumns(): array
    {
        return [
            Column::computed('id')->data('DT_RowIndex')->title('#')->width(10),
            Column::computed('plan_name')->title(__('plan_name')),
            Column::computed('date_time')->title(__('date_time')),
            Column::computed('next_billing')->title(__('next_billing')),
            Column::computed('payment_method')->title(__('payment_method')),
            Column::computed('status')->title(__('status')),
            Column::computed('file')->title(__('file')),
            Column::computed('action')->title(__('action'))
                ->exportable(false)
                ->printable(false)
                ->searchable(false)->addClass('action-card')->width(10),
        ];
    }

    protected function filename(): string
    {
        return 'Currency_' . date('YmdHis');
    }


    public function nextBilling($subscription): string
    {
        $created_at = Carbon::parse($subscription->created_at);
        $now        = Carbon::now();

        if (@$subscription->plan->type == 'monthly') {
            $expiry_date = $created_at->copy()->addMonthsNoOverflow(1);
        } else {
            $expiry_date = $created_at->copy()->addYear();
        }

        // If expired
        if ($now->gte($expiry_date)) {
            return 'Expired';
        }

        // Calculate difference
        $diff = $now->diff($expiry_date);

        $parts = [];

        if ($diff->m > 0) {
            $parts[] = $diff->m . ' month' . ($diff->m > 1 ? 's' : '');
        }

        if ($diff->d > 0) {
            $parts[] = $diff->d . ' day' . ($diff->d > 1 ? 's' : '');
        }

        if (empty($parts)) {
            return 'Less than a day';
        }

        return implode(' ', $parts);
    }
}
