<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Setting;
use App\Models\StoreInformation;
use Illuminate\Support\Facades\Cache;

class SettingsController extends Controller
{
    /**
     * Display the settings index page
     */
    public function index()
    {
        $storeInfo = StoreInformation::first();
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        
        return view('settings.index', compact('storeInfo', 'settings'));
    }

    /**
     * Display general settings
     */
    public function general()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        $storeInfo = StoreInformation::first();
        
        return view('settings.general', compact('settings', 'storeInfo'));
    }

    /**
     * Update settings
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'app_name' => 'required|string|max:100',
            'app_url' => 'required|url',
            'timezone' => 'required|string',
            'currency' => 'required|string',
            'date_format' => 'required|string',
            'time_format' => 'required|string',
            'items_per_page' => 'required|integer|min:5|max:100',
        ]);

        foreach ($validated as $key => $value) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        // Clear settings cache
        Cache::forget('settings_cache');
        
        // Log the activity
        activity()
            ->causedBy(auth()->user())
            ->log('updated general settings');

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

    /**
     * Display backup settings
     */
    public function backup()
    {
        $backups = $this->getBackupList();
        $backupStats = $this->getBackupStats();
        
        return view('settings.backup', compact('backups', 'backupStats'));
    }

    /**
     * Create backup
     */
    public function createBackup(Request $request)
    {
        $request->validate([
            'backup_name' => 'required|string|max:100',
            'include_database' => 'boolean',
            'include_files' => 'boolean',
        ]);

        try {
            // Implement backup logic using spatie/laravel-backup
            // or your preferred backup solution
            
            // Example with spatie/laravel-backup (if installed):
            /*
            \Artisan::call('backup:run', [
                '--only-db' => !$request->boolean('include_files'),
            ]);
            */

            // For now, log a placeholder
            activity()
                ->causedBy(auth()->user())
                ->log('created system backup: ' . $request->backup_name);

            return redirect()->route('settings.backup')
                ->with('success', 'Backup created successfully!');

        } catch (\Exception $e) {
            return redirect()->route('settings.backup')
                ->with('error', 'Failed to create backup: ' . $e->getMessage());
        }
    }

    /**
     * Restore backup
     */
    public function restoreBackup(Request $request)
    {
        $request->validate([
            'backup_file' => 'required|file|mimes:zip,sql',
        ]);

        try {
            // Implement restore logic
            // This is a critical operation - ensure proper safeguards
            
            activity()
                ->causedBy(auth()->user())
                ->log('attempted to restore backup');

            return redirect()->route('settings.backup')
                ->with('success', 'Backup restored successfully!');

        } catch (\Exception $e) {
            return redirect()->route('settings.backup')
                ->with('error', 'Failed to restore backup: ' . $e->getMessage());
        }
    }

    /**
     * Get store settings for API
     */
    public function apiGetSettings()
    {
        $storeInfo = StoreInformation::first();
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        
        return response()->json([
            'success' => true,
            'settings' => [
                'store' => [
                    'name' => $storeInfo->store_name ?? config('app.name'),
                    'address' => $storeInfo->address ?? config('pos.store.address'),
                    'phone' => $storeInfo->telephone ?? config('pos.store.phone'),
                    'email' => $storeInfo->email ?? config('pos.store.email'),
                    'currency' => $storeInfo->currency ?? config('pos.store.currency'),
                    'vat_number' => $storeInfo->vat_number ?? config('pos.store.vat_number'),
                    'logo' => $storeInfo->logo ?? config('pos.store.logo'),
                ],
                'pos' => [
                    'tax_rate' => $settings['tax_rate'] ?? config('pos.tax_rate', 16),
                    'auto_print' => $settings['auto_print'] ?? config('pos.auto_print', true),
                    'require_customer' => $settings['require_customer'] ?? config('pos.require_customer', false),
                    'default_payment_method' => $settings['default_payment_method'] ?? config('pos.default_payment_method', 'cash'),
                ],
                'system' => [
                    'app_name' => $settings['app_name'] ?? config('app.name'),
                    'timezone' => $settings['timezone'] ?? config('app.timezone'),
                    'currency' => $settings['currency'] ?? config('pos.store.currency'),
                ]
            ]
        ]);
    }

    /**
     * Get backup list
     */
    private function getBackupList()
    {
        // Implement backup listing logic
        // This could read from storage/app/backups or your backup disk
        
        return [
            // Example backup list
        ];
    }

    /**
     * Get backup statistics
     */
    private function getBackupStats()
    {
        return [
            'total_backups' => 0,
            'last_backup' => null,
            'total_size' => '0 MB',
            'next_backup' => 'Disabled',
        ];
    }
}