<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Settings;
use App\Models\Plans;
use App\Models\Agent;
use App\Models\User_plans;
use App\Models\Admin;
use App\Models\Faq;
use App\Models\Images;
use App\Models\Testimony;
use App\Models\Content;
use App\Models\Asset;
use App\Models\Mt4Details;
use App\Models\Deposit;
use App\Models\Wdmethod;
use App\Models\Withdrawal;
use App\Models\Cp_transaction;
use App\Models\Tp_Transaction;
use App\Models\Notification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\Http\Traits\CPTrait;
use App\Mail\NewNotification;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Config;

class AppSettingsController extends Controller
{

    // Return view
    public function appsettingshow(Request $request)
    {
        $live_timezones = timezone_identifiers_list();
        include 'currencies.php';
        return view('admin.Settings.AppSettings.show', [
            'title'     => 'Website information settings',
            'timezones' => $live_timezones,
            'currencies' => $currencies,
            'settings'  => Settings::where('id', '=', '1')->first(),
        ]);
    }

    // for front end content management
    function RandomStringGenerator($n)
    {
        $generated_string = "";
        $domain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        $len = strlen($domain);
        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, $len - 1);
            $generated_string = $generated_string . $domain[$index];
        }
        return $generated_string;
    }

    // Update website information
    public function updatewebinfo(Request $request)
    {
        $this->validate($request, [
            'logo'    => 'mimes:jpg,jpeg,png|max:500|image',
            'favicon' => 'mimes:jpg,jpeg,png|max:500|image',
        ]);

        $settings = Settings::where('id', '=', '1')->first();
        $strtxt = $this->RandomStringGenerator(6);

        if ($request->hasfile('logo')) {
            $file     = $request->file('logo');
            $logoname = $strtxt . $file->getClientOriginalName() . time();
            $path     = $file->storeAs('public/photos', $logoname);
        } else {
            $logoname = $settings->logo;
        }

        if ($request->hasfile('favicon')) {
            $favfile = $request->file('favicon');
            $favname = $strtxt . $favfile->getClientOriginalName() . time();
            $pathfav = $favfile->storeAs('public/photos', $favname);
        } else {
            $favname = $settings->favicon;
        }

        Settings::where('id', '1')
            ->update([
                'newupdate'    => $request['update'],
                'site_name'    => $request['site_name'],
                'description'  => $request['description'],
                'keywords'     => $request['keywords'],
                'timezone'     => $request['timezone'],
                'site_title'   => $request['site_title'],
                'logo'         => $logoname,
                'favicon'      => $favname,
                'tawk_to'      => strip_tags($request['tawk_to']),
                'site_address' => $request['site_address'],
            ]);

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

    public function updatepreference(Request $request)
    {
        Settings::where('id', $request['id'])
            ->update([
                'contact_email'       => $request['contact_email'],
                'currency'            => $request['currency'],
                's_currency'          => $request['s_currency'],
                'weekend_trade'       => $request['weekend_trade'],
                'location'            => $request['location'],
                'trade_mode'          => $request['trade_mode'],
                'enable_verification' => $request['enail_verify'],
                'google_translate'    => $request['googlet'],
                'enable_kyc'          => $request['enable_kyc'],
                'captcha'             => $request['captcha'],
                'enable_with'         => $request['withdraw'],
                'enable_social_login' => $request['social'],
                'enable_annoc'        => $request['annouc'],
            ]);
        return response()->json(['status' => 200, 'success' => 'Settings Saved successfully']);
    }

    // Update email preference
    public function updateemail(Request $request)
    {
        // Fixed: removed the space bug in where('id', ' 1') -> now where('id', 1)
        Settings::where('id', 1)
            ->update([
                'mail_server'    => $request['server'],
                'emailfrom'      => $request['emailfrom'],
                'emailfromname'  => $request['emailfromname'],
                'smtp_host'      => $request['smtp_host'],
                'smtp_port'      => $request['smtp_port'],
                'smtp_encrypt'   => $request['smtp_encrypt'],
                'smtp_user'      => $request['smtp_user'],
                'smtp_password'  => $request['smtp_password'],
                'google_id'      => $request['google_id'],
                'google_secret'  => $request['google_secret'],
                'google_redirect' => $request['google_redirect'],
                'capt_secret'    => $request['capt_secret'],
                'capt_sitekey'   => $request['capt_sitekey'],
            ]);
        return response()->json(['status' => 200, 'success' => 'Settings Saved successfully']);
    }

    // Test withdraw OTP email
    public function testEmail(Request $request)
    {
        $settings = Settings::where('id', 1)->first();

        if (!$settings) {
            return response()->json(['success' => false, 'message' => 'Settings not found in database.'], 500);
        }

        if (empty($settings->smtp_host) || empty($settings->smtp_user) || empty($settings->smtp_password)) {
            return response()->json(['success' => false, 'message' => 'SMTP settings are incomplete. Please save settings first.'], 422);
        }

        try {
            Config::set('mail.default', 'smtp');
            Config::set('mail.mailers.smtp.transport',  'smtp');
            Config::set('mail.mailers.smtp.host',       trim($settings->smtp_host));
            Config::set('mail.mailers.smtp.port',       (int) $settings->smtp_port);
            Config::set('mail.mailers.smtp.encryption', trim($settings->smtp_encrypt));
            Config::set('mail.mailers.smtp.username',   trim($settings->smtp_user));
            Config::set('mail.mailers.smtp.password',   $settings->smtp_password);
            Config::set('mail.mailers.smtp.timeout',    10);
            Config::set('mail.from.address',            trim($settings->emailfrom));
            Config::set('mail.from.name',               $settings->emailfromname);

            $otp = rand(100000, 999999);

            Mail::raw(
                "Your withdraw OTP test code is: {$otp}\n\nThis is a test alert from your SMTP configuration.",
                function ($message) use ($settings) {
                    $message->to(trim($settings->emailfrom))
                            ->subject('Test Withdraw OTP Alert');
                }
            );

            return response()->json([
                'success' => true,
                'message' => 'Test OTP sent to ' . $settings->emailfrom,
            ]);

        } catch (\Swift_TransportException $e) {
            \Log::error('SMTP Transport Error: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => 'SMTP connection failed: ' . $e->getMessage()], 500);

        } catch (\Exception $e) {
            \Log::error('Mail Error: ' . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}