<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pemeriksaan;
use App\Models\DataPasien;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;


class PemeriksaanController extends Controller
{
  public function pendaftaranPemeriksaan(Request $request, $id)
  {
    $dataPasien = DataPasien::find($id);

    return view(
      'daftar_antrian_pasien.keluhan_dan_pemeriksaan_pasien',
      compact('dataPasien')
    )->with(['notif' => 'add']);
  }

  public function storePemeriksaan(Request $request, $id)
  {
    $data = $request->only(
      'p_alergi',
      'p_anamnesa',
      'p_pemeriksaan_fisik'
    );

    $data['dp_id'] = $id;
    $data['p_status'] = "Antrian";

    Pemeriksaan::create($data);

    return redirect('antrian')->with(['notif' => 'add']);
  }

  public function daftarAntrianPemeriksaan()
  {
    $date = Carbon::now();

    $dataAntrian = Pemeriksaan::all()
      ->load('dataPasien')
      ->where('p_status', '=', 'Antrian')
      ->whereBetween('p_created_at', [Carbon::parse($date)->startOfDay(), Carbon::parse($date)->endOfDay()]);

    return view('antrian.antrian', compact('dataAntrian'));
  }

  public function deleteAntrian(Pemeriksaan $pemeriksaan)
  {
    $pemeriksaan->delete();

    return redirect('antrian');
  }

  public function data()
  {
    $date = Carbon::now();

    $dataAntrian = DB::table('pemeriksaan')
      ->join('data_pasien', 'pemeriksaan.dp_id', '=', 'data_pasien.dp_id')
      ->select(
        'pemeriksaan.*',
        'data_pasien.*',
        DB::raw(
          'DATE_FORMAT(
        FROM_DAYS(
            DATEDIFF(CURRENT_DATE, data_pasien.dp_tgl_lahir)
        ),
        "%y Tahun %m Bulan %d Hari"
        ) 
				AS usia'
        )
      )
      ->whereBetween('p_created_at', [Carbon::parse($date)->startOfDay(), Carbon::parse($date)->endOfDay()])
      ->where('p_deleted_at', '=', null)
      ->where('p_status', '!=', 'Ditangani')
      ->orderBy('pemeriksaan.p_id', 'asc')
      ->get();

    return response(['data' => $dataAntrian]);
  }
}
