<?php

namespace App\Http\Controllers;

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

class LaporanController extends Controller
{
  public function index(Request $request)
  {
    $date = Carbon::now();
    $DSAwal = $request->input('tgl_awal');
    $DSAkhir = $request->input('tgl_akhir');
    $dDisplay = $date->format('d-m-Y');
    if ($DSAkhir == null && $DSAwal == null) {
      $dAwal = Carbon::parse($DSAwal)->format('d-m-Y');
      $dAkhir = null;
    } else {
      $dAwal = Carbon::parse($DSAwal)->format('d-m-Y');
      $dAkhir = Carbon::parse($DSAkhir)->format('d-m-Y');
    }

    $totalPendapatan = $this->getTotalPendapatan($dAwal, $dAkhir);
    $totalPasien = $this->getTotalPasien($dAwal, $dAkhir);


    $dataLaporan = Antrian::all()
      ->load('pasien')
      ->whereBetween('a_created_at', [Carbon::parse($dAwal)->startOfDay(), Carbon::parse($dAwal)->endOfDay()])
      ->where('a_status', '=', 'Ditangani');
    return view(
      'laporan.laporan',
      compact('dataLaporan'),
      [
        'date' => $dDisplay,
        'DSAwal' => $dAwal,
        'DSAkhir' => $dAkhir,
        'totalPendapatan' => $totalPendapatan,
        'totalPasien' => $totalPasien
      ]
    );
  }

  public function getTotalPendapatan($dAwal, $dAkhir)
  {
    if ($dAkhir == null) {
      $totalPendapatan = DB::table('antrian')
        ->select(DB::raw('SUM(a_pembayaran) as total'))
        ->whereBetween('a_created_at', [Carbon::parse($dAwal)->startOfDay(), Carbon::parse($dAwal)->endOfDay()])
        ->where('a_status', '=', 'Ditangani')
        ->groupBy('a_status')->value('total');
    } else {
      $totalPendapatan = DB::table('antrian')
        ->select(DB::raw('SUM(a_pembayaran) as total'))
        ->whereBetween('a_created_at', [Carbon::parse($dAwal)->startOfDay(), Carbon::parse($dAkhir)->endOfDay()])
        ->where('a_status', '=', 'Ditangani')
        ->groupBy('a_status')->value('total');
    }
    return $totalPendapatan;
  }

  public function getTotalPasien($dAwal, $dAkhir)
  {
    if ($dAkhir == null) {
      $totalPasien = DB::table('antrian')
        ->select(DB::raw('COUNT(a_id) as total'))
        ->whereBetween('a_created_at', [Carbon::parse($dAwal)->startOfDay(), Carbon::parse($dAwal)->endOfDay()])
        ->where('a_status', '=', 'Ditangani')
        ->groupBy('a_status')->value('total');
    } else {
      $totalPasien = DB::table('antrian')
        ->select(DB::raw('COUNT(a_id) as total'))
        ->whereBetween('a_created_at', [Carbon::parse($dAwal)->startOfDay(), Carbon::parse($dAkhir)->endOfDay()])
        ->where('a_status', '=', 'Ditangani')
        ->groupBy('a_status')->value('total');
    }

    return $totalPasien;
  }
}
