<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\AzureADSettingsRequest;
use App\Http\Requests\SMTPSettingsRequest;
use App\Http\Requests\EmailTemplateRequest;
use App\Models\Setting;
use App\Models\EmailTemplate;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    /**
     * Get all settings
     */
    public function index()
    {
        $azureAD = Setting::get('azure_ad_config', []);
        $dauha = Setting::get('dauha_dss_config', []);
        $smtp = Setting::get('smtp_config', []);
        $timezone = Setting::get('timezone', 'Africa/Cairo');
        $maxFileSizeMB = Setting::get('max_file_size_mb', 5);
        $allowedFileTypes = Setting::get('allowed_file_types', ['image/jpeg', 'image/jpg', 'image/png']);

        // Mask passwords
        if (isset($azureAD['clientSecret'])) {
            $azureAD['clientSecret'] = '***';
        }
        if (isset($dauha['password'])) {
            $dauha['password'] = '***';
        }
        if (isset($smtp['password'])) {
            $smtp['password'] = '***';
        }

        return response()->json([
            'azureAD' => $azureAD,
            'dauha' => $dauha,
            'smtp' => $smtp,
            'timezone' => $timezone,
            'maxFileSizeMB' => $maxFileSizeMB,
            'allowedFileTypes' => $allowedFileTypes,
        ]);
    }

    /**
     * Update Azure AD configuration
     */
    public function updateAzureAD(AzureADSettingsRequest $request)
    {
        Setting::set('azure_ad_config', [
            'clientId' => $request->clientId,
            'tenantId' => $request->tenantId,
            'clientSecret' => $request->clientSecret,
            'redirectUri' => $request->redirectUri,
            'enabled' => $request->enabled,
        ], 'json', true);

        return response()->json([
            'message' => 'Azure AD configuration updated successfully',
        ]);
    }

    /**
     * Update Dauha DSS configuration
     */
    public function updateDauha(Request $request)
    {
        $request->validate([
            'apiUrl' => 'required_if:enabled,true|url|max:255',
            'username' => 'required_if:enabled,true|string|max:255',
            'password' => 'required_if:enabled,true|string|max:255',
            'enabled' => 'required|boolean',
        ]);

        Setting::set('dauha_dss_config', [
            'apiUrl' => $request->apiUrl,
            'username' => $request->username,
            'password' => $request->password,
            'enabled' => $request->enabled,
        ], 'json', true);

        return response()->json([
            'message' => 'Dauha DSS configuration updated successfully',
        ]);
    }

    /**
     * Update SMTP configuration
     */
    public function updateSMTP(SMTPSettingsRequest $request)
    {
        Setting::set('smtp_config', [
            'host' => $request->host,
            'port' => $request->port,
            'username' => $request->username,
            'password' => $request->password,
            'useTLS' => $request->useTLS,
            'fromEmail' => $request->fromEmail,
            'fromName' => $request->fromName,
        ], 'json', true);

        return response()->json([
            'message' => 'SMTP configuration updated successfully',
        ]);
    }

    /**
     * Update timezone
     */
    public function updateTimezone(Request $request)
    {
        $request->validate([
            'timezone' => 'required|string|timezone',
        ]);

        Setting::set('timezone', $request->timezone);

        // Update app timezone
        config(['app.timezone' => $request->timezone]);
        date_default_timezone_set($request->timezone);

        return response()->json([
            'message' => 'Timezone updated successfully',
        ]);
    }

    /**
     * Get all email templates
     */
    public function emailTemplates()
    {
        $templates = EmailTemplate::all();

        return response()->json([
            'data' => $templates,
        ]);
    }

    /**
     * Update email template
     */
    public function updateEmailTemplate(EmailTemplateRequest $request, int $id)
    {
        $template = EmailTemplate::findOrFail($id);

        $template->update([
            'subject' => $request->subject,
            'body' => $request->body,
            'is_active' => $request->isActive,
        ]);

        return response()->json([
            'message' => 'Email template updated successfully',
            'data' => $template,
        ]);
    }
}
