<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\OperationalCost;
use App\Models\Branch;
use App\Models\JournalEntry;
use App\Models\JournalDetail;
use App\Models\Account;

class OperationalCostController extends Controller
{
    public function index(Request $request)
    {
        $query = OperationalCost::orderBy('date', 'desc');

        if ($request->filled('month')) {
            $query->whereMonth('date', $request->month);
        }
        if ($request->filled('year')) {
            $query->whereYear('date', $request->year);
        }
        if ($request->filled('branch') && $request->branch != 'Semua Cabang') {
            $query->where('branch', $request->branch);
        }

        $costs = $query->get();
        $branches = Branch::all();
        $labels = OperationalCost::select('label')->distinct()->pluck('label');

        return view('biaya_operasional', compact('costs', 'branches', 'labels'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'branch' => 'required|string|max:255',
            'label' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
        ]);

        $cleanAmount = str_replace('.', '', $request->amount);

        \Illuminate\Support\Facades\DB::transaction(function () use ($request, $cleanAmount) {
            $cost = OperationalCost::create([
                'date' => $request->date,
                'branch' => $request->branch,
                'label' => $request->label,
                'amount' => (int) $cleanAmount,
            ]);

            $kasAccount = Account::where('code', '101')->first();
            $bebanAccount = Account::where('code', '502')->first();

            if ($kasAccount && $bebanAccount) {
                $journal = JournalEntry::create([
                    'date' => $cost->date,
                    'description' => 'Biaya Operasional: ' . $cost->label,
                    'reference_type' => 'OperationalCost',
                    'reference_id' => $cost->id,
                    'branch' => $cost->branch,
                ]);

                JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $bebanAccount->id, 'debit' => $cost->amount, 'credit' => 0]);
                JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $cost->amount]);
            }
        });

        return back()->with('success', 'Biaya operasional berhasil ditambahkan!');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'date' => 'required|date',
            'branch' => 'required|string|max:255',
            'label' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0',
        ]);

        $cleanAmount = str_replace('.', '', $request->amount);

        \Illuminate\Support\Facades\DB::transaction(function () use ($request, $id, $cleanAmount) {
            $cost = OperationalCost::findOrFail($id);
            $cost->update([
                'date' => $request->date,
                'branch' => $request->branch,
                'label' => $request->label,
                'amount' => (int) $cleanAmount,
            ]);

            JournalEntry::where('reference_type', 'OperationalCost')->where('reference_id', $cost->id)->delete();

            $kasAccount = Account::where('code', '101')->first();
            $bebanAccount = Account::where('code', '502')->first();

            if ($kasAccount && $bebanAccount) {
                $journal = JournalEntry::create([
                    'date' => $cost->date,
                    'description' => 'Biaya Operasional: ' . $cost->label,
                    'reference_type' => 'OperationalCost',
                    'reference_id' => $cost->id,
                    'branch' => $cost->branch,
                ]);

                JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $bebanAccount->id, 'debit' => $cost->amount, 'credit' => 0]);
                JournalDetail::create(['journal_entry_id' => $journal->id, 'account_id' => $kasAccount->id, 'debit' => 0, 'credit' => $cost->amount]);
            }
        });

        return back()->with('success', 'Biaya operasional berhasil diperbarui!');
    }

    public function destroy($id)
    {
        $cost = OperationalCost::findOrFail($id);
        JournalEntry::where('reference_type', 'OperationalCost')->where('reference_id', $cost->id)->delete();
        $cost->delete();
        return back()->with('success', 'Biaya operasional berhasil dihapus!');
    }
}
