<?php

namespace App\Http\Controllers;

use App\Models\SKPTApplication;
use App\Models\Peninjauan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class PenerbitanSKPTController extends Controller
{
    public function index(Request $request)
    {
        $query = SKPTApplication::with(['dataPeninjauan', 'documents'])
        ->whereHas('dataPeninjauan', function($q) {
            $q->where('status', 'selesai');
        });

        // Filter berdasarkan tahun SKPT
        if ($request->filled('tahun_skpt')) {
            $query->whereYear('created_at', $request->tahun_skpt);
        }

        // Filter berdasarkan cari berdasarkan
        if ($request->filled('cari_berdasarkan') && $request->filled('search')) {
            switch ($request->cari_berdasarkan) {
                case 'no_registrasi':
                    $query->where('no_registrasi', 'LIKE', '%' . $request->search . '%');
                    break;
                case 'nama_pemohon':
                    $query->where('nama_pemohon', 'LIKE', '%' . $request->search . '%');
                    break;
            }
        }

        $applications = $query->orderBy('created_at', 'desc')->paginate(10)->withQueryString();

        // Data untuk filter
        $years = SKPTApplication::whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })
            ->selectRaw('YEAR(created_at) as year')
            ->distinct()
            ->orderBy('year', 'desc')
            ->pluck('year');

        return view('admin.penerbitan-skpt.index', compact('applications', 'years'));
    }

    public function show($id)
    {
        $application = SKPTApplication::with(['dataPeninjauan.dataKecamatan', 'dataPeninjauan.coordinates', 'documents', 'additionalDocuments'])
            ->whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })
            ->findOrFail($id);

        // If request is AJAX, return JSON for modal preview
        if (request()->ajax()) {
            return response()->json([
                'id' => $application->id,
                'no_registrasi' => $application->no_registrasi,
                'nama_pemohon' => $application->nama_pemohon,
                'nik' => $application->nik,
                'tempat_lahir' => $application->tempat_lahir,
                'tanggal_lahir' => $application->tanggal_lahir ? $application->tanggal_lahir->format('d-m-Y') : null,
                'pekerjaan' => $application->pekerjaan,
                'alamat_lengkap' => "RT {$application->alamat_rt} RW {$application->alamat_rw} Kode Pos {$application->alamat_kode_pos}",
                'letak_tanah' => $application->letak_tanah,
                'luas' => number_format($application->luas, 0, ',', '.') . ' m²',
                'peruntukan' => $application->peruntukan,
                'status_permohonan' => $application->status_permohonan,
                'created_at' => $application->created_at->format('d M Y'),
                'peninjauan' => $application->dataPeninjauan ? [
                    'ba_tanggal' => $application->dataPeninjauan->ba_tanggal ?
                                  $application->dataPeninjauan->ba_tanggal->format('d M Y') : null,
                    'nomor_ba_penelitian' => $application->dataPeninjauan->nomor_ba_penelitian,
                    'mengetahui_nama' => $application->dataPeninjauan->mengetahui_nama,
                    'mengetahui_nip' => $application->dataPeninjauan->mengetahui_nip,
                ] : null,
            ]);
        }

        return view('admin.penerbitan-skpt.show', compact('application'));
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate(['status' => 'required|in:SELESAI,BELUM SELESAI']);

        $application = SKPTApplication::findOrFail($id);
        $application->status_permohonan = $request->status;
        $application->save();

        return response()->json(['success' => true]);
    }

    public function printSkpt($id)
    {
        $application = SKPTApplication::with(['dataPeninjauan.dataKecamatan', 'dataPeninjauan.coordinates', 'dataPeninjauan.lastMapImage', 'documents'])
            ->whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })
            ->findOrFail($id);

        return view('admin.penerbitan-skpt.print', compact('application'));
    }

    // NEW METHODS FOR PREVIEW AND VERIFICATION

    public function preview($id)
    {
        // Get application data for preview - same as print but can be customized
        $application = SKPTApplication::with(['dataPeninjauan.dataKecamatan', 'dataPeninjauan.coordinates', 'dataPeninjauan.lastMapImage'])
            ->whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })
            ->findOrFail($id);

        // Return the same print view for preview
        return view('admin.penerbitan-skpt.print', compact('application'));
    }

    public function verifyDocument(Request $request, $id)
    {
        $request->validate([
            'verification_status' => 'required|in:approved,needs_revision',
            'verification_notes' => 'nullable|string|max:1000',
            'verification_date' => 'required|date',
        ]);

        try {
            DB::beginTransaction();

            $application = SKPTApplication::whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })->findOrFail($id);

            // Update verification data
            $application->update([
                'verification_status' => $request->verification_status,
                'verification_notes' => $request->verification_notes,
                'verification_date' => $request->verification_date,
                'verified_by' => auth()->user()->id ?? null,
                'verified_at' => now(),
            ]);

            // If approved, update related status
            if ($request->verification_status === 'approved') {
                $application->update([
                    'document_verified' => true,
                    'ready_for_print' => true,
                    'status_permohonan' => 'SELESAI'
                ]);
            }else{
                $application->update([
                    'document_verified' => true,
                    'ready_for_print' => true,
                    'status_permohonan' => 'BELUM SELESAI'
                ]);
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Verifikasi dokumen berhasil disimpan.',
                'data' => [
                    'verification_status' => $application->verification_status,
                    'verification_date' => $application->verification_date,
                    'verified_at' => $application->verified_at,
                ]
            ]);

        } catch (\Exception $e) {
            DB::rollback();

            return response()->json([
                'success' => false,
                'message' => 'Gagal menyimpan verifikasi: ' . $e->getMessage()
            ], 500);
        }
    }

    public function finalizeDocument(Request $request, $id)
    {
        try {
            DB::beginTransaction();

            $application = SKPTApplication::whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })->findOrFail($id);

            // Check if document is verified
            if ($application->verification_status !== 'approved') {
                return response()->json([
                    'success' => false,
                    'message' => 'Dokumen harus diverifikasi terlebih dahulu sebelum difinalisasi.'
                ], 400);
            }

            // Finalize the document
            $application->update([
                'document_finalized' => true,
                'finalized_by' => auth()->user()->id ?? null,
                'finalized_at' => now(),
                'ready_for_official_print' => true,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Dokumen berhasil difinalisasi dan siap untuk diterbitkan secara resmi.',
                'data' => [
                    'finalized_at' => $application->finalized_at,
                    'ready_for_official_print' => $application->ready_for_official_print,
                ]
            ]);

        } catch (\Exception $e) {
            DB::rollback();

            return response()->json([
                'success' => false,
                'message' => 'Gagal memfinalisasi dokumen: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getVerificationHistory($id)
    {
        $application = SKPTApplication::whereHas('dataPeninjauan', function($q) {
            $q->where('status', 'selesai');
        })->findOrFail($id);

        return response()->json([
            'verification_status' => $application->verification_status,
            'verification_notes' => $application->verification_notes,
            'verification_date' => $application->verification_date,
            'verified_by' => $application->verified_by,
            'verified_at' => $application->verified_at,
            'document_finalized' => $application->document_finalized ?? false,
            'finalized_at' => $application->finalized_at,
            'ready_for_official_print' => $application->ready_for_official_print ?? false,
        ]);
    }

    public function updateDocumentStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:draft,review,approved,rejected,finalized',
            'notes' => 'nullable|string|max:500',
        ]);

        try {
            $application = SKPTApplication::whereHas('dataPeninjauan', function($q) {
                $q->where('status', 'selesai');
            })->findOrFail($id);

            $application->update([
                'document_status' => $request->status,
                'status_notes' => $request->notes,
                'status_updated_by' => auth()->user()->id ?? null,
                'status_updated_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Status dokumen berhasil diperbarui.',
                'data' => [
                    'document_status' => $application->document_status,
                    'status_updated_at' => $application->status_updated_at,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal memperbarui status: ' . $e->getMessage()
            ], 500);
        }
    }
}
