<?php

namespace App\Services\User\Tickets;

use App\Models\Ticket;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class TicketsService
{
    /** get ticket list */
    public function getTickets(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        /** @var LengthAwarePaginator */
        $tickets = $user->tickets()->when($request->input('search'), function ($query, $search) {
            $query->where('title', 'like', "%{$search}%");
        })->when($request->input('waiting_admin'), function ($query, $waiting_admin) {
            if ($waiting_admin) {
                $query->where('status', 'waiting_admin');
            }
        })->when($request->input('waiting_user'), function ($query, $waiting_user) {
            if ($waiting_user) {
                $query->where('status', 'waiting_user');
            }
        })->when($request->input('closed'), function ($query, $closed) {
            if ($closed) {
                $query->where('status', 'closed');
            }
        })->orderByRaw("FIELD(status , 'waiting_user', 'waiting_admin', 'closed') ASC")
            ->orderByRaw("FIELD(priority , 'high', 'normal', 'low') ASC")
            ->orderBy('updated_at', 'asc')->paginate(20)->through(fn($ticket) => [
                'id' => $ticket->id,
                'jalali_created_at' => $ticket->jalali_created_at,
                'jalali_updated_at' => $ticket->jalali_updated_at,
                'priority' => $ticket->priority,
                'status' => $ticket->status,
                'title' => $ticket->title,
                'user_id' => $ticket->user_id,
            ]);

        $tickets->withQueryString();

        return $tickets;
    }

    /** upload attachment */
    public function uploadAttachment(Request $request, User $user, Ticket $ticket, $attachmentStatus = false)
    {
        // check folders
        try {
            $this->fixMediaFolders();
        } catch (Exception $e) {
        }

        $file = $request->file('attachment');
        $fileFormat = $file->getClientOriginalExtension();
        $fileType = null;

        switch ($fileFormat) {
            case "jpeg":
            case "jpg":
            case "png":
            case "webp":
            case "gif":
            case "svg":
                $fileType = "image";
                break;
            default:
                return;
                break;
        }

        $fileName = 'file.' . time() . '.' . rand(10000, 99999) . '.' . $file->getClientOriginalExtension();
        $fileSize = floor($file->getSize() / 1000);
        $fileSaveAddressNoName = 'library/' . date('Y-m-d') . '/' . $user->id;
        $fileSaveAddress = $fileSaveAddressNoName . '/' . $fileName;
        $imageResolution = null;

        if ($fileType == "image") {
            $imageResolution = getimagesize($file)[0] . '×' . getimagesize($file)[1];
        }

        $uploadResult = Storage::disk('media')->put($fileSaveAddress, file_get_contents($file));

        if ($uploadResult) {
            $attachmentFile = $user->files()->create([
                'name' => $fileName,
                'url' => '/media/' . $fileSaveAddress,
                'description' => __('messages.sentence.user_attachment_file') . ' ' . $user->get_name,
                'extension' => $fileFormat,
                'size' => $fileSize,
                'resolution' => $imageResolution,
                'type' => $fileType,
            ]);

            if ($attachmentFile != null) {
                $attachment = $ticket->ticketAnswers()->create([
                    'user_id' => $user->id,
                    'type' => 'file',
                    'file' => $attachmentFile->id,
                    'status' => 'publish',
                ]);

                if ($attachmentStatus && $attachment != null) {
                    $ticket->update([
                        'status' => 'waiting_admin'
                    ]);
                }
            }
        }
    }

    /**
     * fix folders permission
     */
    private function fixMediaFolders()
    {
        $disk = Storage::disk('media');
        $rootPath = $disk->path(''); // مسیر root storage/app/media

        $this->checkFolders($rootPath);
    }

    /**
     * check folders permission
     */
    private function checkFolders($path)
    {
        // فقط پوشه‌ها
        $folders = glob($path . '/*', GLOB_ONLYDIR);

        foreach ($folders as $folder) {
            $perm = substr(sprintf('%o', fileperms($folder)), -3);

            // اگر پرمیشن غیر از 755 بود
            if ($perm !== '755') {
                @chmod($folder, 0755);
            }

            // بررسی پوشه‌های داخل این پوشه به صورت بازگشتی
            $this->checkFolders($folder);
        }
    }
}
