<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class FileService
{
    public static function saveFiles($files, string $table, string $t_id, string $t_id_type = '00')
    {
        if (isset($files) && is_array($files)) {
            foreach ($files as $file) {
                $fileName = $file->getClientOriginalName();
                $randomName = bin2hex(random_bytes(16));
                $fileType = $file->getClientMimeType();
                $fileSize = $file->getSize();
                // $tempFile = $file->getPathname();

                $folder = config('custom.data_path').substr($t_id, 0, 6).'/';
                $targetPath = $folder.$randomName;

                if (! is_dir($folder)) {
                    mkdir($folder, 0755, true);
                }

                try {
                    // move_uploaded_file($tempFile, $targetPath);
                    $file->move($folder, $randomName);
                    chmod($targetPath, 0644);

                    DB::table('SITE_FILES')->insert([
                        'F_NAME' => $fileName,
                        'R_NAME' => $randomName,
                        'TABLE' => $table,
                        'T_ID' => $t_id,
                        'T_ID_TYPE' => $t_id_type,
                        'F_TYPE' => $fileType,
                        'F_SIZE' => $fileSize,
                        'REG_USER_NO' => session('Adm.idx') ?? 1,
                    ]);
                } catch (\Exception $e) {
                    return ['error' => '파일업로드 실패', 'code' => 422];
                }
            }
        }
    }

    public static function uploadFiles($request)
    {
        $files = $request['upload'] ?? '';
        $table = $request['table'] ?? 'COMPANY_INFO';
        $t_id = $request['com_no'];
        $file_no = $request['file_no'] ?? '';

        if (isset($files) && is_array($files)) {
            foreach ($files as $key => $file) {

                $originalName = $file->getClientOriginalName(); // 예: "파일명.jpg"
                $ext = pathinfo($originalName, PATHINFO_EXTENSION); // 확장자만 추출: "jpg"
                $userInputName = $request['fileName'][$key] ?? null;
                $fileName = $userInputName ? $userInputName.'.'.$ext : $originalName;

                $randomName = bin2hex(random_bytes(16));
                $fileType = $file->getClientMimeType();
                $fileSize = $file->getSize();
                $t_id_type = $request['fileType'][$key] ?? '00';

                $folder = config('custom.data_path').substr($t_id, 0, 6).'/';
                $targetPath = $folder.$randomName;

                if (! is_dir($folder)) {
                    mkdir($folder, 0755, true);
                }

                try {
                    $file->move($folder, $randomName);
                    chmod($targetPath, 0644);

                    if (! empty($file_no)) {
                        self::deleteFiles(['f_id' => $file_no]);
                    }
                    // 신규 파일 등록
                    DB::table('SITE_FILES')->insert([
                        'F_NAME' => $fileName,
                        'R_NAME' => $randomName,
                        'TABLE' => $table,
                        'T_ID' => $t_id,
                        'T_ID_TYPE' => $t_id_type,
                        'F_TYPE' => $fileType,
                        'F_SIZE' => $fileSize,
                        'REG_USER_NO' => session('Adm.idx') ?? 1,
                    ]);
                } catch (\Exception $e) {
                    return ['error' => '파일업로드 실패', 'code' => 422];
                }
            }

        } elseif ($file_no) {

            // 기존파일인데 업로드 파일이 없을경우 이름과 타입만 변경
            if ($request['fileName'][1]) {
                $ext = pathinfo(DB::table('SITE_FILES')->where('F_NO', $file_no)->value('F_NAME'), PATHINFO_EXTENSION);
                $data['F_NAME'] = $request['fileName'][1].'.'.$ext;
            }

            if ($request['fileType'][1]) {
                $data['T_ID_TYPE'] = $request['fileType'][1];
            }

            DB::table('SITE_FILES')->where('F_NO', $file_no)->update($data);
        }

        return self::getFiles($request);
    }

    public static function getFiles(array $params): array
    {
        $tType = $params['t_type'] ?? null;
        $table = $params['table'] ?? '';
        $idx = $params['idx'] ?? '';
        $com_no = $params['com_no'] ?? '';
        $params['debug'] = $params['debug'] ?? true;

        $query = DB::table('SITE_FILES as SF')
            ->select('SF.T_ID', 'SF.F_NO', 'SF.F_NAME', 'SF.R_NAME', DB::raw('LEFT(SF.T_ID, 6) as PATH'), 'SF.REG_USER_NO');

        if ($table) {
            $query->where('SF.TABLE', $table);
        }
        if ($idx) {
            $query->whereIn('SF.T_ID', explode(',', $idx));
        } elseif ($com_no) {
            $query->where('SF.T_ID', $com_no);
        }
        if ($tType) {
            $query->where('SF.T_ID_TYPE', $tType);
        }

        return $query->get();
    }

    public static function deleteFiles(array $params): string
    {
        $table = $params['TABLE'] ?? null;
        $t_id = $params['T_ID'] ?? null;
        $f_id = $params['f_id'] ?? null;

        $query = DB::table('SITE_FILES');

        if ($table && $t_id) {
            $query->where('TABLE', $table)->where('T_ID', $t_id);
        } elseif ($f_id) {
            $query->whereIn('F_NO', explode(',', $f_id));
        } else {
            return 'Error';
            logger('파일삭제 - 검색조건이 없음');
        }

        $files = $query->get();
        if (empty($files)) {
            return 'Success';
        }
        foreach ($files as $file) {
            $filePath = config('custom.data_path').substr($file->T_ID, 0, 6).'/'.$file->R_NAME;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        $query->delete();

        return 'Success';
    }

    public static function findFile(array $params): ?array
    {
        $fileName = $params['fileName'] ?? '';
        $F_NO = $params['file_no'] ?? '';

        $query = DB::table('SITE_FILES as SF')
            ->select('F_NAME', 'T_ID', 'F_TYPE', DB::raw("IFNULL((SELECT COM_NAME FROM COMPANY_INFO CI WHERE SF.T_ID = CI.COM_NO AND SF.TABLE = 'COMPANY_INFO' LIMIT 1), '') as COM_NAME"));

        if ($F_NO) {
            $query->where('F_NO', $F_NO);
        } else {
            $query->where('R_NAME', $fileName)->first();
        }

        return $query;
    }
}
