<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\InformasiKegiatan;
use App\Models\SaranTanggapan;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class LayananController extends Controller
{
    /**
     * Get all activities data for layanan page
     */
    public function getLayananData(): JsonResponse
    {
        try {
            $activities = InformasiKegiatan::active()
                ->currentPeriod()
                ->orderBy('TanggalMulaiPeriode', 'desc')
                ->get();

            $groupedData = [];

            foreach ($activities as $activity) {
                $docType = strtolower(str_replace(['-', ' '], ['', ''], $activity->JenisDokumen));

                if (!isset($groupedData[$docType])) {
                    $groupedData[$docType] = [];
                }

                $groupedData[$docType][] = [
                    'id' => $activity->KegiatanID,
                    'title' => $activity->NamaKegiatan,
                    'description' => $activity->DampakPotensial,
                    'link' => '#',
                    'periode' => $activity->periode,
                    'no_registrasi' => $activity->NoRegistrasi,
                    'jenis_dokumen' => $activity->JenisDokumen,
                    'bidang_usaha' => $activity->BidangUsaha,
                    'skala_besaran' => $activity->SkalaBesaran,
                    'lokasi_kegiatan' => $activity->LokasiKegiatan,
                    'kewenangan' => $activity->Kewenangan,
                    'pemrakarsa' => $activity->Pemrakarsa,
                    'provinsi_kota' => $activity->ProvinsiKota,
                    'deskripsi_kegiatan' => $activity->DeskripsiKegiatan,
                    'dampak_potensial' => $activity->DampakPotensial,
                    'deskripsi_lokasi' => $activity->DeskripsiLokasi,
                    'latitude' => $activity->Latitude,
                    'longitude' => $activity->Longitude
                ];
            }

            // Add audit data (static for now)
            $groupedData['audit'] = [
                [
                    'no' => 1,
                    'company' => 'PT PETROKIMIA GRESIK',
                    'title' => 'PENGUMUMAN AUDIT LINGKUNGAN HIDUP WAJIB BERKALA INDUSTRI PETROKIMIA',
                    'description' => 'PT Petrokimia Gresik merupakan Kegiatan pada sektor Industri Petrokimia : Industri Pupuk dan Bahan Kimia (Amonia, Pupuk, Asam Sulfat, Asam Fosfat, dan Asam Klorida)...',
                    'link' => '#'
                ]
            ];

            $response = [
                'header' => [
                    'title' => 'Daftar Pengumuman & Informasi',
                    'subtitle' => 'Daftar Pengumuman dan Informasi terkait kegiatan yang mengajukan izin lingkungan'
                ],
                'tabs' => [
                    ['id' => 'amdal', 'label' => 'AMDAL'],
                    ['id' => 'addendum', 'label' => 'Addendum'],
                    ['id' => 'uklupl', 'label' => 'UKL - UPL'],
                    ['id' => 'audit', 'label' => 'AUDIT']
                ],
                'contents' => $groupedData
            ];

            return response()->json($response);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to fetch layanan data',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get specific activity information
     */
    public function getActivityInfo($id): JsonResponse
    {
        try {
            $activity = InformasiKegiatan::findOrFail($id);

            $data = [
                'no_registrasi' => $activity->NoRegistrasi,
                'jenis_dokumen' => $activity->JenisDokumen,
                'nama_kegiatan' => $activity->NamaKegiatan,
                'bidang_usaha' => $activity->BidangUsaha,
                'skala_besaran' => $activity->SkalaBesaran,
                'lokasi_kegiatan' => $activity->LokasiKegiatan,
                'kewenangan' => $activity->Kewenangan,
                'pemrakarsa' => $activity->Pemrakarsa,
                'provinsi_kota' => $activity->ProvinsiKota,
                'deskripsi_kegiatan' => $activity->DeskripsiKegiatan,
                'dampak_potensial' => $activity->DampakPotensial,
                'deskripsi_lokasi' => $activity->DeskripsiLokasi,
                'latitude' => $activity->Latitude,
                'longitude' => $activity->Longitude,
                'periode' => $activity->periode,
                'is_active' => $activity->isActiveFeedbackPeriod()
            ];

            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Activity not found',
                'message' => $e->getMessage()
            ], 404);
        }
    }

    /**
     * Submit feedback for an activity
     */
    public function submitFeedback(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'kegiatan_id' => 'required|exists:InformasiKegiatan,KegiatanID',
                'nama' => 'required|string|max:100',
                'peran' => 'required|in:masyarakat,lsm,akademisi,pemerintah',
                'nik' => 'required|string|size:16',
                'no_telepon' => 'required|string|max:20',
                'email' => 'required|email|max:100',
                'gender' => 'required|in:laki-laki,perempuan',
                'kondisi_lingkungan' => 'required|string',
                'nilai_lokal' => 'required|string',
                'kekhawatiran' => 'required|string',
                'harapan' => 'required|string',
                'tingkat_kekhawatiran' => 'required|integer|min:1|max:5',
                'foto_selfie' => 'nullable|image|mimes:jpg,jpeg,png|max:1024'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'error' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Check if activity is still accepting feedback
            $activity = InformasiKegiatan::findOrFail($request->kegiatan_id);
            if (!$activity->isActiveFeedbackPeriod()) {
                return response()->json([
                    'error' => 'Periode pengajuan tanggapan untuk kegiatan ini sudah berakhir'
                ], 400);
            }

            // Handle photo upload
            $photoPath = null;
            if ($request->hasFile('foto_selfie')) {
                $photo = $request->file('foto_selfie');
                $fileName = time() . '_' . uniqid() . '.' . $photo->getClientOriginalExtension();
                $photoPath = $photo->storeAs('feedback-photos', $fileName, 'public');
            }

            // Create feedback record
            $feedback = SaranTanggapan::create([
                'KegiatanID' => $request->kegiatan_id,
                'Nama' => $request->nama,
                'Peran' => $request->peran,
                'NIK' => $request->nik,
                'NoTelepon' => $request->no_telepon,
                'Email' => $request->email,
                'Gender' => $request->gender,
                'KondisiLingkungan' => $request->kondisi_lingkungan,
                'NilaiLokal' => $request->nilai_lokal,
                'Kekhawatiran' => $request->kekhawatiran,
                'Harapan' => $request->harapan,
                'TingkatKekhawatiran' => $request->tingkat_kekhawatiran,
                'FotoSelfie' => $photoPath,
                'TanggalDiajukan' => now()
            ]);

            return response()->json([
                'message' => 'Tanggapan berhasil dikirim dan akan diproses oleh admin',
                'tanggapan_id' => $feedback->TanggapanID
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to submit feedback',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get feedback statistics for an activity
     */
    public function getFeedbackStats($id): JsonResponse
    {
        try {
            $activity = InformasiKegiatan::findOrFail($id);

            $stats = [
                'total_feedback' => $activity->saranTanggapan()->count(),
                'approved_feedback' => $activity->saranTanggapanApproved()->count(),
                'pending_feedback' => $activity->saranTanggapan()->pending()->count(),
                'by_role' => [
                    'masyarakat' => $activity->saranTanggapanApproved()->byRole('masyarakat')->count(),
                    'lsm' => $activity->saranTanggapanApproved()->byRole('lsm')->count(),
                    'akademisi' => $activity->saranTanggapanApproved()->byRole('akademisi')->count(),
                    'pemerintah' => $activity->saranTanggapanApproved()->byRole('pemerintah')->count(),
                ],
                'average_rating' => $activity->saranTanggapanApproved()->avg('TingkatKekhawatiran')
            ];

            return response()->json($stats);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Activity not found',
                'message' => $e->getMessage()
            ], 404);
        }
    }
}
