<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AppSettingApiController extends Controller
{
    public function index()
    {
        $setting = AppSetting::getSetting();
        
        return response()->json([
            'success' => true,
            'data' => [
                'brand_name' => $setting->brand_name,
                'admin_whatsapp' => $setting->admin_whatsapp,
                'is_online_store_open' => (bool) $setting->is_online_store_open,
                'whatsapp_format' => $setting->whatsapp_format,
                'logo_url' => $setting->brand_logo_url // Memanggil accessor dari model Anda
            ]
        ]);
    }

    public function update(Request $request)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Enterprise Global Settings)
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner yang berhak mengubah Pengaturan Global Aplikasi.'
            ], 403);
        }

        $setting = AppSetting::getSetting();

        $data = $request->only(['brand_name', 'admin_whatsapp', 'whatsapp_format']);
        
        // Konversi string dari FormData Next.js menjadi boolean
        if ($request->has('is_online_store_open')) {
            $data['is_online_store_open'] = filter_var($request->is_online_store_open, FILTER_VALIDATE_BOOLEAN);
        }

        // Handle Upload Logo Baru
        if ($request->hasFile('brand_logo')) {
            // Hapus logo lama jika ada (dan jika formatnya string path biasa)
            if ($setting->brand_logo && is_string($setting->brand_logo)) {
                Storage::disk('public')->delete($setting->brand_logo);
            }
            
            $path = $request->file('brand_logo')->store('logos', 'public');
            $data['brand_logo'] = $path; // Simpan path baru
        }

        $setting->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Pengaturan aplikasi berhasil diperbarui.',
            'logo_url' => $setting->brand_logo_url
        ]);
    }

    // ========================================================
    // TRIGGER ARTISAN COMMANDS (CLOSING & RECALCULATE)
    // ========================================================
    
    public function recalculateStock(Request $request)
    {
        // PENAMBAHAN: Proteksi Eksekusi Proses Berat (Database Heavy Operation)
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner yang berhak mengeksekusi Sinkronisasi Ulang Stok Nasional.'
            ], 403);
        }

        try {
            \Illuminate\Support\Facades\Artisan::call('stock:recalculate');
            return response()->json([
                'success' => true, 
                'message' => 'Sinkronisasi ulang stok berhasil dijalankan.'
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function closeStock(Request $request)
    {
        // PENAMBAHAN: Proteksi Operasi Akuntansi Kritis
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner yang berhak melakukan Tutup Buku (Closing) Stok.'
            ], 403);
        }

        try {
            // Sesuai dengan command di StockClose.php
            \Illuminate\Support\Facades\Artisan::call('stock:close');
            return response()->json([
                'success' => true, 
                'message' => 'Proses Kunci (Closing) stok bulan lalu berhasil.'
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function reopenStock(Request $request)
    {
        // PENAMBAHAN: Proteksi Operasi Akuntansi Kritis
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner yang berhak membuka kembali (Reopen) Stok yang sudah dikunci.'
            ], 403);
        }

        $request->validate([
            'month' => 'required|numeric|min:1|max:12',
            'year' => 'required|numeric'
        ]);

        try {
            // Sesuai dengan command di StockReopen.php
            \Illuminate\Support\Facades\Artisan::call('stock:reopen', [
                '--month' => $request->month,
                '--year' => $request->year
            ]);
            return response()->json([
                'success' => true, 
                'message' => 'Data closing stok berhasil dibuka kembali.'
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}