<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Expense;
use App\Models\ExpenseCategory;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Services\AccountingService;

class ExpenseApiController extends Controller
{
    // 1. Ambil Daftar Kategori Biaya untuk Dropdown di Aplikasi
    public function getCategories(Request $request)
    {
        $categories = ExpenseCategory::where('is_active', 1)->select('id', 'name')->orderBy('name', 'asc')->get();
        
        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    // 2. Simpan Pengeluaran Baru dari Cabang (Petty Cash)
    public function storeExpense(Request $request)
    {
        $request->validate([
            'expense_category_id' => 'required|exists:expense_categories,id',
            'amount' => 'required|numeric|min:1',
            'name' => 'required|string|max:255', // Keperluan
            'note' => 'nullable|string'
        ]);

        $user = $request->user();

        try {
            DB::transaction(function () use ($request, $user) {
                // Pastikan Kategori Biaya memiliki pemetaan Akun (COA)
                $category = ExpenseCategory::find($request->expense_category_id);
                $expenseAccountId = $category->account_id;
                
                if (!$expenseAccountId) {
                    throw new \Exception("Kategori biaya '{$category->name}' belum dipetakan ke COA Akuntansi. Silakan hubungi admin pusat.");
                }

                // PERBAIKAN ENTERPRISE: Ambil akun Kas Kecil spesifik untuk cabang user yang login dan pastikan AKTIF
                $cashDrawerAccountId = DB::table('branch_accounts')
                    ->where('branch_id', $user->branch_id)
                    ->where('type', 'kas_kecil')
                    ->where('is_active', 1) // PROTEKSI: Pastikan mapping tidak sedang dinonaktifkan
                    ->value('account_id');
                
                if (!$cashDrawerAccountId) {
                    throw new \Exception("Akun Kas Operasional (Kas Kecil) untuk cabang Anda belum dipetakan. Silakan hubungi admin pusat.");
                }

                // Simpan record expense
                $expense = Expense::create([
                    'branch_id' => $user->branch_id,
                    'user_id' => $user->id,
                    'expense_category_id' => $request->expense_category_id,
                    'expense_date' => Carbon::now(), 
                    'name' => $request->name,
                    'amount' => $request->amount,
                    'fund_source' => 'drawer', 
                    // PERBAIKAN: Hilangkan istilah POS/Kasir, gunakan istilah operasional ERP
                    'note' => $request->note ?? 'Diinput dari sistem operasional cabang',
                ]);

                // JURNALISASI OTOMATIS: Pengeluaran Kas Operasional Cabang
                AccountingService::log([
                    'branch_id'   => $user->branch_id,
                    'entry_date'  => Carbon::now()->toDateString(),
                    'description' => "Pengeluaran Operasional: " . $request->name,
                    'reference'   => "EXP-" . str_pad($expense->id, 5, '0', STR_PAD_LEFT),
                    'source_type' => 'DRAWER_EXPENSE',
                    'user_id'     => $user->id,
                    'items'       => [
                        // Debit: Beban Operasional / Akun Biaya
                        ['account_id' => $expenseAccountId, 'debit' => $request->amount, 'credit' => 0],
                        // Kredit: Kas Kecil Cabang (Uang keluar)
                        ['account_id' => $cashDrawerAccountId, 'debit' => 0, 'credit' => $request->amount],
                    ]
                ]);
            });

            return response()->json([
                'success' => true, 
                'message' => 'Pengeluaran berhasil dicatat. Kas operasional telah disesuaikan dan dijurnal.'
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Gagal mencatat pengeluaran: ' . $e->getMessage()
            ], 500);
        }
    }

    // 3. Ambil Riwayat Pengeluaran Hari Ini
    public function getTodayExpenses(Request $request)
    {
        $user = $request->user();
        
        $expenses = Expense::with('expenseCategory:id,name')
            ->where('branch_id', $user->branch_id)
            ->whereDate('expense_date', Carbon::today())
            ->where('fund_source', 'drawer')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($exp) {
                return [
                    'id' => $exp->id,
                    'time' => $exp->created_at->format('H:i'),
                    'category_name' => $exp->expenseCategory ? $exp->expenseCategory->name : 'Lain-lain',
                    'name' => $exp->name,
                    'amount' => (float) $exp->amount,
                    'note' => $exp->note,
                ];
            });

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

    public function toggleStatus(Request $request, $id)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Master Data COA Biaya)
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah status Master Kategori Biaya.'
            ], 403);
        }

        try {
            $category = \App\Models\ExpenseCategory::findOrFail($id);
            
            $category->is_active = !$category->is_active;
            $category->save();

            return response()->json([
                'success' => true,
                'message' => 'Status kategori berhasil diperbarui.',
                'new_status' => $category->is_active
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal mengubah status.'], 500);
        }
    }

    public function store(Request $request)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Master Data COA Biaya)
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah Master Kategori Biaya.'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'is_active' => 'required|boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:1024', 
        ]);

        try {
            $category = new \App\Models\ExpenseCategory();
            $category->name = strtoupper($request->name);
            $category->is_active = $request->is_active;

            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('icons/expenses', 'public');
                $category->image_path = $path;
            }

            $category->save();

            return response()->json([
                'success' => true,
                'message' => 'Kategori biaya berhasil ditambahkan!',
                'data' => $category
            ], 201);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}