<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Tax;
use App\Models\Setting;
use Illuminate\Support\Facades\File;
use App\Models\EmailNotificationSettings;
use Illuminate\Support\Facades\Validator;

class SettingsController extends Controller
{
    public function index(){
        $settings = Setting::first();
        $taxes = Tax::all();
        $email_notification_settings = EmailNotificationSettings::firstOrCreate([]);
        return view('admin/settings/index' , compact('settings', 'taxes', 'email_notification_settings'));
    }


    public function update(Request $request)
    {
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'website_name' => 'required|string|max:255',
            'business_email' => 'required|email',
            'business_phone' => 'required|string|max:20',
            'logo' => 'image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust file types and size as needed
            'favicon' => 'image|max:2048', 
            'currency' => 'nullable|string|max:255',
            'address' => 'nullable',
        ]);
    
        // Redirect back with errors if validation fails
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
    
        $settings = Setting::firstOrCreate([]);
    
        // Update settings fields
        $settings->update([
            'website_name' => $request->input('website_name'),
            'business_email' => $request->input('business_email'),
            'business_phone' => $request->input('business_phone'),
            'currency' => $request->input('currency'),
            'address' => $request->input('address'),
        ]);
    
    
    // Handle logo upload
        if ($request->hasFile('logo')) {
            $image = $request->file('logo');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('storage/img'), $imageName); 
        
            // Update the logo path using the update method
            $settings->update(['logo' => $imageName]);
        }

        // Handle favicon upload
        if ($request->hasFile('favicon')) {
            $image = $request->file('favicon');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('storage/img'), $imageName); 
        
            // Update the favicon path using the update method
            $settings->update(['favicon' => $imageName]);
        }

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


    // Store a new tax using AJAX
    public function taxstore(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'tax_name' => 'required|string|max:255',
            'tax_rate' => 'required|numeric|min:0',
        ]);

        // Create a new Tax instance and save it
        $tax = new Tax();
        $tax->name = $request->input('tax_name');
        $tax->rate = $request->input('tax_rate');
        $tax->save();

        // Return a JSON response to the AJAX request
        return response()->json([
            'success' => true,
            'message' => 'Tax added successfully.',
            'tax' => $tax
        ], 200);  // HTTP status code 200 OK
    }

    // Delete a tax using AJAX
    public function taxdestroy($id)
    {
        // Find the tax by ID and delete it
        $tax = Tax::findOrFail($id);
        $tax->delete();

        // Return a JSON response to the AJAX request
        return response()->json([
            'success' => true,
            'message' => 'Tax deleted successfully.',
        ], 200);  // HTTP status code 200 OK
    }

    public function updateEmailSettings(Request $request)
    {
        // Validate the input
        $request->validate([
            'mail_driver' => 'required|string',
            'mail_host' => 'required|string',
            'mail_port' => 'required|numeric',
            'mail_username' => 'required|string',
            'mail_password' => 'required|string',
            'mail_encryption' => 'nullable|string',
            'mail_from_address' => 'required|email',
            'mail_from_name' => 'required|string',
        ]);

        // Update .env file
        $this->updateEnv([
            'MAIL_DRIVER' => $request->mail_driver,
            'MAIL_HOST' => $request->mail_host,
            'MAIL_PORT' => $request->mail_port,
            'MAIL_USERNAME' => $request->mail_username,
            'MAIL_PASSWORD' => $request->mail_password,
            'MAIL_ENCRYPTION' => $request->mail_encryption,
            'MAIL_FROM_ADDRESS' => $request->mail_from_address,
            'MAIL_FROM_NAME' => $request->mail_from_name,
        ]);

        return redirect()->back()->with('success', 'Email settings updated successfully!');
    }

    // Function to update .env file
    protected function updateEnv($data)
    {
        $envPath = base_path('.env');
        if (File::exists($envPath)) {
            foreach ($data as $key => $value) {
                File::put($envPath, preg_replace(
                    "/^{$key}=.*/m",
                    "{$key}={$value}",
                    File::get($envPath)
                ));
            }
        }
    }


    public function updateEmailNotificationSettings(Request $request)
    {
        // Define the fields to update and default them to '0' (false)
        $fields = [
            'new_project_mail_client',
            'new_milestones_mail_client',
            'new_subscriptions_mail_client',
            'payment_request_mail_admin',
            'new_invoices_mail_client',
            'new_meetings_mail_all_members',
            'contracts_mail_client',
            'new_tickets_mail_admin',
            'new_task_add_mail_employee',
            'new_message_mail_user',
            'new_projects_add_mail_client',
        ];
    
        // Validate the inputs, ensuring booleans, and map missing fields to '0'
        $validated = [];
        foreach ($fields as $field) {
            $validated[$field] = $request->boolean($field, false) ? 1 : 0;
        }
    
        // Ensure that at least one checkbox is set to '1'
        if (!array_filter($validated)) {
            return redirect()->back()->withErrors(['error' => 'At least one email notification setting must be enabled.']);
        }
    
        // Fetch the first settings entry
        $settings = EmailNotificationSettings::first();
    
        // Update settings
        $settings->update($validated);
    
        return redirect()->back()->with('success', 'Email notification settings updated successfully!');
    }
    

}
