<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Audit;
use App\Models\Tema;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Exports\LaporanExport;
use Maatwebsite\Excel\Facades\Excel;

class LaporanController extends Controller
{
    public function index(Request $request)
    {
        $temaList = Tema::orderBy('nama')->pluck('nama');
        $statusList = Audit::select('status')->whereNotNull('status')->distinct()->pluck('status');
        $bulanAuditList = DB::table('audit')
            ->selectRaw("DATE_FORMAT(tanggal_audit, '%Y-%m') as bulan")
            ->whereNotNull('tanggal_audit')
            ->distinct()
            ->pluck('bulan');

        $bulanVerifikasiList = DB::table('audit')
            ->selectRaw("DATE_FORMAT(tanggal_verifikasi, '%Y-%m') as bulan")
            ->whereNotNull('tanggal_verifikasi')
            ->distinct()
            ->pluck('bulan');

        $query = Audit::with('auditor', 'bagian', 'tema');

        // Filter Tema
        if ($request->filled('tema')) {
            $query->whereHas('tema', function ($q) use ($request) {
                $q->where('nama', $request->tema);
            });
        }

        // Filter Status
        if ($request->filled('status')) {
            if ($request->status === 'CloseSesudah') {
                $query->where('status', 'Close')
                      ->whereNotNull('foto_sesudah');
            } elseif ($request->status === 'CloseBelumFoto') {
                $query->where('status', 'Close')
                      ->whereNull('foto_sesudah');
            } else {
                $query->where('status', $request->status);
            }
        }

        // Filter Bulan Audit
        if ($request->filled('bulan_audit')) {
            $query->whereRaw("DATE_FORMAT(tanggal_audit, '%Y-%m') = ?", [$request->bulan_audit]);
        }

        // Filter Bulan Verifikasi
        if ($request->filled('bulan_verifikasi')) {
            $query->whereRaw("DATE_FORMAT(tanggal_verifikasi, '%Y-%m') = ?", [$request->bulan_verifikasi]);
        }

        $auditData = $query->get();

        // Data untuk chart
        $barData = $auditData->groupBy(function ($item) {
            return optional($item->bagian)->nama_bagian ?? 'Tidak Diketahui';
        })->map->count();

        $barLabels = $barData->keys()->toArray();
        $barCounts = $barData->values()->toArray();

        $pieLabels = $barLabels;
        $pieCounts = $barCounts;

        return view('admin.laporan', [
            'temaList' => $temaList,
            'statusList' => $statusList,
            'bulanAuditList' => $bulanAuditList,
            'bulanVerifikasiList' => $bulanVerifikasiList,
            'auditData' => $auditData,
            'barLabels' => $barLabels,
            'barCounts' => $barCounts,
            'pieLabels' => $pieLabels,
            'pieCounts' => $pieCounts,
        ]);
    }

    public function exportPdf(Request $request)
    {
        try {
            $query = Audit::with(['bagian','tema']);

            if ($request->filled('tema')) {
                $query->whereHas('tema', function($q) use ($request){
                    $q->where('nama',$request->tema);
                });
            }

            if ($request->filled('status')) {
                if ($request->status === 'CloseSesudah') {
                    $query->where('status','Close')
                          ->whereNotNull('foto_sesudah');
                } elseif ($request->status === 'CloseBelumFoto') {
                    $query->where('status','Close')
                          ->whereNull('foto_sesudah');
                } else {
                    $query->where('status',$request->status);
                }
            }

            if ($request->filled('bulan_audit')) {
                [$tahun,$bulan] = explode('-',$request->bulan_audit);
                $query->whereYear('tanggal_audit',$tahun)
                      ->whereMonth('tanggal_audit',$bulan);
            }

            if ($request->filled('bulan_verifikasi')) {
                [$tahun,$bulan] = explode('-',$request->bulan_verifikasi);
                $query->whereYear('tanggal_verifikasi',$tahun)
                      ->whereMonth('tanggal_verifikasi',$bulan);
            }

            $audits = $query->orderBy('tanggal_audit','asc')->get();

            $periodeAwal = $audits->min('tanggal_audit')
                ? Carbon::parse($audits->min('tanggal_audit'))->translatedFormat('d-m-Y')
                : '-';
            $periodeAkhir = $audits->max('tanggal_verifikasi')
                ? Carbon::parse($audits->max('tanggal_verifikasi'))->translatedFormat('d-m-Y')
                : '-';

            return Pdf::loadView('admin.exports.laporan-pdf',[
                'audits'       => $audits,
                'periodeAwal'  => $periodeAwal,
                'periodeAkhir' => $periodeAkhir,
            ])->setPaper('a4','landscape')
              ->download('laporan_audit.pdf');

        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
                'line'  => $e->getLine(),
                'file'  => $e->getFile(),
            ]);
        }
    }

    public function exportExcel(Request $request)
    {
        $filter = [
            'tema'        => $request->filled('tema') ? $request->tema : null,
            'status'      => $request->filled('status') ? $request->status : null,
            'start_date'  => $request->filled('bulan_audit') 
                                ? Carbon::createFromFormat('Y-m', $request->bulan_audit)->startOfMonth()->toDateString()
                                : null,
            'end_date'    => $request->filled('bulan_audit') 
                                ? Carbon::createFromFormat('Y-m', $request->bulan_audit)->endOfMonth()->toDateString()
                                : null,
            'verif_start' => $request->filled('bulan_verifikasi') 
                                ? Carbon::createFromFormat('Y-m', $request->bulan_verifikasi)->startOfMonth()->toDateString()
                                : null,
            'verif_end'   => $request->filled('bulan_verifikasi') 
                                ? Carbon::createFromFormat('Y-m', $request->bulan_verifikasi)->endOfMonth()->toDateString()
                                : null,
        ];

        return Excel::download(new LaporanExport($filter), 'laporan-audit.xlsx');
    }

}
