<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tenant\Setting;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SettingController extends Controller
{
    public function index()
    {
        $tenant = Auth::user()->tenant;
        
        // General Settings
        $storeName = Setting::get('store_name', $tenant->name);
        $currency = Setting::get('currency', 'USD');
        $currencySymbol = Setting::get('currency_symbol', '$');
        $timezone = Setting::get('timezone', 'UTC');
        $dateFormat = Setting::get('date_format', 'Y-m-d');
        $themeColor = Setting::get('theme_color', '#10B981'); // Default Green
        
        // Files
        $logo = Setting::get('tenant_logo');
        $icon = Setting::get('tenant_icon');

        // Reports
        $reportHeader = Setting::get('report_header');
        $reportFooter = Setting::get('report_footer');

        // Loyalty
        $loyaltyEnabled = Setting::get('loyalty_enabled', '0');
        $conversionRate = Setting::get('loyalty_conversion_rate', '100');
        
        return view('tenant.settings.index', compact(
            'tenant', 
            'storeName', 'currency', 'currencySymbol', 'timezone', 'dateFormat', 'themeColor',
            'logo', 'icon', 'reportHeader', 'reportFooter',
            'loyaltyEnabled', 'conversionRate'
        ));
    }

    public function update(Request $request)
    {
        $request->validate([
            // General
            'store_name' => 'nullable|string|max:255',
            'currency' => 'nullable|string|max:10',
            'currency_symbol' => 'nullable|string|max:5',
            'timezone' => 'nullable|string|max:50',
            'date_format' => 'nullable|string|max:20',
            'theme_color' => 'nullable|string|max:20',
            'tenant_logo' => 'nullable|image|max:2048', // 2MB
            'tenant_icon' => 'nullable|image|max:1024', // 1MB
            'report_header' => 'nullable|string',
            'report_footer' => 'nullable|string',

            // Loyalty
            'loyalty_enabled' => 'nullable|boolean',
            'loyalty_conversion_rate' => 'required_if:loyalty_enabled,1|numeric|min:1',
        ]);

        // Handle File Uploads
        if ($request->hasFile('tenant_logo')) {
            $path = $request->file('tenant_logo')->store('tenant_logos', 'public');
            Setting::set('tenant_logo', $path);
        }

        if ($request->hasFile('tenant_icon')) {
            $path = $request->file('tenant_icon')->store('tenant_icons', 'public');
            Setting::set('tenant_icon', $path);
        }

        // Save General Settings
        if ($request->has('store_name')) Setting::set('store_name', $request->store_name);
        if ($request->has('currency')) Setting::set('currency', $request->currency);
        if ($request->has('currency_symbol')) Setting::set('currency_symbol', $request->currency_symbol);
        if ($request->has('timezone')) Setting::set('timezone', $request->timezone);
        if ($request->has('date_format')) Setting::set('date_format', $request->date_format);
        if ($request->has('theme_color')) Setting::set('theme_color', $request->theme_color);
        if ($request->has('report_header')) Setting::set('report_header', $request->report_header);
        if ($request->has('report_footer')) Setting::set('report_footer', $request->report_footer);

        // Save Loyalty Settings
        // Only update if present in request (to avoid clearing if separate forms used, though we might merge)
        // However, checkboxes are tricky. If form is submitted, unchecked checkbox sends nothing.
        // Assuming we merge forms or handle sections.
        if ($request->has('loyalty_conversion_rate')) {
             Setting::set('loyalty_enabled', $request->has('loyalty_enabled') ? '1' : '0');
             Setting::set('loyalty_conversion_rate', $request->input('loyalty_conversion_rate', '100'));
        }

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

    public function generateDemoData()
    {
        try {
            // Run the TenantDemoDataSeeder with tenant database connection
            Artisan::call('db:seed', [
                '--class' => 'Database\\Seeders\\Tenant\\TenantDemoDataSeeder',
                '--database' => 'tenant',
                '--force' => true,
            ]);

            return redirect()->back()->with('success', 'Demo data generated successfully! You can now explore the system.');
        } catch (\Exception $e) {
            Log::error('Demo Data Generation Failed: ' . $e->getMessage());
            return view('errors.system_error', ['message' => 'Failed to generate demo data. Please try again or contact support.', 'error' => $e->getMessage()]);
        }
    }

    public function cleanData()
    {
        try {
            DB::statement('SET FOREIGN_KEY_CHECKS=0;');

            // List of tables to truncate (Order matters less with FK checks off, but good practice)
            $tables = [
                'sale_items', 'sales',
                'purchase_items', 'purchases',
                'product_variants', 'products',
                'categories', 'brands', 'units', 'manufacturers',
                'customers', 'suppliers',
                // Add other transactional/catalog tables here
            ];

            foreach ($tables as $table) {
                DB::table($table)->truncate();
            }

            DB::statement('SET FOREIGN_KEY_CHECKS=1;');

            return redirect()->back()->with('success', 'All store data has been cleaned. You can now start fresh.');
        } catch (\Exception $e) {
            Log::error('Data Cleaning Failed: ' . $e->getMessage());
            return view('errors.system_error', ['message' => 'Failed to clean data. Please try again or contact support.', 'error' => $e->getMessage()]);
        }
    }
}
