<?php

namespace App\Http\Controllers\Terra;
use App\Http\Controllers\Controller;
use App\Models\Patient;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Carbon\Carbon;

class ImportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['hn'] = 'TESTHN';
        return view('terra.wait.import', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $r)
    {
        if($r->event=="check_patient_id")       {return $this->check_patient_id($r);}
        if($r->event=="upload_file")            {return $this->upload_file($r);}


    }

    public function check_patient_id($r){
        $patient = Patient::get_patient_by_id($r->id);
        $is_match = (isset($patient) && $patient != '') ? $patient : 0;
        $json =  json_encode($is_match);
        echo $json;
    }

    public function upload_file($r){
        $file_name = '';
        $file = '';
        if(isset($r->file)){
            $file = $r->file('file');
            $file_name = $file->getClientOriginalName();
        }

        $path = 'D:/laragon/htdocs/terra';

        if($r->button == 'dicom'){
            $i['ud_fname']      = $file_name; // file
            $i['ud_hn']         = $r->dicom_id;
            $i['ud_name']       = $r->dicom_name;
            $i['ud_dob']        = $r->dicom_dob;
            $i['ud_institute']  = $r->dicom_int;
            $upload_location    = "$path/station";
            DB::table('tb_upload_dicom')->insert($i);
        } else {
            $file_name          = Carbon::now()->format('YmdHis').'.'.$file->getClientOriginalExtension();
            $study_date         = Carbon::parse($r->other_date)->format('Ymd');
            $gender             = $r->other_gender;
            $i['uo_fname']      = $file_name; // file
            $i['uo_hn']         = $r->other_id;
            $i['uo_name']       = $r->other_name;
            $i['uo_dob']        = $r->other_dob;
            $i['uo_gender']     = (str_contains($gender,'ชาย')) ? 1: 2;
            $i['uo_studydate']  = $study_date;
            $upload_location    = "$path/patient/$r->other_id/$study_date";
            DB::table('tb_upload_other')->insert($i);
        }
        $file->move($upload_location,$file_name);
        return redirect(url('terra').'/import');
    }

}
