<?php

namespace Modules\Laporan\Services;

use App\Models\ReportFile;
use App\Services\BaseService;
use Illuminate\Support\Facades\Storage;
use Modules\Laporan\Repositories\LaporanRepository;

class LaporanService extends BaseService implements LaporanServiceInterface
{
    public function __construct(LaporanRepository $laporanRepository)
    {
        $this->mainRepository = $laporanRepository;
    }

    public function datatable()
    {
        return $this->mainRepository->datatable();
    }

    public function datatableLaporanCategory()
    {
        return $this->mainRepository->datatableLaporanCategory();
    }

    public function storeReportFile($request){
        try {
            $userPath = getUploadPath() . config('ppid.laporan');
            $laporan = array();

            // DOKUMEN PERMOHONAN EKSEKUSI
            if ($request->has('userfile')) {
                $fileExecutionName = $request->file('userfile')->getClientOriginalName();
                $fileExecutionExtension = $request->file('userfile')->getClientOriginalExtension();
                $fileExecutionSize = convertFileSize($request->file('userfile')->getSize());

                // VALIDATION FILE SIZE
                if ($fileExecutionSize > getSetting('max_file_upload')) {
                    throw new \Exception(__('validation.max.file', ['attribute' => __('lang.file_report'), 'max' => config('ppid.max_file_upload'),]));
                }

                if (Storage::disk('public')->exists($userPath . '/' . $fileExecutionName)) {
                    throw new \Exception(__('messages.file_exists'));
                }

                // UPLOAD
                Storage::putFileAs($userPath, $request->file('userfile'), $fileExecutionName);

                $laporan[] = [
                    'name' => splitFile($fileExecutionName)[0],
                    'file' => $fileExecutionName,
                    'token' => $request->_token,
                    'created_by' => auth()->id(),
                    'created_at' => getTodayDate(),
                    'updated_at' => NULL,
                ];
            }

            return ReportFile::insert($laporan);
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage() . ' (Line : ' . $e->getLine() . ')', 'alert');

            return false;
        }
    }
}
