<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\GeneralSetting;
use Illuminate\Support\Facades\Validator;
class AdminSettingsController extends Controller
{
    public function index()
    {
        
        $generalSettings = GeneralSetting::all()->pluck('value', 'key')->toArray();
        
        return view('admin.settings', compact('generalSettings'));
    }

//   public function update(Request $request)
// {
   
//     $rules = [
//         'site_name' => 'required|string|max:255',
//         'site_description' => 'nullable|string|max:255',
//         'logo' => '',
//     ];

    
//     $validator = Validator::make($request->all(), $rules);

//     if ($validator->fails()) {
//         return redirect()->back()->withErrors($validator)->withInput();
//     }

    
//     GeneralSetting::updateOrCreate(
//         ['key' => 'site_name'],
//         ['value' => $request->input('site_name')]
//     );

    
//     GeneralSetting::updateOrCreate(
//         ['key' => 'site_description'],
//         ['value' => $request->input('site_description')]
//     );

//      if ($request->hasFile('logo')) {
//         $logo = $request->file('logo');
//         $logoName = time().'.'.$logo->extension();
//         $logo->move(public_path('logo'), $logoName); 
//         $validatedData['logo'] = 'logo/'.$logoName; 
//         GeneralSetting::updateOrCreate(
//             ['key' => 'logo'],
//             ['value' => $validatedData['logo']]
//         );
//     }

    

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

public function update(Request $request)
{
    $rules = [
        'site_name' => 'required|string|max:255',
        'site_description' => 'nullable|string|max:255',
        'logo' => '',
        'privacy_policy' => 'nullable|string',
        'terms_and_conditions' => 'nullable|string',
        'about_us' => 'nullable|string',
    ];

    // Validate the request data
    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

    // Update or create each setting
    GeneralSetting::updateOrCreate(
        ['key' => 'site_name'],
        ['value' => $request->input('site_name')]
    );

    GeneralSetting::updateOrCreate(
        ['key' => 'site_description'],
        ['value' => $request->input('site_description')]
    );

    // Update or create new fields
    $fields = ['privacy_policy', 'terms_and_conditions', 'about_us'];
    foreach ($fields as $field) {
        GeneralSetting::updateOrCreate(
            ['key' => $field],
            ['value' => $request->input($field)]
        );
    }

    // Handle logo upload if present
    // (Assuming the logic for logo upload remains the same as provided)

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



}
