<?php

namespace App\Http\Controllers;

use App\Models\PengajuanSurat;
use App\Models\JenisSurat;
use App\Traits\FormProtection;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;

class PengajuanSuratController extends Controller
{
    use FormProtection;

    public function create()
    {
        $categories = JenisSurat::pluck('nama')->toArray();
        $formToken = $this->generateFormToken();

        return view('pages.pengaduan.pengajuan_surat', compact('categories', 'formToken'));
    }

    public function store(Request $request)
    {
        $this->checkHoneypot($request);
        $this->validateFormToken($request);
        $this->checkReferrer($request, 'pengajuan-surat.create');

        $validatedData = $request->validate([
            'nama_lengkap'   => 'required|string|max:255',
            'nik'            => 'required|digits:16',
            'email'          => 'nullable|email|max:255',
            'telepon'        => 'required|string|max:20',
            'kategori'       => 'required|string|exists:jenis_surats,nama',
            'isi_pengaduan'  => 'required|string|min:10',
            'lampiran'       => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',
        ], [
            'nama_lengkap.required' => 'Nama lengkap harus diisi',
            'nik.required' => 'NIK harus diisi',
            'nik.digits' => 'NIK harus 16 digit',
            'email.email' => 'Format email tidak valid',
            'telepon.required' => 'Nomor telepon harus diisi',
            'kategori.required' => 'Jenis surat harus dipilih',
            'kategori.exists' => 'Jenis surat tidak valid',
            'isi_pengaduan.required' => 'Keterangan harus diisi',
            'isi_pengaduan.min' => 'Keterangan minimal 10 karakter',
            'lampiran.mimes' => 'Lampiran harus berformat jpg, jpeg, png, atau pdf',
            'lampiran.max' => 'Ukuran lampiran maksimal 2MB',
        ]);

        DB::beginTransaction();

        try {
            do {
                $nomorTiket = 'SRT-' . strtoupper(Str::random(8));
            } while (PengajuanSurat::where('nomor_tiket', $nomorTiket)->exists());

            $path = null;
            if ($request->hasFile('lampiran')) {
                $file = $request->file('lampiran');
                if ($file->isValid()) {
                    $fileName = $nomorTiket . '_' . time() . '.' . $file->getClientOriginalExtension();
                    $fileContent = file_get_contents($file->getRealPath());
                    $encryptedContent = Crypt::encrypt($fileContent);
                    $path = 'lampiran_pengaduan/' . $fileName;
                    Storage::disk('local')->put($path, $encryptedContent);
                    Log::info('File uploaded and encrypted successfully: ' . $path);
                }
            }

            $pengajuan = PengajuanSurat::create([
                'nama_lengkap'  => $validatedData['nama_lengkap'],
                'nik'           => $validatedData['nik'],
                'email'         => $validatedData['email'] ?? null,
                'telepon'       => $validatedData['telepon'],
                'jenis_surat'   => $validatedData['kategori'],
                'keterangan'    => $validatedData['isi_pengaduan'],
                'lampiran'      => $path,
                'nomor_tiket'   => $nomorTiket,
                'status'        => 'Pending',
            ]);

            DB::commit();

            Log::info('Pengajuan surat berhasil dibuat', [
                'id' => $pengajuan->id,
                'nomor_tiket' => $nomorTiket,
                'nama' => $validatedData['nama_lengkap']
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Pengajuan surat berhasil dikirim!',
                'ticket_number' => $nomorTiket,
                'data' => [
                    'id' => $pengajuan->id,
                    'nama' => $pengajuan->nama_lengkap,
                    'kategori' => $pengajuan->jenis_surat,
                    'created_at' => $pengajuan->created_at->format('d/m/Y H:i')
                ]
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Validasi gagal',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Gagal menyimpan pengajuan surat: ' . $e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan pada server. Silakan coba beberapa saat lagi.',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
