<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\Preference;

class PreferenceController extends Controller
{
    public function index()
    {
        $preference = Preference::first();
        return view('backoffice.preferences.index', compact('preference'));
    }


    public function store(Request $request)
    {
        $request->validate([
            'Email_address' => 'nullable|email',
            'footer_discription' => 'nullable|string',
            'subcription_description_free' => 'nullable|string',
            'subcription_description' => 'nullable|string',
        ]);

        $data = $request->only([
            'facebook',
            'instagram',
            'youtube',
            'Email_address',
            'footer_discription',
            'copy_right_text',
            // Free Subscription
            'subcription_heading_free',
            'subcription_sub_heading_free',
            'subcription_description_free',
            'subcription_duration_free',

            // Paid Subscription
            'subcription_heading',
            'subcription_sub_heading',
            'subcription_description',
            'subcription_duration',
        ]);

        // Handle header logo
        if ($request->hasFile('header_logo')) {
            $data['header_logo'] = $this->uploadFile($request->file('header_logo'), 'header_logo');
        }

        // Handle footer logo
        if ($request->hasFile('footer_logo')) {
            $data['footer_logo'] = $this->uploadFile($request->file('footer_logo'), 'footer_logo');
        }

        $preference = Preference::first();
        if ($preference) {
            $preference->update($data);
        } else {
            Preference::create($data);
        }

        return redirect()->back()->with('success', 'Preferences saved successfully!');
    }

    private function uploadFile($file, $prefix)
    {
        $destinationPath = public_path('website/uploads/preferences');
        $fileHash = md5_file($file->getRealPath());

        $existing = collect(glob($destinationPath . '/*'))
            ->first(fn($existingFile) => md5_file($existingFile) === $fileHash);

        if ($existing) {
            return 'website/uploads/preferences/' . basename($existing);
        } else {
            $fileName = $prefix . '_' . time() . '_' . $file->getClientOriginalName();
            $file->move($destinationPath, $fileName);
            return 'website/uploads/preferences/' . $fileName;
        }
    }
}
