<?php

namespace App\Http\Controllers;

use App\Models\Budget;
use App\Models\Category;
use App\Http\Requests\StoreBudgetRequest;
use App\Http\Requests\UpdateBudgetRequest;
use Illuminate\Http\Request;

class BudgetController extends Controller
{
    /**
     * Display a listing of budgets.
     */
    public function index(Request $request)
    {
        $user = $request->user();

        $budgets = Budget::where('user_id', $user->id)
            ->with('category')
            ->orderBy('is_active', 'desc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($budget) {
                $budget->spent = $budget->spent_amount;
                $budget->percentage = $budget->spent_percentage;
                $budget->remaining = $budget->remaining_amount;
                return $budget;
            });

        // Summary
        $activeBudgets = $budgets->where('is_active', true);
        $totalBudgeted = $activeBudgets->sum('amount');
        $totalSpent = $activeBudgets->sum('spent');
        $totalRemaining = $activeBudgets->sum('remaining');

        return view('budgets.index', compact(
            'budgets',
            'totalBudgeted',
            'totalSpent',
            'totalRemaining'
        ));
    }

    /**
     * Show the form for creating a new budget.
     */
    public function create(Request $request)
    {
        $user = $request->user();

        // Get expense categories that don't have active budgets
        $existingBudgetCategoryIds = Budget::where('user_id', $user->id)
            ->where('is_active', true)
            ->pluck('category_id');

        $categories = Category::forUser($user->id)
            ->active()
            ->where(function ($q) {
                $q->where('type', 'expense')->orWhere('type', 'both');
            })
            ->whereNotIn('id', $existingBudgetCategoryIds)
            ->parents()
            ->with('children')
            ->get();

        $periods = Budget::PERIOD_LABELS;

        return view('budgets.create', compact('categories', 'periods'));
    }

    /**
     * Store a newly created budget.
     */
    public function store(StoreBudgetRequest $request)
    {
        $data = $request->validated();
        $data['user_id'] = $request->user()->id;

        // Check if budget already exists for this category/period
        $exists = Budget::where('user_id', $data['user_id'])
            ->where('category_id', $data['category_id'])
            ->where('is_active', true)
            ->exists();

        if ($exists) {
            return back()->withErrors(['category_id' => 'Anggaran aktif sudah ada untuk kategori ini.']);
        }

        Budget::create($data);

        return redirect()->route('budgets.index')
            ->with('success', 'Anggaran berhasil dibuat.');
    }

    /**
     * Show the form for editing the budget.
     */
    public function edit(Request $request, Budget $budget)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $budget->load('category');
        $periods = Budget::PERIOD_LABELS;

        // Get expense categories for dropdown
        $categories = $request->user()->categories()
            ->where('type', 'expense')
            ->orderBy('name')
            ->get();

        return view('budgets.edit', compact('budget', 'periods', 'categories'));
    }

    /**
     * Update the specified budget.
     */
    public function update(UpdateBudgetRequest $request, Budget $budget)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $budget->update($request->validated());

        return redirect()->route('budgets.index')
            ->with('success', 'Anggaran berhasil diperbarui.');
    }

    /**
     * Remove the specified budget.
     */
    public function destroy(Budget $budget)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $budget->delete();

        return redirect()->route('budgets.index')
            ->with('success', 'Anggaran berhasil dihapus.');
    }

    /**
     * Get budget progress (AJAX).
     */
    public function getProgress(Request $request)
    {
        $user = $request->user();

        $budgets = Budget::where('user_id', $user->id)
            ->where('is_active', true)
            ->with('category')
            ->get()
            ->map(function ($budget) {
                return [
                    'id' => $budget->id,
                    'category' => $budget->category->name,
                    'amount' => $budget->amount,
                    'spent' => $budget->spent_amount,
                    'remaining' => $budget->remaining_amount,
                    'percentage' => $budget->spent_percentage,
                    'status' => $budget->status,
                    'status_color' => $budget->status_color,
                ];
            });

        return response()->json($budgets);
    }

    /**
     * Toggle budget active status.
     */
    public function toggleActive(Budget $budget)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $budget->update(['is_active' => !$budget->is_active]);

        return redirect()->route('budgets.index')
            ->with('success', 'Budget status updated.');
    }
}
