<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Province;
use App\Models\City;
use App\Models\District;
use Illuminate\Database\QueryException; // PENAMBAHAN: Standar ERP untuk menangkap error constraint database

class AdminRegionController extends Controller
{
    // === PROVINSI ===
    public function storeProvince(Request $request) {
        $user = $request->user();
        
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Master Data Geografis)
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah data Provinsi.'
            ], 403);
        }

        $request->validate(['name' => 'required|string|unique:provinces,name']);
        $data = Province::create(['name' => strtoupper($request->name)]);
        return response()->json(['success' => true, 'data' => $data]);
    }

    // PENAMBAHAN: Injeksi Request untuk membaca sesi user yang login
    public function deleteProvince(Request $request, $id) {
        $user = $request->user();
        
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus data Provinsi.'
            ], 403);
        }

        try {
            Province::findOrFail($id)->delete();
            return response()->json(['success' => true]);
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap error jika provinsi masih terhubung dengan data Kota/Customer
            if ($e->getCode() == "23000") {
                return response()->json(['success' => false, 'message' => 'Gagal menghapus: Data provinsi ini sedang digunakan oleh data Kota atau Pelanggan di sistem.'], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // === KOTA ===
    public function storeCity(Request $request) {
        $user = $request->user();
        
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah data Kota.'
            ], 403);
        }

        $request->validate([
            'province_id' => 'required|exists:provinces,id',
            'name' => 'required|string'
        ]);
        
        $data = City::create([
            'province_id' => $request->province_id,
            'name' => strtoupper($request->name)
        ]);
        
        return response()->json(['success' => true, 'data' => $data]);
    }

    public function deleteCity(Request $request, $id) {
        $user = $request->user();
        
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus data Kota.'
            ], 403);
        }

        try {
            City::findOrFail($id)->delete();
            return response()->json(['success' => true]);
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap error jika kota masih terhubung
            if ($e->getCode() == "23000") {
                return response()->json(['success' => false, 'message' => 'Gagal menghapus: Data kota ini sedang digunakan oleh data Kecamatan atau Pelanggan.'], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // === KECAMATAN ===
    public function storeDistrict(Request $request) {
        $user = $request->user();
        
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah data Kecamatan.'
            ], 403);
        }

        $request->validate([
            'city_id' => 'required|exists:cities,id',
            'name' => 'required|string'
        ]);
        
        $data = District::create([
            'city_id' => $request->city_id,
            'name' => strtoupper($request->name)
        ]);
        
        return response()->json(['success' => true, 'data' => $data]);
    }

    public function deleteDistrict(Request $request, $id) {
        $user = $request->user();
        
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus data Kecamatan.'
            ], 403);
        }

        try {
            District::findOrFail($id)->delete();
            return response()->json(['success' => true]);
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap error jika kecamatan masih terhubung dengan Pelanggan
            if ($e->getCode() == "23000") {
                return response()->json(['success' => false, 'message' => 'Gagal menghapus: Data kecamatan ini sedang digunakan oleh Master Pelanggan.'], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}