<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pasien;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

class PasienController extends Controller
{

    private $apiKey = "lkjnsfaJHoahslkf889w4najnKLNLKGjnaljnsdio8";

    public function show(Request $req, $id)
    {
        $errApiKey = "You don't have Authorization.";
        if ($this->apiKey != $req->header('apiKey')) {
            return response([
                'status' => 'Error',
                'message' => $errApiKey,
            ], 200);
        }

        $scsMessage = "Berhasil mengambil data pasien";
        $data = Pasien::where('id_perawat', $id)->orderBy('id', 'desc')->get();

        return response([
            'status' => 'Ok',
            'message' => $scsMessage,
            'data' => $data
        ], 200);
    }

    public function store(Request $req)
    {
        $errApiKey = "You don't have Authorization.";
        if ($this->apiKey != $req->header('apiKey')) {
            return response([
                'status' => 'Error',
                'message' => $errApiKey,
            ], 200);
        }

        $path_file = '';
        if ($req->hasFile('path_foto')) {
            $dir = 'storage/pasiens';
            $path = public_path($dir);
            if (!file_exists($path)) {
                File::makeDirectory($path, 0777, true, true);
            }
            $file = $req->file('path_foto');
            $file_name = Str::random(20).".jpg";
            $file->move($path, $file_name);
            $path_file = $dir . "/" . $file_name;
        }

        $scsMessage = "Berhasil menyimpan data.";
        $data = new Pasien();
        $data->id_perawat = $req->id_perawat;
        $data->nama = $req->nama;
        $data->tanggal_lahir = $req->tanggal_lahir;
        $data->tempat_lahir = $req->tempat_lahir;
        $data->alamat = $req->alamat;
        $data->pendidikan = $req->pendidikan;
        $data->pekerjaan = $req->pekerjaan;
        $data->status = $req->status;
        $data->path_foto = $path_file;
        $data->save();

        return response([
            'status' => 'Ok',
            'message' => $scsMessage,
            'data' => $data
        ], 200);
    }
}
