<?php

namespace App\Services;

use App\Models\SchoolSetting;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class SchoolSettingService
{
    /**
     * Get all settings as key-value array
     */
    public function getAllSettings(): array
    {
        return SchoolSetting::getAllCached();
    }

    /**
     * Save multiple settings at once
     */
    public function saveMultiple(array $data): void
    {
        foreach ($data as $key => $value) {
            SchoolSetting::updateOrCreate(['key' => $key], ['value' => $value]);
        }
        SchoolSetting::clearCache();
    }

    /**
     * Upload school logo
     */
    public function uploadLogo(UploadedFile $file): string
    {
        // Delete old logo if exists
        $oldPath = SchoolSetting::get('school_logo');
        if (!empty($oldPath) && Storage::disk('public')->exists($oldPath)) {
            Storage::disk('public')->delete($oldPath);
        }

        $ext = $file->getClientOriginalExtension() ?: 'png';
        $filename = 'school/logo_' . time() . '.' . $ext;
        $file->storeAs('', $filename, 'public');

        SchoolSetting::set('school_logo', $filename);
        return $filename;
    }

    /**
     * Upload favicon
     */
    public function uploadFavicon(UploadedFile $file): string
    {
        $oldPath = SchoolSetting::get('school_favicon');
        if (!empty($oldPath) && Storage::disk('public')->exists($oldPath)) {
            Storage::disk('public')->delete($oldPath);
        }

        $ext = $file->getClientOriginalExtension() ?: 'ico';
        $filename = 'school/favicon_' . time() . '.' . $ext;
        $file->storeAs('', $filename, 'public');

        SchoolSetting::set('school_favicon', $filename);
        return $filename;
    }

    /**
     * Upload principal signature image
     */
    public function uploadSignature(UploadedFile $file): string
    {
        $oldPath = SchoolSetting::get('principal_signature');
        if (!empty($oldPath) && Storage::disk('public')->exists($oldPath)) {
            Storage::disk('public')->delete($oldPath);
        }

        $ext = $file->getClientOriginalExtension() ?: 'png';
        $filename = 'school/signature_' . time() . '.' . $ext;
        $file->storeAs('', $filename, 'public');

        SchoolSetting::set('principal_signature', $filename);
        return $filename;
    }

    /**
     * Delete a file setting (logo/favicon/signature)
     */
    public function deleteFile(string $key): void
    {
        $path = SchoolSetting::get($key);
        if (!empty($path) && Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }
        SchoolSetting::set($key, '');
    }
}
