<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Instansi;
use App\Models\InternshipBookingParticipant;
use App\Models\MasterData;

class LandingController extends Controller
{
    /**
     * Tampilkan landing page dengan statistik dan daftar instansi
     */
    public function index()
    {
        $instansis = Instansi::with('bidangs')->get();
        
        $statusActiveId = MasterData::idFor(MasterData::BOOKING_STATUS, 'active');
        $statusAcceptedId = MasterData::idFor(MasterData::BOOKING_STATUS, 'accepted');

        // Kalkulasi statistik untuk ditampilkan di landing page
        foreach ($instansis as $instansi) {
            $occupiedSlots = InternshipBookingParticipant::whereHas('booking', function ($q) use ($instansi, $statusActiveId, $statusAcceptedId) {
                $q->where('instansi_id', $instansi->id)
                  ->whereIn('status_id', [$statusActiveId, $statusAcceptedId])
                  ->where(function ($subQ) {
                      $subQ->where('expires_at', '>', now())
                           ->orWhereNull('expires_at');
                  });
            })->count();

            $instansi->slot_tersedia = max(0, $instansi->kuota - $occupiedSlots);
            $instansi->peserta_aktif = $occupiedSlots; // Sederhananya, tapi idealnya dibedakan antara active (booking) dan accepted (resmi)
        }

        $totalPendaftar = InternshipBookingParticipant::count(); // Sederhana
        $totalDiterima = InternshipBookingParticipant::whereHas('booking', function($q) use ($statusAcceptedId) {
            $q->where('status_id', $statusAcceptedId);
        })->count();

        // Statistik 7 Layanan Publik untuk Grafik
        $services = [
            'Penelitian (Perguruan Tinggi)',
            'Penelitian (Instansi / Lembaga Lainnya)',
            'KKL / PKL / Magang (Mahasiswa)',
            'KKN Mahasiswa',
            'KKL / PKL / Magang (Siswa Sekolah)',
            'Pelaksanaan Kegiatan',
            'Perpanjangan Izin Rekomendasi'
        ];

        $baselines = [
            'Penelitian (Perguruan Tinggi)' => [
                'registered' => 120,
                'accepted' => 45,
                'weekly' => [2, 4, 1, 3, 5, 2, 3]
            ],
            'Penelitian (Instansi / Lembaga Lainnya)' => [
                'registered' => 85,
                'accepted' => 30,
                'weekly' => [1, 2, 0, 3, 1, 2, 1]
            ],
            'KKL / PKL / Magang (Mahasiswa)' => [
                'registered' => 450,
                'accepted' => 180,
                'weekly' => [8, 12, 15, 10, 14, 6, 12]
            ],
            'KKN Mahasiswa' => [
                'registered' => 320,
                'accepted' => 120,
                'weekly' => [5, 8, 10, 7, 9, 3, 8]
            ],
            'KKL / PKL / Magang (Siswa Sekolah)' => [
                'registered' => 280,
                'accepted' => 95,
                'weekly' => [4, 6, 8, 5, 7, 2, 5]
            ],
            'Pelaksanaan Kegiatan' => [
                'registered' => 95,
                'accepted' => 40,
                'weekly' => [2, 1, 3, 2, 4, 1, 2]
            ],
            'Perpanjangan Izin Rekomendasi' => [
                'registered' => 60,
                'accepted' => 25,
                'weekly' => [1, 2, 1, 3, 2, 0, 1]
            ],
        ];

        $chartData = [];
        $pastDates = [];
        $pastDayNames = [];
        $dayMap = [
            'Mon' => 'Sen',
            'Tue' => 'Sel',
            'Wed' => 'Rab',
            'Thu' => 'Kam',
            'Fri' => 'Jum',
            'Sat' => 'Sab',
            'Sun' => 'Min'
        ];

        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i);
            $pastDates[] = $date->toDateString();
            $pastDayNames[] = $dayMap[$date->format('D')] ?? $date->format('D');
        }

        foreach ($services as $service) {
            $dbRegistered = \App\Models\LayananPublik::where('jenis_layanan', $service)->count();
            $dbAccepted = \App\Models\LayananPublik::where('jenis_layanan', $service)->where('status', 'approved')->count();
            
            $base = $baselines[$service];
            
            $weeklyCounts = [];
            foreach ($pastDates as $idx => $dateString) {
                $dbDayCount = \App\Models\LayananPublik::where('jenis_layanan', $service)
                    ->whereDate('created_at', $dateString)
                    ->count();
                $weeklyCounts[] = $base['weekly'][$idx] + $dbDayCount;
            }
            
            $chartData[$service] = [
                'registered' => $base['registered'] + $dbRegistered,
                'accepted' => $base['accepted'] + $dbAccepted,
                'today' => end($weeklyCounts),
                'weekly_series' => $weeklyCounts,
            ];
        }

        return view('landing.index', compact('instansis', 'totalPendaftar', 'totalDiterima', 'chartData', 'pastDayNames'));
    }

    public function instansi()
    {
        return view('landing.instansi');
    }

    public function instansiDetail()
    {
        return view('landing.instansi_detail');
    }

    public function peserta()
    {
        return view('landing.peserta');
    }

    // Forms
    public function formPerpanjangan() { return view('landing.forms.perpanjangan'); }
    public function formPenelitianPt() { return view('landing.forms.penelitian_pt'); }
    public function formPenelitianInstansi() { return view('landing.forms.penelitian_instansi'); }
    public function formKklSiswa() { return view('landing.forms.kkl_siswa'); }
    public function formKklMahasiswa() { return view('landing.forms.kkl_mahasiswa'); }
    public function formKkn() { return view('landing.forms.kkn_mahasiswa'); }
    public function formPelaksanaanKegiatan() { return view('landing.forms.pelaksanaan_kegiatan'); }

    public function showProfile()
    {
        $user = auth()->user();
        return view('landing.profile', compact('user'));
    }

    public function updateProfile(Request $request)
    {
        $user = auth()->user();
        
        $data = $request->validate([
            'nama' => 'required|string|max:100',
            'email' => 'required|email|max:100|unique:md_user,email,' . $user->id,
            'nik' => 'required|string|max:16|unique:md_user,nik,' . $user->id,
            'nim' => 'required|string|max:30',
            'tempat_lahir' => 'required|string|max:100',
            'tanggal_lahir' => 'required|date',
            'program_studi' => 'required|string|max:150',
            'asal_instansi' => 'required|string|max:255',
            'no_hp' => 'required|string|max:30',
            'alamat' => 'required|string',
            'password' => 'nullable|string|min:6|confirmed',
        ], [
            'nama.required' => 'Nama lengkap wajib diisi.',
            'email.required' => 'Email wajib diisi.',
            'email.email' => 'Format email tidak valid.',
            'email.unique' => 'Email sudah terdaftar.',
            'nik.required' => 'NIK wajib diisi.',
            'nik.unique' => 'NIK sudah digunakan.',
            'nim.required' => 'NIM / NIS wajib diisi.',
            'tempat_lahir.required' => 'Tempat lahir wajib diisi.',
            'tanggal_lahir.required' => 'Tanggal lahir wajib diisi.',
            'program_studi.required' => 'Program studi wajib diisi.',
            'asal_instansi.required' => 'Asal instansi pendidikan wajib diisi.',
            'no_hp.required' => 'Nomor WhatsApp wajib diisi.',
            'alamat.required' => 'Alamat lengkap wajib diisi.',
            'password.min' => 'Password minimal 6 karakter.',
            'password.confirmed' => 'Konfirmasi password tidak sama.',
        ]);

        $updateData = [
            'nama' => $data['nama'],
            'email' => $data['email'],
            'nik' => $data['nik'],
            'nim' => $data['nim'],
            'tempat_lahir' => $data['tempat_lahir'],
            'tanggal_lahir' => $data['tanggal_lahir'],
            'program_studi' => $data['program_studi'],
            'asal_instansi' => $data['asal_instansi'],
            'no_hp' => $data['no_hp'],
            'alamat' => $data['alamat'],
        ];

        if (!empty($data['password'])) {
            $updateData['password'] = $data['password'];
        }

        $user->update($updateData);

        return redirect()->back()->with('success_swal', 'Profil berhasil diperbarui.');
    }
}
