<?php

namespace App\Http\Controllers\Api;

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

class AdminCustomerTypeController extends Controller
{
    public function index()
    {
        try {
            // Semua pengguna (termasuk admin cabang) diizinkan melihat daftar Tipe Outlet (Read-Only)
            $types = CustomerType::orderBy('name', 'asc')->get();
            return response()->json([
                'success' => true,
                'data' => $types
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat (Enterprise Master Data)
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah Master Tipe Outlet.'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255|unique:customer_types,name'
        ]);

        try {
            $type = CustomerType::create([
                'name' => strtoupper($request->name)
            ]);
            return response()->json(['success' => true, 'message' => 'Tipe Outlet berhasil ditambahkan', 'data' => $type], 201);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah Master Tipe Outlet.'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255|unique:customer_types,name,' . $id
        ]);

        try {
            $type = CustomerType::findOrFail($id);
            $type->update([
                'name' => strtoupper($request->name)
            ]);
            return response()->json(['success' => true, 'message' => 'Tipe Outlet berhasil diperbarui', 'data' => $type], 200);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function destroy(Request $request, $id)
    {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus Master Tipe Outlet.'
            ], 403);
        }

        try {
            $type = CustomerType::findOrFail($id);
            
            // Cek apakah tipe ini sedang dipakai pelanggan
            if ($type->customers()->count() > 0) {
                return response()->json(['success' => false, 'message' => 'Gagal dihapus: Tipe ini sedang digunakan oleh data Pelanggan.'], 400);
            }

            $type->delete();
            return response()->json(['success' => true, 'message' => 'Tipe Outlet berhasil dihapus'], 200);
            
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Lapis kedua untuk menangkap error constraint jika di masa depan ada relasi lain
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal dihapus: Tipe Outlet ini masih memiliki keterikatan relasi aktif di dalam database sistem.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}