<?php

namespace Modules\Travel\Repositories;

use Carbon\Carbon;
use App\Models\Upload;
use Illuminate\Support\Facades\DB;
use Modules\Travel\Entities\TravelMeeting;
use App\Helpers\CoreApp\Traits\FileHandler;

class TravelMeetingRepository
{
    use FileHandler;

    function fields()
    {
        return [
            _trans('common.ID'),
            _trans('common.Employee'),
            _trans('common.Date'),
            _trans('common.Company Info'),
            _trans('common.Meeting Time'),
            _trans('common.File'),
            _trans('common.Rating'),
            _trans('common.Action')
        ];
    }

    function table($request, $plan_id)
    {
        $data   = TravelMeeting::query()
                ->where('company_id', auth()->user()->company_id)
                ->where('travel_plan_id', $plan_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('customer_company_name', 'like', '%' . $search . '%')
                        ->orWhere('customer_name', 'like', '%' . $search . '%')
                        ->orWhere('customer_phone', 'like', '%' . $search . '%')
                        ->orWhere('customer_email', 'like', '%' . $search . '%');
                    });
                })
                ->when(filled(request('from')) && filled(request('to')), function ($q) {
                    $q->whereBetween('date', [request('from'), request('to')]);
                })
                ->when(!isAdminOrHr(), fn ($q) => $q->whereIn("employee_id", getRelatedUserIds()))
                ->latest('id')
                ->paginate($request->limit ?? 2);

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

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

                    if (hasPermission('travel_meeting_update')) {
                        $action_button .= '<a href="' . route('travel.plans.meetings.edit', ['id' => $data->id, 'plan_id' => $plan_id]) . '" class="dropdown-item"> ' . _trans('common.Edit') . ' </a>';   
                    }

                    if (hasPermission('travel_meeting_delete')) {
                        $action_button .= actionButton(_trans('common.Delete'), '__globalDelete(' . $data->id . ', `travel/plans/meetings/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>';


                    $companyInfo =  '<div class="d-flex flex-column gap-0">
                                        <div class="d-flex align-items-start gap-3">
                                            <span class="w-50">' . _trans("common.Company") . '</span>
                                            <span>: ' . $data->customer_company_name . '</span>
                                        </div>
                                        <div class="d-flex align-items-start gap-3">
                                            <span class="w-50">' . _trans("common.Customer Name") . '</span>
                                            <span>: ' . $data->customer_name . '</span>
                                        </div>
                                        <div class="d-flex align-items-start gap-3">
                                            <span class="w-50">' . _trans("common.Email") . '</span>
                                            <span>: ' . $data->customer_email . '</span>
                                        </div>
                                        <div class="d-flex align-items-start gap-3">
                                            <span class="w-50">' . _trans("common.Phone") . '</span>
                                            <span>: ' . $data->customer_phone . '</span>
                                        </div>
                                    </div>';

                        $totalTime = calculateTotalHoursHumanReadable($data->meeting_start_time, $data->meeting_end_time);
                        $meetingTime =  '<div class="d-flex flex-column gap-0">
                                            <div class="d-flex align-items-start gap-3">
                                                <span class="w-50">' . _trans("common.Schedule Time") . '</span>
                                                <span>: ' . date('h:i A', strtotime($data->meeting_schedule_time)) . '</span>
                                            </div>
                                            <div class="d-flex align-items-start gap-3">
                                                <span class="w-50">' . _trans("common.Start Time") . '</span>
                                                <span>: ' . date('h:i A', strtotime($data->meeting_start_time)) . '</span>
                                            </div>
                                            <div class="d-flex align-items-start gap-3">
                                                <span class="w-50">' . _trans("common.End Time") . '</span>
                                                <span>: ' . date('h:i A', strtotime($data->meeting_end_time)) . '</span>
                                            </div>
                                            <div class="d-flex align-items-start gap-3">
                                                <span class="w-50">' . _trans("common.Total Time") . '</span>
                                                <span>: ' . $totalTime . '</span>
                                            </div>
                                        </div>';

                    if ($data->file_id) {
                        $file = '<a href="' . uploaded_asset($data->file_id) . '" download class="btn btn-primary btn-sm">
                                    <i class="fas fa-download"></i>
                                </a>';
                    } else {
                        $file = _trans('common.N/A');
                    }
                                   
                    $rating = '';
                    for ($i = 1; $i <= 5; $i++) {
                        $fillColor = $i <= $data->rating_of_meeting_experience ? 'text-warning' : '';

                        $rating .= '<i class="las la-star ' . $fillColor . '"></i>';
                    }

                    return [
                        'id' => $data->id,
                        'employee' => $data->employee->name,
                        'date' => $data->date,
                        'company_info' => $companyInfo,
                        'meeting_time' => $meetingTime,
                        'file' => $file,
                        'rating' => $rating,
                        '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 storeTravelMeeting($request, $plan_id)
    {
        if ($request->file_id) {
            $file_id = $request->file_id;
        } else {
            $file_id = $request->file ? $this->uploadImage($request->file, 'uploads/travel/file')->id : null;
        }

        $travelMeeting                               = new TravelMeeting();
        $travelMeeting->travel_plan_id               = $plan_id;
        $travelMeeting->employee_id                  = auth()->id();
        $travelMeeting->date                         = Carbon::parse($request->date)->format('Y-m-d');
        $travelMeeting->meeting_schedule_time        = $request->meeting_schedule_time;
        $travelMeeting->meeting_start_time           = $request->meeting_start_time;
        $travelMeeting->meeting_end_time             = $request->meeting_end_time;
        $travelMeeting->customer_company_name        = $request->customer_company_name;
        $travelMeeting->customer_name                = $request->customer_name;
        $travelMeeting->customer_email               = $request->customer_email;
        $travelMeeting->customer_phone               = $request->customer_phone;
        $travelMeeting->purpose                      = $request->purpose;
        $travelMeeting->remark                       = $request->remark;
        $travelMeeting->file_id                      = $file_id;
        $travelMeeting->rating_of_meeting_experience = $request->rating ?? $request->rating_of_meeting_experience;
        $travelMeeting->company_id                   = auth()->user()->company_id;
        $travelMeeting->branch_id                    = getCurrentBranch();
        $travelMeeting->created_by                   = auth()->id();

        $travelMeeting->save();

        return $travelMeeting;
    }
    
    public function updateTravelMeeting($request, $id)
    {
        $travelMeeting = TravelMeeting::find($id);

        if ($request->file_id) {
            $file_id = $request->file_id;
        } else {
            $file_id = $request->file ? $this->uploadImage($request->file, 'uploads/travel/file')->id : $travelMeeting->file_id;
        }

        if ($request->file || $request->file_id) {

            $upload_id = $travelMeeting->file_id;

            $travelMeeting->file_id = null;

            $travelMeeting->save();

            if (file_exists(asset_path($upload_id))) {
                unlink(asset_path($upload_id));
            }

            Upload::destroy($upload_id);
        }
        
        $travelMeeting->date                         = Carbon::parse($request->date)->format('Y-m-d');
        $travelMeeting->meeting_schedule_time        = $request->meeting_schedule_time;
        $travelMeeting->meeting_start_time           = $request->meeting_start_time;
        $travelMeeting->meeting_end_time             = $request->meeting_end_time;
        $travelMeeting->customer_company_name        = $request->customer_company_name;
        $travelMeeting->customer_name                = $request->customer_name;
        $travelMeeting->customer_email               = $request->customer_email;
        $travelMeeting->customer_phone               = $request->customer_phone;
        $travelMeeting->purpose                      = $request->purpose;
        $travelMeeting->remark                       = $request->remark;
        $travelMeeting->file_id                      = $file_id;
        $travelMeeting->rating_of_meeting_experience = $request->rating ?? $request->rating_of_meeting_experience;
        $travelMeeting->updated_by                   = auth()->id();

        $travelMeeting->save();

        return $travelMeeting;
    }

    public function delete($id)
    {
        DB::transaction(function () use ($id) {
            $travelMeeting = TravelMeeting::find($id);

            if ($travelMeeting->file_id) {
                $upload_id = $travelMeeting->file_id;

                $travelMeeting->update([
                    'file_id' => null
                ]);

                if (file_exists(asset_path($upload_id))) {
                    unlink(asset_path($upload_id));
                }

                Upload::destroy($upload_id);
            }

            $travelMeeting->delete();
        });
    }
}
