<?php

namespace Modules\Travel\Repositories;

use Carbon\Carbon;
use Modules\Travel\Entities\TravelPlan;


class TravelPlanRepository
{
    function fields()
    {
        return [
            _trans('common.ID'),
            _trans('common.Employee'),
            _trans('common.From Date'),
            _trans('common.To Date'),
            _trans('common.From Location'),
            _trans('common.To Location'),
            _trans('common.Status'),
            _trans('common.Action')
        ];
    }

    function table($request)
    {
        $data = TravelPlan::query()
            ->with(['employee', 'signature', 'status', 'approvedBy', 'rejectedBy', 'createdBy', 'updatedBy'])
            ->where('company_id', auth()->user()->company_id)
            ->when(request('search'), function ($q) {
                $search = request('search');
                $q->where(function ($q) use ($search) {
                    $q->whereHas('employee', function ($q) use ($search) {
                        $q->where('name', 'like', '%' . $search . '%');
                    })
                    ->orWhere('from_location', 'like', '%' . $search . '%')
                    ->orWhere('to_location', 'like', '%' . $search . '%');
                });
            })
            ->when(filled(request('from')) && filled(request('to')), function ($q) {
                $q->where('from_date', '>=', request('from'))
                    ->where('to_date', '<=', request('to'));
            })
            ->when(!isAdminOrHr(), fn ($q) => $q->whereIn("employee_id", getRelatedUserIds()))
            ->latest('id')
            ->paginate($request->limit ?? 2);


            return [
                'data' => $data->map(function ($data) {
                    $action_button = '';

                    if (hasPermission('travel_plan_read')) {
                        $action_button .= '<a href="' . route('travel.plans.show', $data->id) . '" class="dropdown-item"> ' . _trans('common.View') . ' </a>';
                    }
                    
                    if ($data->status_id == 2 && hasPermission('travel_plan_update')) {
                        $action_button .= '<a href="' . route('travel.plans.edit', $data->id) . '" class="dropdown-item"> ' . _trans('common.Edit') . ' </a>';
                    }

                    if ($data->status_id == 5) {
                        if (hasPermission('travel_meeting_read')) {
                            $action_button .= '<a href="' . route('travel.plans.meetings.index', $data->id) . '" class="dropdown-item"> ' . _trans('common.Meeting') . ' </a>';
                        }

                        if (hasPermission('travel_expense_read')) {
                            $action_button .= '<a href="' . route('travel.plans.expenses.index', $data->id) . '" class="dropdown-item"> ' . _trans('common.Expense') . ' </a>';
                        }
                    }
                    
                    if ($data->status_id == 2 && hasPermission('travel_plan_read')) {
                        if (hasPermission('travel_plan_approve')) {
                            $action_button .= '<a href="' . route('travel.plans.show', ['id' => $data->id, 'type' => 'approve']) . '" class="dropdown-item"> ' . _trans('common.Approve') . ' </a>';
                        }

                        if (hasPermission('travel_plan_reject')) {
                            $action_button .= '<a href="' . route('travel.plans.show', ['id' => $data->id, 'type' => 'reject']) . '" class="dropdown-item"> ' . _trans('common.Reject') . ' </a>';
                        }
                    }

                    if (hasPermission('travel_plan_delete')) {
                        $action_button .= actionButton(_trans('common.Delete'), '__globalDelete(' . $data->id . ',`travel/plans/delete/`)', 'delete');
                    }

                    $button = ' <div class="dropdown dropdown-action">
                                    <button type="button" class="btn-dropdown" data-bs-toggle="dropdown"
                                        aria-expanded="false">
                                        <i class="fa-solid fa-ellipsis"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                    ' . $action_button . '
                                    </ul>
                                </div>';

                    return [
                        'id' => $data->id,
                        'employee' => $data->employee->name,
                        'from_date' => $data->from_date,
                        'to_date' => $data->to_date,
                        'from_location' => $data->from_location ?? 'N/A',
                        'to_location' => $data->to_location ?? 'N/A',
                        'status' => '<small class="badge badge-' . @$data->status->class . '">' . @$data->status->name . '</small>',
                        'action'   => $button
                    ];
                }),
                'pagination' => [
                    'total' => $data->total(),
                    'count' => $data->count(),
                    'per_page' => $data->perPage(),
                    'current_page' => $data->currentPage(),
                    'total_pages' => $data->lastPage(),
                    'pagination_html' =>  $data->links('backend.pagination.custom')->toHtml(),
                ],
            ];
    }

    public function storeTravelPlan($request)
    {
        $travelPlan                 = new TravelPlan();
        $travelPlan->employee_id    = auth()->id();
        $travelPlan->from_date      = Carbon::parse($request->from_date)->format('Y-m-d');
        $travelPlan->to_date        = Carbon::parse($request->to_date)->format('Y-m-d');
        $travelPlan->from_location  = $request->from_location;
        $travelPlan->to_location    = $request->to_location;
        $travelPlan->purpose        = $request->purpose;
        $travelPlan->amount         = $request->amount;
        $travelPlan->signature      = $request->signature;
        $travelPlan->signature_date = Carbon::parse($request->signature_date)->format('Y-m-d');
        $travelPlan->status_id      = 2;
        $travelPlan->company_id     = auth()->user()->company_id;
        $travelPlan->branch_id      = getCurrentBranch();
        $travelPlan->created_by     = auth()->id();

        $travelPlan->save();

        return $travelPlan;
    }

    public function updateTravelPlan($request, $id)
    {
        $travelPlan                 = TravelPlan::find($id);
        $travelPlan->from_date      = Carbon::parse($request->from_date)->format('Y-m-d');
        $travelPlan->to_date        = Carbon::parse($request->to_date)->format('Y-m-d');
        $travelPlan->from_location  = $request->from_location;
        $travelPlan->to_location    = $request->to_location;
        $travelPlan->purpose        = $request->purpose;
        $travelPlan->amount         = $request->amount;
        $travelPlan->signature      = $request->signature;
        $travelPlan->signature_date = Carbon::parse($request->signature_date)->format('Y-m-d');
        $travelPlan->updated_by     = auth()->id();

        $travelPlan->save();

        return $travelPlan;
    }

    public function approveOrReject($request, $id)
    {
        TravelPlan::where('id', $id)->update([
            'approved_remark' => $request->is_approved && $request->remark ? $request->remark : '',
            'approved_by'     => $request->is_approved ? auth()->id() : null,
            'approved_at'     => $request->is_approved ? now() : null,
            'rejected_remark' => $request->is_rejected && $request->remark ? $request->remark : '',
            'rejected_by'     => $request->is_rejected ? auth()->id() : null,
            'rejected_at'     => $request->is_rejected ? now() : null,
            'status_id'       => $request->is_approved ? 5 : 6
        ]);
    }

    public function delete($id)
    {
        $travelPlan = TravelPlan::with('travelMeetings')->find($id);

        foreach($travelPlan->travelMeetings ?? [] as $travelMeeting) {
            (new TravelMeetingRepository)->delete($travelMeeting->id);
        }

        $travelPlan->delete();
    }
}
