<?php

namespace Modules\Travel\Repositories;

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

class TravelWorkflowRepository
{
    use FileHandler;


    function fields()
    {
        return [
            _trans('common.ID'),
            _trans('common.Employee'),
            _trans('common.Date'),
            _trans('common.Time'),
            _trans('common.Calls Made'),
            _trans('common.Positive Leads'),
            _trans('common.Total Sales'),
            _trans('common.How was your day'),
            _trans('common.Action')
        ];
    }

    function table($request)
    {
        $data = TravelWorkflow::query()
            ->with(['employee'])
            ->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 . '%');
                    });
                });
            })
            ->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) {
                    $action_button = '';

                    if (hasPermission('travel_workflow_read')) {
                        $action_button .= '<a href="' . route('travel.workflows.show', $data->id) . '" class="dropdown-item"> ' . _trans('common.View') . ' </a>';
                    }

                    if (hasPermission('travel_workflow_update')) {
                        $action_button .= '<a href="' . route('travel.workflows.edit', $data->id) . '" class="dropdown-item"> ' . _trans('common.Edit') . ' </a>';
                    }

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

                    $totalTime = calculateTotalHoursHumanReadable($data->start_time, $data->end_time);
                    $time =  '<div class="d-flex flex-column gap-0">
                                    <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->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->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>';

                    return [
                        'id' => $data->id,
                        'employee' => $data->employee->name,
                        'date' => $data->date,
                        'time' => $time,
                        'calls_made' => $data->calls_made,
                        'positive_leads' => $data->positive_leads,
                        'total_sales' => $data->total_sales,
                        'how_was_your_day' => $data->how_was_your_day_mark,
                        '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 storeTravelWorkflow($request)
    {
        $travelWorkflow                                = new TravelWorkflow();
        $travelWorkflow->employee_id                   = auth()->id();
        $travelWorkflow->date                          = $request->date;
        $travelWorkflow->start_time                    = $request->start_time;
        $travelWorkflow->end_time                      = $request->end_time;
        $travelWorkflow->calls_made                    = $request->calls_made;
        $travelWorkflow->positive_leads                = $request->positive_leads;
        $travelWorkflow->total_sales                   = $request->total_sales;
        $travelWorkflow->is_update_pending_and_leads   = $request->is_update_pending_and_leads;
        $travelWorkflow->pending_and_leads_other_note  = $request->pending_and_leads_other_note;
        $travelWorkflow->is_worked_on_recovery_today   = $request->is_worked_on_recovery_today;
        $travelWorkflow->recovery_today_other_note     = $request->recovery_today_other_note;
        $travelWorkflow->daily_report_summary          = $request->daily_report_summary;
        $travelWorkflow->complaints_questions_comments = $request->complaints_questions_comments;
        $travelWorkflow->file_id                       = $request->file ? $this->uploadImage($request->file, 'uploads/travel/workflow')->id : null;
        $travelWorkflow->how_was_your_day_mark         = $request->how_was_your_day_mark;
        $travelWorkflow->company_id                    = auth()->user()->company_id;
        $travelWorkflow->branch_id                     = getCurrentBranch();
        $travelWorkflow->created_by                    = auth()->id();
        $travelWorkflow->save();

        return $travelWorkflow;
    }

    public function updateTravelWorkflow($request, $id)
    {
        $travelWorkflow                                = TravelWorkflow::find($id);

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

            $travelWorkflow->file_id = null;

            $travelWorkflow->save();

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

            Upload::destroy($upload_id);
        }

        $travelWorkflow->date                          = $request->date;
        $travelWorkflow->start_time                    = $request->start_time;
        $travelWorkflow->end_time                      = $request->end_time;
        $travelWorkflow->calls_made                    = $request->calls_made;
        $travelWorkflow->positive_leads                = $request->positive_leads;
        $travelWorkflow->total_sales                   = $request->total_sales;
        $travelWorkflow->is_update_pending_and_leads   = $request->is_update_pending_and_leads;
        $travelWorkflow->pending_and_leads_other_note  = $request->pending_and_leads_other_note;
        $travelWorkflow->is_worked_on_recovery_today   = $request->is_worked_on_recovery_today;
        $travelWorkflow->recovery_today_other_note     = $request->recovery_today_other_note;
        $travelWorkflow->daily_report_summary          = $request->daily_report_summary;
        $travelWorkflow->complaints_questions_comments = $request->complaints_questions_comments;
        $travelWorkflow->file_id                       = $request->file ? $this->uploadImage($request->file, 'uploads/travel/workflow')->id : $travelWorkflow->file_id;
        $travelWorkflow->how_was_your_day_mark         = $request->how_was_your_day_mark;
        $travelWorkflow->updated_by                    = auth()->id();

        $travelWorkflow->save();

        return $travelWorkflow;
    }

    public function delete($id)
    {
        DB::transaction(function () use ($id) {
            $travelWorkflow = TravelWorkflow::find($id);

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

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

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

                Upload::destroy($upload_id);
            }

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