<?php

namespace App\Http\Controllers;

use App\Models\Transaksi;
use Illuminate\Http\Request;

class LaporanController extends Controller
{
    public function index(Request $request)
    {
        $perPage = (int) $request->query('perpage', 15);

        $query = Transaksi::with('tiket.event');

        if ($search = $request->query('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('nama_pembeli', 'like', "%{$search}%")
                    ->orWhere('status', 'like', "%{$search}%")
                    ->orWhereHas('tiket.event', function ($qe) use ($search) {
                        $qe->where('nama_event', 'like', "%{$search}%");
                    });
            });
        }

        if ($status = $request->query('status')) {
            $query->where('status', $status);
        }

        if ($date = $request->query('date_filter')) {
            if ($date === 'today') {
                $query->whereDate('created_at', now()->toDateString());
            } elseif ($date === 'this_week') {
                $query->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()]);
            } elseif ($date === 'this_month') {
                $query->whereYear('created_at', now()->year)->whereMonth('created_at', now()->month);
            } elseif ($date === 'custom') {
                $from = $request->query('date_from');
                $to = $request->query('date_to');
                if ($from) $query->whereDate('created_at', '>=', $from);
                if ($to) $query->whereDate('created_at', '<=', $to);
            }
        }

        $totalPendapatan = $query->sum('total_harga');
        $totalTiket = $query->sum('jumlah');

        $transaksis = $query->latest()
            ->paginate($perPage)
            ->appends($request->except('page'));

        return view(
            'laporan.index',
            compact(
                'totalPendapatan',
                'totalTiket',
                'transaksis'
            )
        );
    }

    public function pdf()
    {
        $transaksis =
            Transaksi::with('tiket.event')
            ->get();

        $totalPendapatan =
            Transaksi::sum('total_harga');

        $totalTiket =
            Transaksi::sum('jumlah');

        $pdf =
            \Barryvdh\DomPDF\Facade\Pdf::loadView(
                'laporan.pdf',
                compact(
                    'transaksis',
                    'totalPendapatan',
                    'totalTiket'
                )
            );

        return $pdf->download(
            'laporan-penjualan.pdf'
        );
    }
}