<?php

namespace App\Http\Controllers\Api;

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

class AdminSupplierController extends Controller
{
    public function index()
    {
        try {
            // Semua role (termasuk admin cabang) berhak melihat daftar supplier untuk keperluan input Pembelian (PO)
            $suppliers = Supplier::orderBy('name', 'asc')->get();
            return response()->json(['success' => true, 'data' => $suppliers], 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 Data Supplier.'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:20',
        ]);

        try {
        $supplier = Supplier::create([
            'name'              => strtoupper($request->name),
            'contact_person'    => $request->contact_person,
            'phone'             => $request->phone,
            'email'             => $request->email,
            'address'           => $request->address,
            'is_pkp'            => $request->is_pkp ? 1 : 0,
            'npwp'              => $request->npwp,
            'bank_account_info' => $request->bank_account_info,
            'term_of_payment'   => $request->term_of_payment ?? 0,
            // LOGIKA PENTING: Jika 'all' atau kosong, simpan sebagai NULL (Global)
            'branch_id'         => ($request->branch_id == 'all' || !$request->branch_id) ? null : $request->branch_id,
        ]);
        return response()->json(['success' => true, 'message' => 'Supplier berhasil disimpan', 'data' => $supplier], 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 Data Supplier.'
            ], 403);
        }

        $supplier = Supplier::find($id);
    if (!$supplier) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);

    try {
        $supplier->update([
            'name'              => strtoupper($request->name),
            'contact_person'    => $request->contact_person, // Tambahkan ini
            'phone'             => $request->phone,
            'email'             => $request->email,
            'address'           => $request->address,
            'is_pkp'            => $request->is_pkp ? 1 : 0, // Tambahkan ini
            'npwp'              => $request->npwp,           // Tambahkan ini
            'bank_account_info' => $request->bank_account_info, // Tambahkan ini
            'term_of_payment'   => $request->term_of_payment ?? 0, // Tambahkan ini
            'branch_id'         => $request->branch_id       // Tambahkan ini
        ]);
        return response()->json(['success' => true, 'message' => 'Data berhasil diupdate', 'data' => $supplier], 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 Data Supplier.'
            ], 403);
        }

        try {
            $supplier = Supplier::findOrFail($id);
            
            // Proteksi Integritas Data (Manual Check)
            // Mencegah penghapusan jika supplier sudah memiliki riwayat pembelian
            $hasPurchases = DB::table('purchases')->where('supplier_id', $id)->exists();
            
            if ($hasPurchases) {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal dihapus: Supplier ini memiliki riwayat transaksi pembelian.'
                ], 400);
            }

            $supplier->delete();
            return response()->json(['success' => true, 'message' => 'Data dihapus'], 200);
            
        } catch (QueryException $e) {
            // PENAMBAHAN: Lapis kedua proteksi Enterprise untuk menangkap error constraint dari relasi tabel lain (misal hutang piutang)
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal dihapus: Supplier 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);
        }
    }
}