<?php

namespace App\Http\Controllers;

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

class AntrianController extends Controller
{
	public function index()
	{
		$date = Carbon::now();

		$dataAntrian = Antrian::all()
			->load('pasien')
			->where('a_status', '=', 'Antri')
			->whereBetween('a_created_at', [Carbon::parse($date)->startOfDay(), Carbon::parse($date)->endOfDay()]);

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

	public function deleteAntrian(Antrian $antrian)
	{
		$antrian->delete();

		return redirect('antrian');
	}

	public function penanganan($id)
	{
		$dataAntrian = Antrian::all()
			->load('pasien')
			->where('a_id', '=', $id)->first();

		$dataRekamMedis = Antrian::all()
			->load('pasien')
			->where('dp_id', '=', $dataAntrian['dp_id'])
			->where('a_status', '=', 'Ditangani');

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

	public function updatePenanganan(Request $request, Antrian $antrian)
	{
		$data = $request->only(
			'a_alergi',
			'a_anamnesa',
			'a_pemeriksaan_fisik',
			'a_diagnosa',
			'a_terapi',
			'a_pembayaran',
		);

		$data['a_status'] = "Ditangani";

		$antrian->update($data);

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

	public function updateStatusAntrian(Request $request, Antrian $antrian)
	{
		$data = $request->only(
			'a_status'
		);

		$antrian->update($data);
	}

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

		$dataAntrian = DB::table('antrian')
			->join('data_pasien', 'antrian.dp_id', '=', 'data_pasien.dp_id')
			->select(
				'antrian.*',
				'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('a_created_at', [Carbon::parse($date)->startOfDay(), Carbon::parse($date)->endOfDay()])
			->where('a_deleted_at', '=', null)
			->where('a_status', '!=', 'Ditangani')
			->orderBy('antrian.a_id', 'asc')
			->get();

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