<?php

namespace App\Controllers;

use App\Controllers\BaseController;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;

use CodeIgniter\HTTP\DownloadResponse;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;

use App\Libraries\LogCollector;
use App\Services\MyLogService;

abstract class CommonController extends BaseController
{
    private $_myAuth = null;
    private ?MyLogService $_myLogService = null;
    private $_viewDatas = [];
    abstract public function getService(): mixed;
    abstract function getHelper(): mixed;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->isLoggedIn = false;
        if ($this->getMyAuth()->isLoggedIn()) {
            $this->isLoggedIn = true;
            $this->myAuthName = $this->getMyAuth()->getNameByAuthInfo();
            $this->myAuthUID = $this->getMyAuth()->getUIDByAuthInfo();
        }
    }
    final public function __get($name)
    {
        if (!array_key_exists($name, $this->_viewDatas)) {
            return null;
        }
        return $this->_viewDatas[$name];
    }
    final public function __set($name, $value): void
    {
        $this->_viewDatas[$name] = $value;
    }
    final protected function getMyAuth(): mixed
    {
        if (!$this->_myAuth) {
            $this->_myAuth = service('myauth');
        }
        return $this->_myAuth;
    }
    final public function getViewDatas(): array
    {
        return $this->_viewDatas;
    }
    final public function getMyLogService(): mixed
    {
        if (!$this->_myLogService) {
            $this->_myLogService = new MyLogService($this->request);
        }
        return $this->_myLogService;
    }
    //Index,FieldForm관련
    protected function init(string $action, array $fields = []): void
    {
        $this->action = $action;
        $this->fields = array_key_exists('fields', $fields) && is_array($fields['fields']) && count($fields['fields']) ? $fields['fields'] : $this->getFields();
        $this->field_rules = array_key_exists('field_rules', $fields) && is_array($fields['field_rules']) && count($fields['field_rules']) ? $fields['field_rules'] : $this->getFieldRules($this->action, $this->fields);
        $this->filter_fields = array_key_exists('filter_fields', $fields) && is_array($fields['filter_fields']) && count($fields['filter_fields']) ? $fields['filter_fields'] : $this->getFilterFields();
        $this->field_options = array_key_exists('field_options', $fields) && is_array($fields['field_optionss']) && count($fields['field_options']) ? $fields['field_options'] : $this->getFormFieldOptions($this->filter_fields);
        $this->batchjob_fields = array_key_exists('batchjob_fields', $fields) && is_array($fields['batchjob_fields']) && count($fields['batchjob_fields']) ? $fields['filter_fields'] : $this->getBatchJobFields();
    }
    public function getFields(): array
    {
        return  $this->getService()->getFields();
    }
    public function getFilterFields(): array
    {
        return  $this->getService()->getFilterFields();
    }
    public function getBatchJobFields(): array
    {
        return $this->getService()->getBatchJobFields();
    }
    protected function getFieldRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            default:
                $rule = $this->getService()->getFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    final protected function getFieldRules(string $action, array $fields, $rules = []): array
    {
        foreach ($fields as $field) {
            $rules[$field] = $this->getFieldRule($action, $field);
        }
        return $rules;
    }
    protected function getFormFieldOption(string $field, array $options): array
    {
        switch ($field) {
            default:
                $options[$field] = lang($this->getService()->getClassName() . '.' . strtoupper($field));
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 field의 options 값이 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    final protected function getFormFieldOptions(array $fields, array $options = []): array
    {
        foreach ($fields as $field) {
            if (is_array($field)) {
                throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true));
            }
            if (!array_key_exists($field, $options)) {
                $options[$field] = [];
            }
            $options = $this->getFormFieldOption($field, $options);
        }
        return $options;
    }
    protected function setValidation(Validation $validation, string $action, string $field, ?string $rule = null): Validation
    {
        switch ($field) {
            default:
                $validation->setRule($field, $field, $rule ?? $this->getFieldRule($action, $field));
                break;
        }
        return $validation;
    }
    //Field관련
    //데이터 검증
    final protected function doValidate(string $action, array $fields, ?Validation $validation = null): array
    {
        //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
        if (!$validation) {
            $validation = service('validation');
        }
        foreach ($fields as $field) {
            $validation = $this->setValidation($validation, $action, $field, $this->field_rules[$field] ?? null);
        }
        if (!$validation->withRequest($this->request)->run()) {
            throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
                "\n",
                $validation->getErrors()
            ));
        }
        return $validation->getValidated();
    }
    protected function getResultPageByActon(string $action, string $message = MESSAGES["SUCCESS"]): RedirectResponse|string
    {
        switch ($action) {
            case 'create':
                $segments = $this->request->getUri()->getSegments();
                if (!empty($segments)) {
                    // 마지막 세그먼트 무조건 view로 교체
                    $segments[count($segments) - 1] = 'view';
                }
                $redirectPath = '/' . implode('/', $segments);
                $result = redirect()->to($redirectPath . '/' . $this->entity->getPK());
                // $result = view($this->view_path . 'view', ['viewDatas' => $this->getViewDatas()]);;
                break;
            case 'modify':
                $segments = $this->request->getUri()->getSegments();
                if (!empty($segments)) {
                    // 마지막 세그먼트 무조건 view로 교체
                    $segments[count($segments) - 2] = 'view';
                }
                $result = redirect()->to('/' . implode('/', $segments));
                // $result = view($this->view_path . 'view', ['viewDatas' => $this->getViewDatas()]);;
                break;
            case 'create_form':
            case 'modify_form':
            case 'login_form':
            case 'index':
            case 'view':
                $this->getHelper()->setViewDatas($this->getViewDatas());
                $result = view($this->view_path . $action, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련

    //  생성
    protected function create_form_process(): void {}
    final public function create_form(): RedirectResponse|string
    {
        try {
            // 현재 URL을 스택에 저장
            // $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            helper(['form']);
            $this->init(__FUNCTION__);
            $this->create_form_process();
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    protected function create_process(): mixed
    {
        return $this->getService()->create($this->formDatas);
    }
    final public function create(): RedirectResponse|string
    {
        $this->getService()->getModel()->transStart();
        try {
            $this->init(__FUNCTION__);
            //데이터 검증
            $this->formDatas = $this->doValidate($this->action, $this->fields);
            $this->entity = $this->create_process();
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            // dd($e->getMessage());
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    //수정관련
    protected function modify_form_process(mixed $uid): mixed
    {
        return $this->getService()->getEntity($uid);
    }
    final public function modify_form(mixed $uid): RedirectResponse|string
    {
        try {
            // 현재 URL을 스택에 저장
            // $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            helper(['form']);
            $this->init(__FUNCTION__);
            $this->entity = $this->modify_form_process($uid);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    protected function modify_process(mixed $uid): mixed
    {
        //자신정보정의
        $entity = $this->getService()->getEntity($uid);
        return $this->getService()->modify($entity, $this->formDatas);
    }
    final public function modify(int $uid): RedirectResponse|string
    {
        //Transaction Start
        $this->getService()->getModel()->transStart();
        try {
            $this->init(__FUNCTION__);
            //데이터 검증
            $this->formDatas =  $this->doValidate($this->action, $this->fields);
            $this->entity = $this->modify_process($uid);
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    //단일필드작업
    protected function toggle_process(mixed $uid): mixed
    {
        //자신정보정의
        $entity = $this->getService()->getEntity($uid);
        return $this->getService()->modify($entity, $this->formDatas);
    }
    final public function toggle(mixed $uid, string $field): RedirectResponse
    {
        //Transaction Start
        $this->getService()->getModel()->transStart();
        try {
            $this->action = __FUNCTION__;
            $this->fields = [$field];
            //데이터 검증
            $this->formDatas =  $this->doValidate($this->action, $this->fields);
            $this->entity = $this->toggle_process($uid);
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    //일괄처리작업
    protected function batchjob_process(array $entities): array
    {
        $temps = [];
        foreach ($entities as $entity) {
            $temps[] = $this->getService()->modify($entity, $this->formDatas);
        }
        return $temps;
    }
    final public function batchjob(): RedirectResponse
    {
        //Transaction Start
        $this->getService()->getModel()->transStart();
        try {
            $this->init(__FUNCTION__);
            //변경할 UIDS
            $uids = $this->request->getVar('batchjob_uids[]');
            if (!is_array($uids) || !count($uids)) {
                throw new \Exception("적용할 리스트를 선택하셔야합니다.");
            }
            //데이터가 있는경우 Field만 처리하기위해
            $fields = [];
            foreach ($this->batchjob_fields as $field) {
                if ($this->request->getVar($field)) {
                    $fields[] = $field;
                }
            }
            if (!count($fields)) {
                throw new \Exception("변경할 정보를 선택하셔야합니다.");
            }
            $this->fields   = $fields;
            $entities = [];
            foreach ($uids as $uid) {
                $entity = $this->getService()->getEntity($uid);
                $entities[] = $entity;
            }
            //데이터 검증
            $this->formDatas =  $this->doValidate($this->action, $this->fields);
            $this->entities = $this->batchjob_process($entities);
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }

    //삭제,일괄삭제 공통사용
    protected function delete_process(mixed $entity): mixed
    {
        $result = $this->getService()->delete($entity);
        if (!$result) {
            throw new \Exception("[{$entity->getTitle()}] 삭제실패");
        }
        return $entity;
    }
    final public function delete(mixed $uid): RedirectResponse|string
    {
        //Transaction Start
        $this->getService()->getModel()->transStart();
        try {
            $this->init(__FUNCTION__);
            $entity = $this->getService()->getEntity($uid);
            $this->entity = $this->delete_process($entity);
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
    //일괄삭제
    protected function batchjob_delete_process(array $entities): int
    {
        $cnt = 0;
        foreach ($entities as $entity) {
            $result = $this->getService()->delete($entity);
            if (!$result) {
                LogCollector::error("[{$entity->getTitle()}] 삭제실패");
                $cnt++;
            }
        }
        return $cnt;
    }
    final public function batchjob_delete(): RedirectResponse|string
    {
        //Transaction Start
        $this->getService()->getModel()->transStart();
        try {
            $this->init(__FUNCTION__);
            //변경할 UIDS
            $uids = $this->request->getVar('batchjob_uids[]');
            if (!is_array($uids) || !count($uids)) {
                throw new \Exception("적용할 리스트를 선택하셔야합니다.");
            }
            $entities = [];
            foreach ($uids as $uid) {
                $entity = $this->getService()->getEntity($uid);
                $entities[] = $entity;
            }
            $cnt = $this->batchjob_delete_process($entities);
            if ($cnt) {
                $message = "총:" . count($entities) . "중에 " . $cnt . "개를 실패";
                LogCollector::error($message);
                throw new \Exception($message);
            }
            $this->getService()->getModel()->transCommit();
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["SUCCESS"]);
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            $this->getService()->getModel()->transRollback();
            LogCollector::debug($e->getMessage());
            $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->getMyAuth(), MESSAGES["FAILED"]);
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }

    //View
    protected function view_process($uid): mixed
    {
        //자신정보정의
        $entity = $this->getService()->getEntity($uid);
        if (!$entity) {
            throw new \Exception("해당 사용자정보를 찾을수 없습니다.");
        }
        return $entity;
    }
    final public function view(string $uid): RedirectResponse|string
    {
        try {
            helper(['form']);
            $this->init(__FUNCTION__);
            $this->entity = $this->view_process($uid);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }

    //리스트
    //List 조건절 처리
    final protected function setConditionForList(array $filter_fields): void
    {
        //조건절 처리
        foreach ($filter_fields as $field) {
            $this->$field = $this->request->getVar($field);
            if ($this->$field !== null && $this->$field !== '') {
                if ($field === 'role') {
                    $where = "FIND_IN_SET(" . $this->getService()->getModel()->escape($this->$field) . ", {$this->getService()->getModel()->getTable()}.{$field}) > 0";
                    //FIND_IN_SET()은 MySQL 함수이므로 CodeIgniter가 이를 일반 컬럼명으로 착각하고 escape하게 되면 오류가 발생합니다. 따라서 ->where($sql, null, false)로 명시하여 escape를 꺼줘야 정상 작동
                    $this->getService()->getModel()->where($where, null, false);
                } else {
                    $this->getService()->getModel()->where("{$this->getService()->getModel()->getTable()}.{$field}", $this->$field);
                }
            }
        }
        //검색어 처리
        $this->word = $this->request->getVar('word');
        if ($this->word !== null && $this->word !== '') {
            $this->getService()->getModel()->setList_WordFilter($this->word);
        }
        //검색일 처리
        $this->start  = $this->request->getVar('start');
        if ($this->start !== null && $this->start !== '') {
            $this->getService()->getModel()->where(sprintf("%s.created_at >= '%s 00:00:00'", $this->getService()->getModel()->getTable(), $this->start));
        }
        $this->end = $this->request->getVar('end');
        if ($this->end !== null && $this->end !== '') {
            $this->getService()->getModel()->where(sprintf("%s.created_at <= '%s 23:59:59'", $this->getService()->getModel()->getTable(), $this->end));
        }
    }
    protected function setOrderByForList()
    {
        //OrderBy 처리
        $this->order_field = $this->request->getVar('order_field');
        $this->order_value = $this->request->getVar('order_value');
        if ($this->order_field !== null && $this->order_field !== '') {
            $this->getService()->getModel()->orderBy(sprintf("%s.%s %s", $this->getService()->getModel()->getTable(), $this->order_field, $this->order_value ?: "DESC"));
        } else {
            $this->getService()->getModel()->orderBy(sprintf("%s.%s %s", $this->getService()->getModel()->getTable(), $this->getService()->getModel()->getPKField(), "DESC"));
        }
    }
    //PageNation 처리
    final protected function getPageOptionsByPaginationForList(): array
    {
        $page_options = ["" => "줄수선택"];
        for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
            $page_options[$i] = $i;
        }
        $page_options[$this->total_count] = $this->total_count;
        return $page_options;
    }
    final protected function getPaginationForList($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full')
    {
        //Page, Per_page필요부분
        $this->page = (int) $this->request->getVar('page') ?: 1;
        $this->per_page = (int) $this->request->getVar('per_page') ?: intval(DEFAULT_LIST_PERPAGE ?? 20);
        //줄수 처리용
        $this->page_options = $this->getPageOptionsByPaginationForList();
        // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성
        // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
        // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
        $pager = service("pager");
        // $this->getService()->getModel()->paginate($this->per_page, $pager_group, $this->page, $segment);
        $pager->makeLinks($this->page, $this->per_page, $this->total_count, $template, $segment, $pager_group);
        $this->page = $pager->getCurrentPage($pager_group);
        $this->total_page = $pager->getPageCount($pager_group);
        return $pager->links($pager_group, $template);
    }
    protected function index_process(): array
    {
        //조건절 처리
        $this->setConditionForList($this->filter_fields);
        //TotalCount
        $this->total_count = intval($this->getService()->getModel()->selectCount('*', 'cnt')->get()->getRow()->cnt);
        //Pagination 처리
        $this->pagination = $this->getPaginationForList();
        //조건절 , OrcerBy , Limit 처리
        $this->setConditionForList($this->filter_fields);
        $this->setOrderByForList();
        $this->getService()->getModel()->limit($this->per_page);
        $this->getService()->getModel()->offset(($this->page - 1) * $this->per_page);
        return $this->getService()->getEntities();
    }
    public function index()
    {
        try {
            // 현재 URL을 스택에 저장
            $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            helper(['form']);
            $this->init(__FUNCTION__);
            // if (env('app.debug.index')) {
            //     echo "ClassName: " . $this->getService()->getClassName() . "<BR>";
            //     echo "Title: " . $this->title . "<BR>";
            //     echo "uri_path: " . $this->uri_path . " <BR>";
            //     echo "view_path: " . $this->view_path . "<BR>";
            //     echo "action: " . $this->action . "<BR>";
            //     echo "fields: " . implode(",", $this->fields) . "<BR>";
            //     // exit;
            // }
            $this->entities = $this->index_process();
            return $this->getResultPageByActon($this->action);
        } catch (\Exception $e) {
            // if (env('app.debug.index')) {
            //     echo "Error ClassName: " . $this->getService()->getClassName() . "<BR>";
            //     echo "Error Title: " . $this->title . "<BR>";
            //     echo "Error uri_path: " . $this->uri_path . " <BR>";
            //     echo "Error view_path: " . $this->view_path . "<BR>";
            //     echo "Error action: " . $this->action . "<BR>";
            //     echo "Error fields: " . implode(",", $this->fields) . "<BR>";
            //     // exit;
            // }
            return redirect()->with('error', $e->getMessage());
        }
    }

    //OUPUT Document 관련
    private function download_document(string $document_type, mixed $loaded_data): array
    {
        $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel";
        switch ($document_type) {
            case 'excel':
                $file_name = sprintf("%s_%s.xlsx", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = IOFactory::createWriter($loaded_data, 'Xlsx');
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
            case 'pdf':
                $file_name = sprintf("%s_%s.pdf", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = new Mpdf($loaded_data);
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
        }
        return array($full_path, $file_name);
    }
    // Download
    final public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse
    {
        $this->init(__FUNCTION__);
        try {
            helper(['form']);
            //URL처리
            $this->uri = $this->request->getUri();
            switch ($output_type) {
                case 'excel':
                case 'pdf':
                    // string buffer에서 읽어오는 경우
                    $this->entities = $this->index_process();
                    $html = view('templates' . DIRECTORY_SEPARATOR . 'common' . DIRECTORY_SEPARATOR . __FUNCTION__, ['viewDatas' => $this->getViewDatas()]);
                    //data loading
                    $reader = new Html();
                    $loaded_data = $reader->loadFromString($html);
                    list($full_path, $file_name) = $this->download_document($output_type, $loaded_data);
                    $full_path .= DIRECTORY_SEPARATOR . $file_name;
                    break;
                default:
                    if (!$uid) {
                        throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다.");
                    }
                    $this->entity = $this->getService()->getEntity($uid);
                    list($file_name, $uploaded_filename) = $this->entity->getDownlaodFile();
                    $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename;
                    break;
            }
            return $this->response->download($full_path, null)->setFileName($file_name);
        } catch (\Exception $e) {
            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }
    }
}
