<?php

namespace App\Http\Controllers;

use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SettingsController extends Controller
{
    public function theme(Request $request)
    {
        $theme = $request->input('theme', 'system');

        if (Auth::check()) {
            Auth::user()->update(['theme' => $theme]);
        }

        return response()->json(['success' => true, 'theme' => $theme]);
    }

    public function index()
    {
        $receiptSettings = [
            'receipt_header' => DB::table('settings')->where('key', 'receipt_header')->value('value') ?? 'POS SYSTEM',
            'receipt_tagline' => DB::table('settings')->where('key', 'receipt_tagline')->value('value') ?? 'Your Trusted Shopping Destination',
            'receipt_address' => DB::table('settings')->where('key', 'receipt_address')->value('value') ?? '',
            'receipt_phone' => DB::table('settings')->where('key', 'receipt_phone')->value('value') ?? '',
            'receipt_footer' => DB::table('settings')->where('key', 'receipt_footer')->value('value') ?? '*** THANK YOU FOR YOUR BUSINESS ***',
            'receipt_dev_ad' => DB::table('settings')->where('key', 'receipt_dev_ad')->value('value') ?? '',
        ];

        $reportSettings = [
            'report_header' => DB::table('settings')->where('key', 'report_header')->value('value') ?? 'POS System Report',
            'report_company' => DB::table('settings')->where('key', 'report_company')->value('value') ?? 'POS SYSTEM',
            'report_footer' => DB::table('settings')->where('key', 'report_footer')->value('value') ?? 'Generated by POS System',
            'report_dev_ad' => DB::table('settings')->where('key', 'report_dev_ad')->value('value') ?? '',
        ];

        return view('settings.index', compact('receiptSettings', 'reportSettings'));
    }

    public function update(Request $request)
    {
        $settings = $request->except('_token', '_method');

        foreach ($settings as $key => $value) {
            DB::table('settings')->updateOrInsert(
                ['key' => $key],
                ['value' => $value, 'updated_at' => now()]
            );
        }

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

    public function smsIndex()
    {
        $smsService = new SmsService;
        $settings = $smsService->getSettings();

        return view('settings.sms', compact('settings'));
    }

    public function smsSave(Request $request)
    {
        $settings = [
            'sms_enabled' => $request->sms_enabled ? '1' : '0',
            'sms_provider' => $request->sms_provider,
            'sms_api_key' => $request->sms_api_key,
            'sms_shortcode' => $request->sms_shortcode,
            'sms_sender_id' => $request->sms_sender_id,
            'sms_oauth_client_id' => $request->sms_oauth_client_id,
            'sms_oauth_client_secret' => $request->sms_oauth_client_secret,
            'sms_oauth_username' => $request->sms_oauth_username,
            'sms_oauth_password' => $request->sms_oauth_password,
            'sms_channel_id' => $request->sms_channel_id,
        ];

        foreach ($settings as $key => $value) {
            DB::table('settings')->updateOrInsert(
                ['key' => $key],
                ['value' => $value, 'updated_at' => now()]
            );
        }

        // Clear existing tokens
        DB::table('settings')->where('key', 'sms_oauth_access_token')->update(['value' => '', 'updated_at' => now()]);
        DB::table('settings')->where('key', 'sms_oauth_refresh_token')->update(['value' => '', 'updated_at' => now()]);
        DB::table('settings')->where('key', 'sms_oauth_token_expires')->update(['value' => '', 'updated_at' => now()]);

        return redirect()->route('settings.sms')->with('success', 'SMS settings saved successfully!');
    }

    public function smsTest(Request $request)
    {
        $request->validate([
            'phone' => 'required|string',
        ]);

        $smsService = new SmsService;
        $result = $smsService->testSms($request->phone);

        return response()->json($result);
    }

    public function smsClearCache()
    {
        DB::table('settings')->where('key', 'sms_oauth_access_token')->update(['value' => '', 'updated_at' => now()]);
        DB::table('settings')->where('key', 'sms_oauth_refresh_token')->update(['value' => '', 'updated_at' => now()]);
        DB::table('settings')->where('key', 'sms_oauth_token_expires')->update(['value' => '', 'updated_at' => now()]);

        return response()->json(['success' => true, 'message' => 'Cache cleared successfully']);
    }

    public function systemIndex()
    {
        if (! Auth::user()->isSuperAdmin()) {
            abort(403, 'Access denied. Super admin only.');
        }

        $systemName = DB::table('settings')->where('key', 'system_name')->value('value') ?? 'POS System';
        $inactivityTimeout = DB::table('settings')->where('key', 'inactivity_timeout')->value('value') ?? 300;

        return view('settings.system', compact('systemName', 'inactivityTimeout'));
    }

    public function systemUpdate(Request $request)
    {
        if (! Auth::user()->isSuperAdmin()) {
            abort(403, 'Access denied. Super admin only.');
        }

        $request->validate([
            'system_name' => 'required|string|max:255',
            'inactivity_timeout' => 'required|integer|min:0|max:86400',
        ]);

        DB::table('settings')->updateOrInsert(
            ['key' => 'system_name'],
            ['value' => $request->system_name, 'updated_at' => now()]
        );

        DB::table('settings')->updateOrInsert(
            ['key' => 'inactivity_timeout'],
            ['value' => $request->inactivity_timeout, 'updated_at' => now()]
        );

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