<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\SettingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class SettingController extends Controller
{
    public function __construct(
        protected SettingService $settingService
    ) {}

    /**
     * Display the settings form page.
     */
    public function edit(): Response
    {
        $settings = $this->settingService->all();
        $settings['version'] = config('app.version', 'v1.0.0');

        return Inertia::render('Settings/Edit', [
            'settings' => $settings,
        ]);
    }

    /**
     * Update the application settings.
     */
    public function update(Request $request): RedirectResponse
    {
        if (app()->environment('demo')) {
            return redirect()->back()->with('error', 'Mode Demo Aktif: Pengubahan pengaturan sistem tidak diizinkan di mode demo.');
        }

        $request->validate([
            'site_name' => ['required', 'string', 'max:255'],
            'site_description' => ['nullable', 'string', 'max:1000'],
            'site_logo' => ['nullable', 'image', 'max:2048', 'mimes:png,jpg,jpeg,webp,svg'],
            'site_favicon' => ['nullable', 'file', 'max:1024', 'mimes:ico,png,jpg,jpeg,svg'],
            'thermal_logo' => ['nullable', 'image', 'max:2048', 'mimes:png,jpg,jpeg,webp,svg'],
            'qris_image' => ['nullable', 'image', 'max:2048', 'mimes:png,jpg,jpeg,webp,svg'],
            'tax_percentage' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'service_charge_percentage' => ['nullable', 'numeric', 'min:0', 'max:100'],
            'tax_enabled' => ['nullable', 'boolean'],
            'service_charge_enabled' => ['nullable', 'boolean'],
        ]);

        $updates = [
            'site_name' => $request->input('site_name'),
            'site_description' => $request->input('site_description'),
            'tax_percentage' => $request->input('tax_percentage', '0'),
            'service_charge_percentage' => $request->input('service_charge_percentage', '0'),
            'tax_enabled' => $request->boolean('tax_enabled') ? '1' : '0',
            'service_charge_enabled' => $request->boolean('service_charge_enabled') ? '1' : '0',
        ];

        // Handle Site Logo upload
        if ($request->hasFile('site_logo')) {
            $this->deleteOldFile('site_logo');
            $path = $request->file('site_logo')->store('settings', 'public');
            $updates['site_logo'] = Storage::disk('public')->url($path);
        }

        // Handle Site Favicon upload
        if ($request->hasFile('site_favicon')) {
            $this->deleteOldFile('site_favicon');
            $path = $request->file('site_favicon')->store('settings', 'public');
            $updates['site_favicon'] = Storage::disk('public')->url($path);
        }

        // Handle Thermal Logo upload
        if ($request->hasFile('thermal_logo')) {
            $this->deleteOldFile('thermal_logo');
            $path = $request->file('thermal_logo')->store('settings', 'public');
            $updates['thermal_logo'] = Storage::disk('public')->url($path);
        }

        // Handle QRIS Image upload
        if ($request->hasFile('qris_image')) {
            $this->deleteOldFile('qris_image');
            $path = $request->file('qris_image')->store('settings', 'public');
            $updates['qris_image'] = Storage::disk('public')->url($path);
        }

        $this->settingService->setMany($updates);

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

    /**
     * Helper to delete the old setting file from storage.
     */
    protected function deleteOldFile(string $key): void
    {
        $oldUrl = $this->settingService->get($key);

        if (!$oldUrl) {
            return;
        }

        // Extract path from URL to locate it on public storage
        $path = parse_url($oldUrl, PHP_URL_PATH);
        
        if ($path) {
            // Remove '/storage/' prefix for local disk delete
            $relativePath = preg_replace('/^\/storage\//', '', $path);
            
            // Check and delete file
            if (Storage::disk('public')->exists($relativePath)) {
                Storage::disk('public')->delete($relativePath);
            }
        }
    }
}
