<?php

namespace App\Http\Controllers;

use App\Models\Perusahaan;
use App\Models\JenisKegiatan;
use App\Http\Requests\PerusahaanRequest;
use App\Models\JenisDokIL;
use App\Models\Kabupaten;
use App\Models\Kecamatan;
use App\Models\Kelurahan;
use App\Models\Verifikator;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Illuminate\Support\Facades\Session;

class PerusahaanController extends Controller
{
    public function index()
    {
        try {
            $perusahaan = Perusahaan::with('jenisKegiatan', 'kelurahan.kecamatan.kabupaten', 'verifikator', 'jenisDokIL')->get();
            return Inertia::render('admin/perusahaan/index_perusahaan', [
               'perusahaan' => $perusahaan,
                'jenisKegiatan' => JenisKegiatan::all(),
                'jenisDokIL' => JenisDokIL::all(),
                'verifikator' => Verifikator::all(),
                'kabupaten' => Kabupaten::all(),
                'kecamatan' => Kecamatan::all(),
                'kelurahan' => Kelurahan::all(),
            ]);

        } catch (\Exception $e) {
            Log::error('Error fetching data: ' . $e->getMessage());
            return back()->with('error', 'Terjadi kesalahan saat memuat data.');
        }
    }

    // public function store(Request $request)
    // {
    //     $request->validate([
    //         'ILDokumen' => 'required|file|mimes:pdf|max:20480',
    //     ]);

    //     try {
    //         return DB::transaction(function () use ($request) {
    //             if ($request->hasFile('ILDokumen')) {
    //                 $file = $request->file('ILDokumen');
    //                 $fileName = time() . '_' . $file->getClientOriginalName();

    //                 if (!Storage::exists('public/files/il')) {
    //                     Storage::makeDirectory('public/files/il');
    //                 }

    //                 $path = $file->storeAs('files/il', $fileName, 'public');

    //                 $request->merge(['ILDokumen' => $path]);
    //             }

    //             $perusahaan = Perusahaan::create($request->all());

    //             return response()->json([
    //                 'message' => 'Perusahaan berhasil ditambahkan',
    //                 'data' => $perusahaan
    //             ]);
    //         });
    //     } catch (\Exception $e) {
    //         if (isset($path) && Storage::exists($path)) {
    //             Storage::delete($path);
    //         }

    //         return response()->json([
    //             'message' => 'Error: ' . $e->getMessage()
    //         ], 500);
    //     }
    // }

    public function store(Request $request)
{
    $request->validate([
        'NomorInduk' => 'required|string|unique:Perusahaan',
        'NamaPerusahaan' => 'required|string',
        'JenisKegiatanId' => 'required|string',
        'VerifikatorId' => 'required|string',
        'KelurahanId' => 'required|string',
        'Email' => 'required|email',
    ]);

    try {
        DB::beginTransaction();

        $data = $request->all();

        if ($request->hasFile('ILDokumen')) {
            $file = $request->file('ILDokumen');

            if (!$file->isValid()) {
                throw new \Exception('Invalid PDF file');
            }

            $fileName = time() . '_' . $file->getClientOriginalName();
            $path = $file->storeAs('files/il', $fileName, 'public');

            if ($path === false) {
                throw new \Exception('Failed to store PDF file');
            }

            $data['ILDokumen'] = $path;
        }

        // Convert boolean string to actual boolean
        $data['IsPublish'] = filter_var($request->input('IsPublish'), FILTER_VALIDATE_BOOLEAN);
        $data['ReportLocked'] = filter_var($request->input('ReportLocked'), FILTER_VALIDATE_BOOLEAN);

        $perusahaan = Perusahaan::create($data);

        DB::commit();

        return redirect()
        ->route('admin.perusahaan.index')
        ->with('success', 'Perusahaan berhasil ditambahkan');

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

        if (isset($path) && Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }

        Log::error('Error creating perusahaan: ' . $e->getMessage());

        return response()->json([
            'message' => 'Error: ' . $e->getMessage()
        ], 500);
    }
}

    public function show(Perusahaan $perusahaan): JsonResponse
    {
        $perusahaan->load([
            'JenisKegiatan',
            'Kelurahan',
            'JenisDokIL',
            'Verifikator',
            'Kawasan'
        ]);

        return response()->json([
            'status' => 'success',
            'data' => $perusahaan
        ]);
    }

    public function update(PerusahaanRequest $request, Perusahaan $perusahaan): JsonResponse
    {
        $perusahaan->update($request->validated());

        return response()->json([
            'status' => 'success',
            'message' => 'Data perusahaan berhasil diperbarui',
            'data' => $perusahaan
        ]);
    }

    public function destroy(Perusahaan $perusahaan): JsonResponse
    {
        $perusahaan->delete();

        return response()->json([
            'status' => 'success',
            'message' => 'Data perusahaan berhasil dihapus'
        ]);
    }
}
