<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Currency;
use App\Models\Goal;
use App\Models\GoalContribution;
use App\Http\Requests\StoreGoalRequest;
use App\Http\Requests\UpdateGoalRequest;
use Illuminate\Http\Request;

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

        $goals = Goal::where('user_id', $user->id)
            ->with('currency')
            ->orderByRaw("CASE WHEN status = 'active' THEN 0 WHEN status = 'achieved' THEN 1 ELSE 2 END")
            ->orderBy('target_date')
            ->get();

        // Separate by status
        $activeGoals = $goals->where('status', 'active');
        $achievedGoals = $goals->where('status', 'achieved');

        // Summary
        $totalTarget = $activeGoals->sum('target_amount');
        $totalSaved = $activeGoals->sum('current_amount');

        return view('goals.index', compact(
            'goals',
            'activeGoals',
            'achievedGoals',
            'totalTarget',
            'totalSaved'
        ));
    }

    /**
     * Show the form for creating a new goal.
     */
    public function create(Request $request)
    {
        $currencies = Currency::active()->get();
        $accounts = $request->user()->activeAccounts()->get();
        $icons = Goal::DEFAULT_ICONS;
        $defaultCurrency = Currency::where('code', 'IDR')->first();

        return view('goals.create', compact('currencies', 'accounts', 'icons', 'defaultCurrency'));
    }

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

        // Set default currency if not provided
        if (!isset($data['currency_id'])) {
            $data['currency_id'] = $request->user()->default_currency->id;
        }

        Goal::create($data);

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

    /**
     * Display the specified goal.
     */
    public function show(Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $goal->load(['currency', 'account', 'contributions' => function ($query) {
            $query->orderBy('date', 'desc');
        }]);

        return view('goals.show', compact('goal'));
    }

    /**
     * Show the form for editing the goal.
     */
    public function edit(Request $request, Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $currencies = Currency::active()->get();
        $accounts = $request->user()->activeAccounts()->get();
        $icons = Goal::DEFAULT_ICONS;

        return view('goals.edit', compact('goal', 'currencies', 'accounts', 'icons'));
    }

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

        return redirect()->route('goals.show', $goal)
            ->with('success', 'Target berhasil diperbarui.');
    }

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

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

    /**
     * Add a contribution to the goal.
     */
    public function contribute(Request $request, Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'date' => 'nullable|date',
            'notes' => 'nullable|string|max:255',
        ]);

        $goal->addContribution(
            $validated['amount'],
            $validated['notes'] ?? null,
            isset($validated['date']) ? \Carbon\Carbon::parse($validated['date']) : null
        );

        return redirect()->route('goals.show', $goal)
            ->with('success', 'Kontribusi berhasil ditambahkan.');
    }

    /**
     * Remove a contribution.
     */
    public function removeContribution(Goal $goal, GoalContribution $contribution)
    {
        // Authorization handled by route model binding in AppServiceProvider
        if ($contribution->goal_id !== $goal->id) {
            abort(404);
        }

        $contribution->delete();

        return redirect()->route('goals.show', $goal)
            ->with('success', 'Kontribusi berhasil dihapus.');
    }

    /**
     * Mark goal as achieved.
     */
    public function achieve(Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $goal->markAsAchieved();

        return redirect()->route('goals.show', $goal)
            ->with('success', 'Selamat! Target berhasil dicapai!');
    }

    /**
     * Cancel a goal.
     */
    public function cancel(Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $goal->cancel();

        return redirect()->route('goals.index')
            ->with('success', 'Target dibatalkan.');
    }

    /**
     * Reactivate a goal.
     */
    public function reactivate(Goal $goal)
    {
        // Authorization handled by route model binding in AppServiceProvider
        $goal->reactivate();

        return redirect()->route('goals.show', $goal)
            ->with('success', 'Target diaktifkan kembali.');
    }
}
