<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\MedicalRecap;
use App\Imports\MedicalRecapImport;
use Maatwebsite\Excel\Facades\Excel;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;

class MedicalRecapController extends Controller
{
    public function index(Request $request)
    {
        $query = MedicalRecap::query();

        if ($request->filled('dokter')) {
            $query->where('dokter', $request->dokter);
        }

        if ($request->filled('start_date') && $request->filled('end_date')) {
            $query->whereBetween('tgl_perawatan', [$request->start_date, $request->end_date]);
        }

        if ($request->ajax()) {
            return \Yajra\DataTables\Facades\DataTables::of($query)
                ->addColumn('tgl_perawatan_formatted', function ($recap) {
                    return $recap->tgl_perawatan ? $recap->tgl_perawatan->format('d M y') : '-';
                })
                ->addColumn('dokter_formatted', function ($recap) {
                    $name = \Illuminate\Support\Str::limit($recap->dokter, 20);
                    return '<div style="font-weight: 600;">' . e($name) . '</div><div style="font-size: 0.75rem; color: var(--text-muted);">RMK: ' . e($recap->rmk) . '</div>';
                })
                ->addColumn('nama_pasien_formatted', function ($recap) {
                    return \Illuminate\Support\Str::limit($recap->nama_pasien, 20);
                })
                ->addColumn('jumlah_formatted', function ($recap) {
                    return 'Rp ' . number_format($recap->jumlah, 0, ',', '.');
                })
                ->addColumn('status_formatted', function ($recap) {
                    $class = $recap->status_bayar == 'Sudah' ? 'badge-success' : 'badge-warning';
                    return '<span class="badge ' . $class . '">' . e($recap->status_bayar) . '</span>';
                })
                ->rawColumns(['dokter_formatted', 'status_formatted'])
                ->make(true);
        }
        // Stats based on filter
        $total_dokter = (clone $query)->distinct('dokter')->count('dokter');
        $total_pasien = (clone $query)->count();
        $total_jumlah = (clone $query)->sum('jumlah');

        return view('medical-recap.index', compact('total_dokter', 'total_pasien', 'total_jumlah', 'request'));
    }

    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv',
        ]);

        Excel::import(new MedicalRecapImport, $request->file('file'));

        return redirect()->back()->with('success', 'Data berhasil diimport.');
    }

    public function exportPdf(Request $request)
    {
        $dokter = $request->dokter;
        $startDate = $request->start_date;
        $endDate = $request->end_date;

        $query = MedicalRecap::query();

        if ($dokter) {
            $query->where('dokter', $dokter);
        }

        if ($startDate && $endDate) {
            $query->whereBetween('tgl_perawatan', [$startDate, $endDate]);
        }

        $data = $query->orderBy('tgl_perawatan', 'asc')->get();
        $total = $data->sum('jumlah');

        $pdf = Pdf::loadView('medical-recap.pdf', [
            'data' => $data,
            'total' => $total,
            'dokter' => $dokter ?: 'Semua Dokter',
            'startDate' => $startDate,
            'endDate' => $endDate,
        ])->setPaper('a4', 'portrait');

        return $pdf->download('Laporan_Jasa_Medis_' . ($dokter ?: 'Semua') . '.pdf');
    }

    public function clear()
    {
        MedicalRecap::truncate();
        return redirect()->back()->with('success', 'Semua data telah dihapus.');
    }
}
