<?php

namespace App\Http\Controllers\Admin;

use App\Exports\TicketsExport;
use App\Http\Controllers\Controller;
use App\Models\ServiceTicket;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ReportController extends Controller
{
    // ── Halaman laporan ───────────────────────────────

    public function index(Request $request)
    {
        $year   = (int) ($request->query('year',  now()->year));
        $month  = (int) ($request->query('month', 0));   // 0 = semua bulan

        // ── Statistik per bulan dalam setahun (bar chart) ──
        $monthlyRaw = ServiceTicket::selectRaw(
            'MONTH(created_at) AS m,
             COUNT(*) AS total,
             SUM(status = "Picked Up") AS selesai,
             SUM(status = "Cancelled") AS batal'
        )
        ->whereYear('created_at', $year)
        ->groupBy('m')
        ->orderBy('m')
        ->get()
        ->keyBy('m');

        // Normalisasi ke array 12 bulan
        $months   = [];
        $monthly  = [];
        for ($i = 1; $i <= 12; $i++) {
            $months[]  = Carbon::create($year, $i, 1)->locale('id')->monthName;
            $row       = $monthlyRaw->get($i);
            $monthly[] = [
                'total'   => (int) ($row?->total   ?? 0),
                'selesai' => (int) ($row?->selesai  ?? 0),
                'batal'   => (int) ($row?->batal    ?? 0),
            ];
        }

        // ── Ringkasan kartu KPI ──────────────────────────────
        $baseQuery = ServiceTicket::whereYear('created_at', $year);
        if ($month > 0) {
            $baseQuery->whereMonth('created_at', $month);
        }

        $kpi = (clone $baseQuery)->selectRaw(
            'COUNT(*) AS total,
             SUM(status = "Picked Up") AS selesai,
             SUM(status = "Cancelled") AS batal,
               SUM(status IN ("Pending","Checking","Repairing","Ready")) AS aktif'
        )->first();

        // ── Statistik per jenis perangkat ────────────────────
        $byDevice = (clone $baseQuery)
            ->selectRaw('device_type, COUNT(*) AS total')
            ->groupBy('device_type')
            ->orderByDesc('total')
            ->get();

        // ── Tabel detail (paginasi 30 per halaman) ───────────
        $tableQuery = ServiceTicket::with('customer')
            ->whereYear('created_at', $year)
            ->orderByDesc('created_at');

        if ($month > 0) {
            $tableQuery->whereMonth('created_at', $month);
        }

        $tickets = $tableQuery->paginate(30)->withQueryString();

        // ── Daftar tahun tersedia (dari data) ────────────────
        $availableYears = ServiceTicket::selectRaw('YEAR(created_at) AS y')
            ->groupBy('y')
            ->orderByDesc('y')
            ->pluck('y');

        if ($availableYears->isEmpty()) {
            $availableYears = collect([now()->year]);
        }

        return view('admin.reports.index', compact(
            'year', 'month', 'months', 'monthly', 'kpi',
            'byDevice', 'tickets', 'availableYears'
        ));
    }

    // ── Export Excel ──────────────────────────────────

    public function export(Request $request)
    {
        $year   = (int)    ($request->query('year',   now()->year));
        $month  = (int)    ($request->query('month',  0));
        $status = (string) ($request->query('status', ''));

        $filename = 'laporan-servis-' . $year
            . ($month  ? '-' . str_pad($month, 2, '0', STR_PAD_LEFT) : '')
            . ($status ? '-' . \Str::slug($status) : '')
            . '.xlsx';

        return Excel::download(
            new TicketsExport($year, $month ?: null, $status ?: null),
            $filename
        );
    }
}
