<?php

namespace App\Http\Controllers;

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

class SurveiController extends Controller
{
    public function form()
    {
        return view('survei.pertanyaan');
    }

    public function submit(Request $request)
    {
        // Validasi data pelapor dan pertanyaan survei
        $request->validate([
            'nama_pelapor' => 'required|string|max:100',
            'no_hp' => 'required|numeric|digits_between:10,15',
            'email' => 'nullable|email',
            'alamat' => 'nullable|string',
            'unsur_1' => 'required|in:1,2,3,4',
            'unsur_2' => 'required|in:1,2,3,4',
            'unsur_3' => 'required|in:1,2,3,4',
            'unsur_4' => 'required|in:1,2,3,4',
            'unsur_5' => 'required|in:1,2,3,4',
            'unsur_6' => 'required|in:1,2,3,4',
            'unsur_7' => 'required|in:1,2,3,4',
            'unsur_8' => 'required|in:1,2,3,4',
            'unsur_9' => 'required|in:1,2,3,4',
            'unsur_10' => 'required|in:1,2,3,4',
            'unsur_11' => 'required|in:1,2,3,4',
            'saran' => 'nullable|string|max:1000'
        ], [
            'nama_pelapor.required' => 'Nama pelapor wajib diisi',
            'no_hp.required' => 'Nomor HP wajib diisi',
            'no_hp.numeric' => 'Nomor HP harus berupa angka',
            'no_hp.digits_between' => 'Nomor HP harus 10-15 digit',
            'email.email' => 'Format email tidak valid',
            'unsur_1.required' => 'Pertanyaan Unsur 1 wajib dijawab',
            'unsur_2.required' => 'Pertanyaan Unsur 2 wajib dijawab',
            'unsur_3.required' => 'Pertanyaan Unsur 3 wajib dijawab',
            'unsur_4.required' => 'Pertanyaan Unsur 4 wajib dijawab',
            'unsur_5.required' => 'Pertanyaan Unsur 5 wajib dijawab',
            'unsur_6.required' => 'Pertanyaan Unsur 6 wajib dijawab',
            'unsur_7.required' => 'Pertanyaan Unsur 7 wajib dijawab',
            'unsur_8.required' => 'Pertanyaan Unsur 8 wajib dijawab',
            'unsur_9.required' => 'Pertanyaan Unsur 9 wajib dijawab',
            'unsur_10.required' => 'Pertanyaan Unsur 10 wajib dijawab',
            'unsur_11.required' => 'Pertanyaan Unsur 11 wajib dijawab',
        ]);

        // Simpan data responden dengan data pelapor
        $respondenId = DB::table('responden')->insertGetId([
            'nama_pelapor' => $request->nama_pelapor,
            'no_hp' => $request->no_hp,
            'email' => $request->email,
            'alamat' => $request->alamat,
            'tanggal_survei' => now()->format('Y-m-d'),
            'created_at' => now(),
            'updated_at' => now()
        ]);

        // Simpan jawaban survei
        for ($i = 1; $i <= 11; $i++) {
            DB::table('jawaban_survei')->insert([
                'responden_id' => $respondenId,
                'unsur_id' => $i,
                'nilai' => $request->input("unsur_{$i}"),
                'created_at' => now(),
                'updated_at' => now()
            ]);
        }

        // Update saran di tabel responden jika ada
        if ($request->saran) {
            DB::table('responden')->where('id', $respondenId)->update([
                'saran' => $request->saran,
                'updated_at' => now()
            ]);
        }

        return redirect()->route('survei.selesai');
    }

    public function selesai()
    {
        return view('survei.selesai');
    }

    public function hasil(Request $request)
    {
        $tahun = $request->get('tahun', date('Y'));
        $semester = $request->get('semester');
        $opd = $request->get('opd');

        // Query dasar untuk filter
        $query = DB::table('responden')
            ->whereYear('tanggal_survei', $tahun);

        // Filter semester (1-6 = semester 1, 7-12 = semester 2)
        if ($semester == 1) {
            $query->whereMonth('tanggal_survei', '>=', 1)
                  ->whereMonth('tanggal_survei', '<=', 6);
        } elseif ($semester == 2) {
            $query->whereMonth('tanggal_survei', '>=', 7)
                  ->whereMonth('tanggal_survei', '<=', 12);
        }

        $totalResponden = $query->count();

        // Daftar nama unsur
        $unsurData = [
            1 => 'Persyaratan',
            2 => 'Sistem, Mekanisme, dan Prosedur',
            3 => 'Waktu Penyelesaian',
            4 => 'Biaya / Tarif',
            5 => 'Produk Spesifikasi Jenis Pelayanan',
            6 => 'Kompetensi Pelaksana',
            7 => 'Perilaku Pelaksana',
            8 => 'Penanganan Pengaduan, Saran dan Masukan',
            9 => 'Sarana dan Prasarana',
            10 => 'Unsur 10',
            11 => 'Unsur 11'
        ];

        // Ambil data real dari database
        $hasilSurvei = [];
        $respondenIds = $query->pluck('id');

        for ($i = 1; $i <= 11; $i++) {
            $jawabanStats = DB::table('jawaban_survei')
                ->whereIn('responden_id', $respondenIds)
                ->where('unsur_id', $i)
                ->select(
                    DB::raw('COUNT(*) as total'),
                    DB::raw('SUM(nilai) as total_skor'),
                    DB::raw('AVG(nilai) as rata_rata')
                )
                ->first();

            $totalSkor = $jawabanStats->total_skor ?? 0;
            $rataRata = $jawabanStats->rata_rata ?? 0;

            $hasilSurvei[] = [
                'no' => $i,
                'jenis_survei' => $unsurData[$i],
                'total_skor' => $totalSkor,
                'indeks' => round($rataRata, 2),
                'keterangan' => $this->getKeterangan($rataRata)
            ];
        }

        // Hitung IKM (Total Skor / Jumlah Responden)
        // IKM dalam skala 11-44 (11 unsur × nilai 1-4)
        $totalSkorSemua = array_sum(array_column($hasilSurvei, 'total_skor'));
        $ikm = $totalResponden > 0 ? $totalSkorSemua / $totalResponden : 0;

        // Data untuk filter
        $tahunList = range(date('Y'), date('Y') - 5);
        $opdList = ['Sekretariat Kementerian', 'Deputi Bidang Pemuda', 'Deputi Bidang Olahraga'];

        return view('survei.hasil', compact(
            'hasilSurvei', 'totalResponden', 'tahun', 'semester', 'opd',
            'ikm', 'tahunList', 'opdList'
        ));
    }

    public function dataResponden(Request $request)
    {
        $tahun = $request->get('tahun', date('Y'));
        $semester = $request->get('semester');

        // Data dummy jenis kelamin
        $jenisKelamin = [
            ['no' => 1, 'jenis' => 'Laki-laki', 'responden' => 85, 'persentase' => 56.67],
            ['no' => 2, 'jenis' => 'Perempuan', 'responden' => 65, 'persentase' => 43.33],
            ['no' => '', 'jenis' => 'Total', 'responden' => 150, 'persentase' => 100.00]
        ];

        // Data dummy usia
        $usia = [
            ['no' => 1, 'range' => '≤ 24 tahun', 'responden' => 35, 'persentase' => 23.33],
            ['no' => 2, 'range' => '25 – 34 tahun', 'responden' => 55, 'persentase' => 36.67],
            ['no' => 3, 'range' => '35 – 44 tahun', 'responden' => 40, 'persentase' => 26.67],
            ['no' => 4, 'range' => '≥ 45 tahun', 'responden' => 20, 'persentase' => 13.33],
            ['no' => '', 'range' => 'Total', 'responden' => 150, 'persentase' => 100.00]
        ];

        $tahunList = [2024, 2023, 2022];

        return view('survei.data_responden', compact('jenisKelamin', 'usia', 'tahun', 'semester', 'tahunList'));
    }

    private function getKeterangan($nilai)
    {
        // Untuk skala total 11-44 (11 unsur × nilai 1-4)
        // Atau untuk rata-rata per unsur 1-4
        if ($nilai >= 38.83) return 'A (Sangat Baik)';  // >= 88.31% dari 44
        if ($nilai >= 33) return 'B (Baik)';            // >= 33
        if ($nilai >= 28.60) return 'C (Kurang Baik)';  // >= 65% dari 44
        return 'D (Tidak Baik)';
    }
}