<?php

namespace Modules\SupportTicket\Repositories;

use App\Traits\SendNotification;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Modules\CourseSetting\Entities\Course;
use Modules\SupportTicket\Entities\SupportTicket;
use Modules\SupportTicket\Entities\SupportTicketFile;
use Modules\SupportTicket\Entities\TicketCategory;
use Modules\SupportTicket\Entities\TicketPriority;
use Modules\SupportTicket\Entities\TicketStatus;

class SupportTicketRepository
{
    use SendNotification;

    public function coursesTicketList(array $filter_data = [])
    {
         $user = Auth::user();
        $query = SupportTicket::query();
        if ($user->role_id == 5 && isModuleActive('Organization') && Auth::user()->isOrganization()) {
            $query = SupportTicket::query();
            $query->whereHas('assignUser', function ($q) {
                $q->where('organization_id', Auth::id());
                $q->orWhere('id', Auth::id());
            });
        } elseif ($user->role_id !== 1) {
            $query = SupportTicket::query()->where('refer_id', $user->id);
        }

        $query->with(['attachFiles', 'user', 'category', 'priority', 'status', 'messages', 'assignUser']);
        $query->whereNotNull('course_id');

        $priority = $filter_data['f_priority_id'] ?? null;
        $status = $filter_data['f_status_id'] ?? null;

        $query->when($priority, function ($query, $priority) {
            $query->where('priority_id', $priority);
        });

        $query->when($status, function ($query, $status) {
            $query->where('status_id', $status);
        });

        return $query->latest();
    }


    public function ticketList()
    {
        return SupportTicket::with(['attachFiles', 'user', 'category', 'priority', 'status', 'messages'])->whereNull('course_id')->latest();
    }

    public function ticketListMine()
    {
        $category_id = request()->category_id;
        $priority_id = request()->priority_id;
        $status_id = request()->status_id;
       return SupportTicket::with(['attachFiles', 'user'])
            ->where('refer_id', auth()->id())
            ->when($category_id, function ($query, $category_id) {
                $query->where('category_id', $category_id);
            })
            ->when($priority_id, function ($query, $priority_id) {
                $query->where('priority_id', $priority_id);
            })
            ->when($status_id, function ($query, $status_id) {
                $query->where('status_id', $status_id);
            })
            ->latest();
    }

    public function ticketListByAuth()
    {
        $query = SupportTicket::with(['attachFiles', 'user'])->where('user_id', auth()->id())->latest();

        if (request()->category) {
            $query->where('category_id', request()->category);
        }
        if (request()->priority) {
            $query->where('priority_id', request()->priority);
        }
        if (request()->status) {
            $query->where('status_id', request()->status);
        }
        return $query;
    }

    public function ticketListWithUserReferId()
    {
        return SupportTicket::where('user_id', auth()->id())->orWhere('refer_id', auth()->id())->orWhere('refer_id', null)->whereNull('course_id')->with('attachFiles')->latest()->get();
    }

    public function categoryList()
    {
        return TicketCategory::where('status', 1)->latest()->get();
    }

    public function priorityList()
    {
        return TicketPriority::where('status', 1)->latest()->get();
    }

    public function statusList()
    {
        return TicketStatus::where('status', 1)->latest()->get();
    }

    public function agentList()
    {
        return User::whereIn('role_id', [1, 4])->get();
    }

    public function userList($id)
    {
        return User::whereNotIn('role_id', [1, 4])->where('id', '!=', $id)->latest()->get();
    }

    public function addAttachment($supportTicket, $files)
    {
        if (!file_exists('public/upload/support_ticket/')) {
            mkdir('public/upload/support_ticket/', 0777, true);
        }
        foreach ($files as $file) {
            if ($file) {
                $ignore = strtolower($file->getClientOriginalExtension());
                if ($ignore != 'php' && $ignore != 'js') {
                    $fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
                    $file->move('public/upload/support_ticket/', $fileName);
                    $filePath = 'public/upload/support_ticket/' . $fileName;

                    $ticketFile = new SupportTicketFile();
                    $ticketFile->attachment_id = $supportTicket->id;
                    $ticketFile->url = $filePath;
                    $ticketFile->name = $file->getClientOriginalName();
                    $ticketFile->type = $file->getClientOriginalExtension();
                    $supportTicket->attachFiles()->save($ticketFile);
                }
            }

        }
    }

    public function create(array $data)
    {
        $rand = mt_rand(10, 99);
        $time = time();
        $time = substr($time, 6);
        $pre = 'TIC-';
        $uliqueId = $rand . $time;

        $supportTicket = SupportTicket::create([
            'reference_no' => $pre . $uliqueId,
            'subject' => $data['subject'],
            'description' => clean($data['description']),
            'user_id' => $data['user_id'] ?? auth()->id(),
            'refer_id' => $data['refer_id'] ?? null,
            'priority_id' => $data['priority_id'],
            'category_id' => $data['category_id'],
            'status_id' => $data['status'] ?? 1,
            'course_id' => $data['course_id'] ?? null
        ]);

        if (isset($data['course_id']) && $data['course_id'] && $supportTicket->refer_id == null) {
            $course = Course::where('id', $data['course_id'])->first();
            if ($course) {
                $supportTicket->refer_id = $course->user_id;
                $supportTicket->save();
            }
        }

        $files = isset($data['ticket_file']) ? $data['ticket_file'] : null;

        if ($files != null) {
            $this->addAttachment($supportTicket, $files);
        }


        $admins = User::where('role_id', 1)->get();
        foreach ($admins as $admin) {
            $this->sendNotification('CREATE_SUPPORT_TICKET', $admin, [
                'created_by' => $supportTicket->user->name,
                'time' => now(),
                'category' => $supportTicket->category->name,
                'priority' => $supportTicket->priority->name,
                'subject' => $supportTicket->subject,
                'message' => $supportTicket->description,
            ]);
        }

        return $supportTicket;
    }

    public function supportTicketWithMsgAndFile($id)
    {

        return SupportTicket::with('messages')->with('messages.attachFiles')->find($id);
    }

    public function new()
    {
        return new SupportTicket();
    }

    public function find($id)
    {
        return SupportTicket::with('attachFiles')->findOrFail($id);
    }

    public function update(array $data, $id)
    {

        $supportTicket = SupportTicket::findOrFail($id);
        $supportTicket->update([
            'subject' => $data['subject'],
            'description' => clean($data['description']),
            'user_id' => $data['user_id'] ?? $supportTicket->user_id,
            'refer_id' => $data['refer_id'] ?? $supportTicket->refer_id,
            'priority_id' => $data['priority_id'],
            'category_id' => $data['category_id'],
            'status_id' => $data['status'] ?? $supportTicket->status_id,
            'course_id' => $data['course_id'] ?? null
        ]);

        $changes = $supportTicket->getChanges();

        if (in_array('category_id', $changes)) {
            $category = TicketCategory::find($changes['category_id']);
            if ($category->slug != 'course') {
                $supportTicket->course_id = null;
                $supportTicket->save();
            }
        }

        if (isset($data['course_id']) && $data['course_id'] && in_array('course', $changes)) {
            $course = Course::where('id', $data['course_id'])->first();
            if ($course) {
                $supportTicket->refer_id = $course->user_id;
                $supportTicket->save();
            }
        }

        $files = $data['ticket_file'] ?? null;

        if ($files != null) {
            $this->addAttachment($supportTicket, $files);
        }

        return true;
    }

    public function ticketWithFile($id)
    {

        return SupportTicket::where('id', $id)->with('attachFiles')->first();
    }

    public function fileDelete($id)
    {
        return SupportTicketFile::whereIn('id', $id)->delete();
    }

    public function attachFileDelete($id)
    {
        $file = SupportTicketFile::findOrFail($id);

        File::delete($file->url);
        $file->delete();
        return true;
    }

    public function searchWithAttr($category_id, $priority_id, $status_id)
    {

        $supportTicket = SupportTicket::with(['attachFiles', 'user', 'category', 'priority', 'status']);
        $supportTicket->whereNull('course_id');

        if ($category_id != null) {
            $supportTicket->where('category_id', $category_id);
        }

        if ($priority_id != null) {
            $supportTicket->where('priority_id', $priority_id);
        }

        if ($status_id != null) {
            $supportTicket->where('status_id', $status_id);
        }

        return $supportTicket;
    }

    public function searchAssignedTicketWithAttr($category_id, $priority_id, $status_id)
    {
        $supportTicket = SupportTicket::query();
        $supportTicket->whereNull('course_id');
        if ($status_id) {
            $supportTicket->where('status_id', $status_id);
        }
        if ($category_id) {
            $supportTicket->where('category_id', $category_id);
        }
        if ($priority_id) {
            $supportTicket->where('priority_id', $priority_id);
        }
        return $supportTicket->with(['attachFiles', 'user', 'category', 'priority', 'status'])->where('refer_id', auth()->id())->latest();
    }

    public function search()
    {
        return SupportTicket::with(['attachFiles', 'user', 'category', 'priority', 'status'])->whereNull('course_id')->orderBy('updated_at', 'desc');
    }

    public function saveSupportTicketFile(array $data)
    {
        return SupportTicketFile::create($data);
    }

}
