<?php

namespace App\DataTables;

use App\Enums\MemberStatusEnum;
use App\Enums\MemberTypeEnum;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Services\DataTable;

class AcademyAssignedMemberDataTable extends DataTable
{
    public $academyId = 0;

    public function dataTable($query)
    {
        return datatables()
            ->query($query)
            ->addColumn('checkbox', fn ($row) =>
                '<input type="checkbox" class="row-checkbox" value="' . e((string) ($row->row_key ?? '')) . '">'
            )
            ->addColumn('name', function ($row) {
                $isDependent = (string) ($row->record_type ?? '') === 'dependent';
                $id = (int) ($row->id ?? 0);
                $link = $isDependent
                    ? route('admin.dependents.show', $id)
                    : route('admin.members.show', $id);
                return '<a href="' . $link . '" class="fw-medium text-primary">' . e((string) ($row->name ?? '-')) . '</a>';
            })
            ->addColumn('phone', fn ($row) => e((string) ($row->phone ?? '-')))
            // Type comes directly from enrollment source tables (academy_member / academy_dependent)
            ->addColumn('assignment_type', fn ($row) => ((string) ($row->record_type ?? '') === 'dependent') ? __('dashboard.dependent') : __('dashboard.member'))
            ->addColumn('status', fn ($row) => MemberStatusEnum::badge((int) ($row->status ?? 1)))
            ->addColumn('member_type', fn ($row) =>
                (string) ($row->record_type ?? '') === 'dependent'
                    ? '-'
                    : MemberTypeEnum::label((int) ($row->member_type ?? 1))
            )
            ->addColumn('end_date_subscription', fn ($row) => $row->end_date_subscription ?: '-')
            ->addColumn('created_at', fn ($row) => UpdateDate($row->created_at))
            ->addColumn('action', fn ($row) => '-')
            ->rawColumns(['checkbox', 'name', 'status', 'action'])
            ->addIndexColumn();
    }

    public function query()
    {
        $academyId = (int) $this->academyId;

        $members = DB::table('academy_member as am')
            ->join('members as m', 'm.id', '=', 'am.member_id')
            ->select([
                'm.id as id',
                DB::raw("CONCAT('member-', m.id) as row_key"),
                'm.name as name',
                'm.phone as phone',
                'm.status as status',
                'm.member_type as member_type',
                DB::raw("DATE_FORMAT(m.end_date_subscription, '%Y-%m-%d') as end_date_subscription"),
                'am.created_at as created_at',
                DB::raw("'member' as record_type"),
            ])
            ->where('am.academy_id', $academyId);

        $dependents = DB::table('academy_dependent as ad')
            ->join('dependents as d', 'd.id', '=', 'ad.dependent_id')
            ->select([
                'd.id as id',
                DB::raw("CONCAT('dependent-', d.id) as row_key"),
                'd.name as name',
                'd.phone as phone',
                'd.status as status',
                DB::raw('NULL as member_type'),
                DB::raw("'-' as end_date_subscription"),
                'ad.created_at as created_at',
                DB::raw("'dependent' as record_type"),
            ])
            ->where('ad.academy_id', $academyId);

        return DB::query()->fromSub(
            $members->unionAll($dependents),
            'academy_assigned_people'
        );
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('academy-assigned-members-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->ajax([
                'url'  => route('admin.academies.assigned-members.datatable', ['academy' => $this->academyId]),
                'data' => dtFilters([]),
            ])
            ->orderBy(1, 'desc')
            ->language([
                'url' => asset('/dashboard_assets/js/datatable/datatables/langs/' . app()->getLocale() . '.json'),
            ])
            ->scrollX(true)
            ->dom('Blfrtip')
            ->parameters([
                'select'  => ['style' => 'multi', 'selector' => 'td:first-child'],
                'buttons' => dtButtons([]),
            ] + dtLength(10));
    }

    protected function getColumns(): array
    {
        return [
            computedCol('checkbox', '<input type="checkbox" id="check-all">', 'text-center checkbox-col', false, false, 8),
            addCol('name',        __('dashboard.name'),        true, true,  true, true),
            addCol('phone',       __('dashboard.phone'),       true, true,  true, true),
            addCol('assignment_type', __('dashboard.type'),     true, false, true, true),
            addCol('status',      __('dashboard.status'),      true, false, true, true),
            addCol('member_type', __('dashboard.member_type'), true, false, true, true),
            addCol('end_date_subscription', __('dashboard.end_date_subscription') ?? 'Expiry', true, false, true, true),
            addCol('created_at',  __('dashboard.created_at'),  true, false, true, true),
            computedCol('action', __('dashboard.actions')),
        ];
    }

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