<?php

namespace App\Http\Controllers;

use App\Models\Currency;
use App\Models\UserSetting;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    /**
     * Display the settings page.
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $settings = $user->getSettings();
        $currencies = Currency::active()->get();

        return view('settings.index', compact('settings', 'currencies'));
    }

    /**
     * Update the settings.
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'default_currency_id' => 'nullable|exists:currencies,id',
            'theme' => 'required|in:light,dark,system',
            'locale' => 'required|string|max:10',
            'timezone' => 'required|string|max:50',
            'date_format' => 'required|in:Y-m-d,d/m/Y,m/d/Y,d-m-Y,d M Y',
            'first_day_of_week' => 'required|in:sunday,monday',
            'email_notifications' => 'boolean',
            'budget_alerts' => 'boolean',
            'bill_reminders' => 'boolean',
            'weekly_summary' => 'boolean',
            'monthly_summary' => 'boolean',
        ]);

        $settings = $request->user()->getSettings();
        $settings->update($validated);

        return redirect()->route('settings.index')
            ->with('success', 'Settings updated successfully.');
    }

    /**
     * Export all user data.
     */
    public function exportData(Request $request)
    {
        $user = $request->user();

        $data = [
            'user' => [
                'name' => $user->name,
                'email' => $user->email,
            ],
            'settings' => $user->settings,
            'accounts' => $user->accounts()->with('currency')->get(),
            'categories' => $user->categories,
            'transactions' => $user->transactions()->with(['account', 'category', 'tags'])->get(),
            'transfers' => $user->transfers()->with(['fromAccount', 'toAccount'])->get(),
            'budgets' => $user->budgets()->with('category')->get(),
            'goals' => $user->goals()->with('contributions')->get(),
            'recurring_transactions' => $user->recurringTransactions()->with(['account', 'category'])->get(),
            'tags' => $user->tags,
            'exported_at' => now()->toIso8601String(),
        ];

        $filename = 'mymoney_export_' . now()->format('Y-m-d_His') . '.json';

        return response()->json($data)
            ->header('Content-Disposition', "attachment; filename=\"{$filename}\"");
    }

    /**
     * Delete all user data (except account).
     */
    public function deleteData(Request $request)
    {
        $validated = $request->validate([
            'confirm' => 'required|string|in:DELETE',
        ]);

        $user = $request->user();

        // Delete all user data
        $user->transactions()->forceDelete();
        $user->transfers()->delete();
        $user->budgets()->delete();
        $user->goals()->delete();
        $user->recurringTransactions()->delete();
        $user->tags()->delete();
        $user->accounts()->forceDelete();
        $user->categories()->delete();
        $user->userNotifications()->delete();
        $user->imports()->delete();
        $user->settings?->delete();

        return redirect()->route('dashboard')
            ->with('success', 'All data has been deleted.');
    }
}
