<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

use App\Models\Teknisi;
use App\Models\Penugasan;
use App\Models\PenugasanItem;
use App\Models\Laporan;
use App\Models\TarifPekerjaan;

class DashboardController extends Controller
{
    public function index()
    {
        $now = Carbon::now();

        // ── STAT CARDS ──────────────────────────────────────
       // ── STAT CARDS ──
$totalTeknisi   = Teknisi::count();
$teknisiAktif   = Teknisi::where('status', 'aktif')->count(); // sesuaikan nanti kalau error
$totalPekerjaan = Penugasan::count();
$totalLaporan   = 0;
$penugasanAktif = Penugasan::where('status_pekerjaan', 'dalam_proses')->count(); // ✅

        // ── BAR CHART & DONUT ────────────────────────────────
        $chartData = PenugasanItem::select('jenis_pekerjaan', DB::raw('count(*) as total'))
            ->groupBy('jenis_pekerjaan')
            ->pluck('total', 'jenis_pekerjaan');

        $jenisMapping = [
            'sr' => 'Sambungan Rumah (SR)',
            'pengembangan_jaringan_pipa' => 'Pengembangan Pipa',
            'perbaikan_jaringan_pipa' => 'Perbaikan Pipa',
            'gali_urug' => 'Gali Urug',
            'pemasangan_gate_valve' => 'Pemas. Gate Valve',
            'pengangkatan' => 'Pengangkatan',
            'pengecatan_pipa_besi' => 'Pengecatan Pipa',
            'penyempurnaan_jaringan_pipa' => 'Penyempurnaan Pipa',
        ];

        $chartColors = ['#1d9e75', '#378add', '#e24b4a', '#ef9f27', '#7f77dd', '#a552cc', '#34d399', '#f472b6'];
        
        $chartLabels = [];
        $chartValues = [];
        $chartBgColors = [];
        
        $i = 0;
        foreach($jenisMapping as $key => $label) {
            $chartLabels[] = $label;
            $chartValues[] = $chartData->get($key, 0);
            $chartBgColors[] = $chartColors[$i % count($chartColors)];
            $i++;
        }

        // ── LINE CHART TEKNISI (MULTI-LINE PER BULAN) ──────────────────
        $months = [];
        $monthLabels = [];
        for ($i = 5; $i >= 0; $i--) {
            $date = Carbon::now()->subMonths($i);
            $months[] = $date->format('Y-m');
            $monthLabels[] = $date->translatedFormat('F'); // ex: Januari, Februari
        }

        $teknisiData = Penugasan::join('teknisis', 'penugasans.id_teknisi', '=', 'teknisis.id_teknisi')
            ->select('teknisis.nama', DB::raw('DATE_FORMAT(penugasans.created_at, "%Y-%m") as month_year'), DB::raw('count(penugasans.id_penugasan) as total'))
            ->where('penugasans.created_at', '>=', Carbon::now()->subMonths(5)->startOfMonth())
            ->groupBy('teknisis.id_teknisi', 'teknisis.nama', 'month_year')
            ->get();

        $teknisiDatasets = [];
        $lineColors = ['#378add', '#e24b4a', '#1d9e75', '#ef9f27', '#7f77dd', '#a552cc', '#f472b6', '#34d399'];
        $colorIdx = 0;

        foreach ($teknisiData->groupBy('nama') as $nama => $records) {
            $dataArray = [];
            foreach ($months as $m) {
                $record = $records->firstWhere('month_year', $m);
                $dataArray[] = $record ? $record->total : 0;
            }
            
            $teknisiDatasets[] = [
                'label' => $nama,
                'data' => $dataArray,
                'borderColor' => $lineColors[$colorIdx % count($lineColors)],
                'backgroundColor' => 'transparent',
                'borderWidth' => 2,
                'pointBackgroundColor' => '#fff',
                'pointBorderColor' => $lineColors[$colorIdx % count($lineColors)],
                'pointBorderWidth' => 2,
                'pointRadius' => 4,
                'tension' => 0.3
            ];
            $colorIdx++;
        }

        // ── TARIF PEKERJAAN ──────────────────────────────────
        $tarifPekerjaans = TarifPekerjaan::where('is_active', true)
            ->orderBy('jenis_pekerjaan')
            ->orderBy('dimensi_pipa')
            ->get();

        // ── KONTRAK — tidak ada, kirim collection kosong ─────
        $kontrakJatuhTempo = collect();

        return view('dashboard', compact(
            'totalTeknisi',
            'teknisiAktif',
            'totalPekerjaan',
            'totalLaporan',
            'penugasanAktif',
            'chartLabels',
            'chartValues',
            'chartBgColors',
            'monthLabels',
            'teknisiDatasets',
            'tarifPekerjaans',
            'kontrakJatuhTempo',
        ));
    }
}