<?php

namespace App\Http\Controllers;

use App\Models\SystemSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SettingsController extends Controller
{
    public function index()
    {
        $companyInfoSource = SystemSetting::getCompanyInfoSource();
        $globalIdPrefix = SystemSetting::getGlobalIdPrefix();
        $appTimezone = SystemSetting::get('app_timezone', config('app.timezone', 'Asia/Kuala_Lumpur'));
        $siteTitle = SystemSetting::get('site_title', 'Omni Management System');
        $siteName = SystemSetting::get('site_name', 'Omni');
        $siteLogo = SystemSetting::get('site_logo', '');
        $loginDescription = SystemSetting::get('login_description', 'Welcome to Omni Management System');
        $footerText = SystemSetting::get('footer_text', '© 2025 Omni. All rights reserved.');
        $registrationEnabled = SystemSetting::get('registration_enabled', 'false');

        // BayarCash Payment Gateway Settings
        $bayarcashPortalKey = SystemSetting::get('bayarcash_portal_key', '');
        $bayarcashPat = SystemSetting::get('bayarcash_pat', '');
        $bayarcashSecretKey = SystemSetting::get('bayarcash_secret_key', '');
        $bayarcashEnvironment = SystemSetting::get('bayarcash_environment', 'sandbox');

        // COD Shipping Rates
        $codRateEastMalaysia = SystemSetting::get('cod_rate_east_malaysia', 20.00);
        $codRatePeninsular = SystemSetting::get('cod_rate_peninsular', 10.00);

        // Online Payment Shipping Cost (for cost estimation)
        $onlinePaymentShippingCost = SystemSetting::get('online_payment_shipping_cost', 6.00);

        // FPX Payment Gateway Fee Settings
        $fpxFeeType = SystemSetting::get('fpx_fee_type', 'none');
        $fpxFixedFee = SystemSetting::get('fpx_fixed_fee', 0);
        $fpxPercentageFee = SystemSetting::get('fpx_percentage_fee', 0);
        $fpxFeeBearer = SystemSetting::get('fpx_fee_bearer', 'customer');

        // DuitNow Payment Gateway Fee Settings
        $duitnowFeeType = SystemSetting::get('duitnow_fee_type', 'none');
        $duitnowFixedFee = SystemSetting::get('duitnow_fixed_fee', 0);
        $duitnowPercentageFee = SystemSetting::get('duitnow_percentage_fee', 0);
        $duitnowFeeBearer = SystemSetting::get('duitnow_fee_bearer', 'customer');

        // PWA Notification Settings
        $pwaNotificationsEnabled = SystemSetting::get('pwa_notifications_enabled', 'true');
        $pwaNotificationTitle = SystemSetting::get('pwa_notification_title', '{emoji} Kaching! Pesanan #{order_number}');
        $pwaNotificationBody = SystemSetting::get('pwa_notification_body', '{total} • {customer} • {platform}');
        $pwaHighValueThreshold = SystemSetting::get('pwa_high_value_threshold', 500);
        $pwaNotificationVolume = SystemSetting::get('pwa_notification_volume', 80);
        $pwaRegularEmoji = SystemSetting::get('pwa_regular_emoji', '💰');
        $pwaHighValueEmoji = SystemSetting::get('pwa_high_value_emoji', '🎉');

        // Maintenance Mode Status (Soft Maintenance)
        $maintenanceMode = SystemSetting::get('soft_maintenance_mode', 'false') === 'true';

        return view('settings.index', compact(
            'companyInfoSource',
            'globalIdPrefix',
            'appTimezone',
            'siteTitle',
            'siteName',
            'siteLogo',
            'loginDescription',
            'footerText',
            'registrationEnabled',
            'bayarcashPortalKey',
            'bayarcashPat',
            'bayarcashSecretKey',
            'bayarcashEnvironment',
            'codRateEastMalaysia',
            'codRatePeninsular',
            'onlinePaymentShippingCost',
            'fpxFeeType',
            'fpxFixedFee',
            'fpxPercentageFee',
            'fpxFeeBearer',
            'duitnowFeeType',
            'duitnowFixedFee',
            'duitnowPercentageFee',
            'duitnowFeeBearer',
            'pwaNotificationsEnabled',
            'pwaNotificationTitle',
            'pwaNotificationBody',
            'pwaHighValueThreshold',
            'pwaNotificationVolume',
            'pwaRegularEmoji',
            'pwaHighValueEmoji',
            'maintenanceMode'
        ));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'company_info_source' => 'required|in:admin,seller',
            'global_id_prefix' => 'required|string|max:10|alpha_dash',
            'app_timezone' => 'required|string|timezone',
            'site_title' => 'required|string|max:100',
            'site_name' => 'required|string|max:50',
            'site_logo' => 'nullable|string|max:500',
            'logo_file' => 'nullable|image|mimes:jpeg,jpg,png,gif,svg,webp|max:2048',
            'remove_logo' => 'nullable|boolean',
            'login_description' => 'required|string|max:255',
            'footer_text' => 'required|string|max:255',
            'registration_enabled' => 'required|in:true,false',
            'cod_rate_east_malaysia' => 'required|numeric|min:0',
            'cod_rate_peninsular' => 'required|numeric|min:0',
            'online_payment_shipping_cost' => 'required|numeric|min:0',
            'bayarcash_portal_key' => 'nullable|string|max:255',
            'bayarcash_pat' => 'nullable|string|max:1000',
            'bayarcash_secret_key' => 'nullable|string|max:255',
            'bayarcash_environment' => 'required|in:sandbox,production',
            'fpx_fee_type' => 'nullable|in:none,fixed,percentage,both',
            'fpx_fixed_fee' => 'nullable|numeric|min:0|max:9999999.99',
            'fpx_percentage_fee' => 'nullable|numeric|min:0|max:100',
            'fpx_fee_bearer' => 'nullable|in:customer,merchant',
            'duitnow_fee_type' => 'nullable|in:none,fixed,percentage,both',
            'duitnow_fixed_fee' => 'nullable|numeric|min:0|max:9999999.99',
            'duitnow_percentage_fee' => 'nullable|numeric|min:0|max:100',
            'duitnow_fee_bearer' => 'nullable|in:customer,merchant',
            'pwa_notifications_enabled' => 'nullable|in:true,false',
            'pwa_notification_title' => 'nullable|string|max:255',
            'pwa_notification_body' => 'nullable|string|max:255',
            'pwa_high_value_threshold' => 'nullable|integer|min:0|max:100000',
            'pwa_notification_volume' => 'nullable|integer|min:0|max:100',
            'pwa_regular_emoji' => 'nullable|string|max:10',
            'pwa_high_value_emoji' => 'nullable|string|max:10',
        ]);

        SystemSetting::set('company_info_source', $validated['company_info_source']);
        SystemSetting::set('global_id_prefix', strtoupper($validated['global_id_prefix']));
        SystemSetting::set('app_timezone', $validated['app_timezone']);
        SystemSetting::set('site_title', $validated['site_title']);
        SystemSetting::set('site_name', $validated['site_name']);

        // Handle logo upload/removal
        $currentLogo = SystemSetting::get('site_logo', '');

        // Remove logo if checkbox is checked
        if ($request->has('remove_logo') && $request->remove_logo) {
            // Delete old file if it exists in public/images
            if ($currentLogo && str_starts_with($currentLogo, '/images/')) {
                $oldPath = public_path($currentLogo);
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
            }
            SystemSetting::set('site_logo', '');
        }
        // Handle file upload
        elseif ($request->hasFile('logo_file')) {
            // Delete old logo file if it exists in public/images
            if ($currentLogo && str_starts_with($currentLogo, '/images/')) {
                $oldPath = public_path($currentLogo);
                if (file_exists($oldPath)) {
                    unlink($oldPath);
                }
            }

            // Create images directory if it doesn't exist
            $imagesPath = public_path('images');
            if (!file_exists($imagesPath)) {
                mkdir($imagesPath, 0755, true);
            }

            // Store the uploaded file
            $file = $request->file('logo_file');
            $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file->getClientOriginalName());
            $file->move($imagesPath, $fileName);

            // Save relative path
            SystemSetting::set('site_logo', '/images/' . $fileName);
        }
        // Otherwise use the URL if provided
        elseif ($request->filled('site_logo')) {
            SystemSetting::set('site_logo', $validated['site_logo']);
        }

        SystemSetting::set('login_description', $validated['login_description']);
        SystemSetting::set('footer_text', $validated['footer_text']);
        SystemSetting::set('registration_enabled', $validated['registration_enabled']);

        // Save COD shipping rates
        SystemSetting::set('cod_rate_east_malaysia', $validated['cod_rate_east_malaysia']);
        SystemSetting::set('cod_rate_peninsular', $validated['cod_rate_peninsular']);

        // Save Online Payment shipping cost
        SystemSetting::set('online_payment_shipping_cost', $validated['online_payment_shipping_cost']);

        // Save BayarCash Payment Gateway Settings
        SystemSetting::set('bayarcash_portal_key', $validated['bayarcash_portal_key'] ?? '');
        SystemSetting::set('bayarcash_pat', $validated['bayarcash_pat'] ?? '');
        SystemSetting::set('bayarcash_secret_key', $validated['bayarcash_secret_key'] ?? '');
        SystemSetting::set('bayarcash_environment', $validated['bayarcash_environment']);

        // Save FPX Payment Gateway Fee Settings
        SystemSetting::set('fpx_fee_type', $validated['fpx_fee_type'] ?? 'none');
        SystemSetting::set('fpx_fixed_fee', $validated['fpx_fixed_fee'] ?? 0);
        SystemSetting::set('fpx_percentage_fee', $validated['fpx_percentage_fee'] ?? 0);
        SystemSetting::set('fpx_fee_bearer', $validated['fpx_fee_bearer'] ?? 'customer');

        // Save DuitNow Payment Gateway Fee Settings
        SystemSetting::set('duitnow_fee_type', $validated['duitnow_fee_type'] ?? 'none');
        SystemSetting::set('duitnow_fixed_fee', $validated['duitnow_fixed_fee'] ?? 0);
        SystemSetting::set('duitnow_percentage_fee', $validated['duitnow_percentage_fee'] ?? 0);
        SystemSetting::set('duitnow_fee_bearer', $validated['duitnow_fee_bearer'] ?? 'customer');

        // Save PWA Notification Settings
        SystemSetting::set('pwa_notifications_enabled', $validated['pwa_notifications_enabled'] ?? 'true');
        SystemSetting::set('pwa_notification_title', $validated['pwa_notification_title'] ?? '{emoji} Kaching! Pesanan #{order_number}');
        SystemSetting::set('pwa_notification_body', $validated['pwa_notification_body'] ?? '{total} • {customer} • {platform}');
        SystemSetting::set('pwa_high_value_threshold', $validated['pwa_high_value_threshold'] ?? 500);
        SystemSetting::set('pwa_notification_volume', $validated['pwa_notification_volume'] ?? 80);
        SystemSetting::set('pwa_regular_emoji', $validated['pwa_regular_emoji'] ?? '💰');
        SystemSetting::set('pwa_high_value_emoji', $validated['pwa_high_value_emoji'] ?? '🎉');

        // Clear all cache to ensure changes take effect immediately
        Cache::flush();

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

    /**
     * Enable maintenance mode (Soft Maintenance - Admins can bypass)
     */
    public function enableMaintenanceMode(Request $request)
    {
        try {
            $message = $request->input('message', 'System is currently under maintenance. We\'ll be back shortly.');

            // Enable soft maintenance mode
            SystemSetting::set('soft_maintenance_mode', 'true');
            SystemSetting::set('maintenance_message', $message);

            \Log::info('Soft maintenance mode enabled', [
                'user_id' => auth()->id(),
                'user_email' => auth()->user()->email,
                'message' => $message,
            ]);

            return redirect()->route('settings.index')
                ->with('success', 'Maintenance mode enabled. Site is now down for regular users. You (admin) can still access the site normally.');
        } catch (\Exception $e) {
            \Log::error('Failed to enable maintenance mode', [
                'error' => $e->getMessage(),
                'user_id' => auth()->id(),
            ]);

            return redirect()->route('settings.index')
                ->with('error', 'Failed to enable maintenance mode: ' . $e->getMessage());
        }
    }

    /**
     * Disable maintenance mode
     */
    public function disableMaintenanceMode()
    {
        try {
            // Disable soft maintenance mode
            SystemSetting::set('soft_maintenance_mode', 'false');

            \Log::info('Soft maintenance mode disabled', [
                'user_id' => auth()->id(),
                'user_email' => auth()->user()->email,
            ]);

            return redirect()->route('settings.index')
                ->with('success', 'Maintenance mode disabled. Site is now accessible to all users.');
        } catch (\Exception $e) {
            \Log::error('Failed to disable maintenance mode', [
                'error' => $e->getMessage(),
                'user_id' => auth()->id(),
            ]);

            return redirect()->route('settings.index')
                ->with('error', 'Failed to disable maintenance mode: ' . $e->getMessage());
        }
    }
}
