<?php

namespace App\Http\Controllers\Admin;

use DateTimeZone;
use App\Models\Config;
use App\Models\Setting;
use App\Models\Currency;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Theme;

class WebsiteSettingController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */

    // General Settings
    public function index()
    {
        // Queries
        $timezonelist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
        $currencies = Currency::get();
        $settings = Setting::first();
        $config = Config::get();
        $themes = Theme::where('status', 1)->get();

        // Get image limit
        $image_limit = [
            'SIZE_LIMIT' => env('SIZE_LIMIT', '')
        ];

        $settings['image_limit'] = $image_limit;

        return view('admin.pages.settings.website', compact('settings', 'timezonelist', 'currencies', 'config', 'themes'));
    }


    // Update Website Setting
    public function changeWebsiteSettings(Request $request)
    {
        Setting::where('id', '1')->update([
            'site_name' => $request->site_name
        ]);

        Config::where('config_key', 'site_name')->update([
            'config_value' => $request->site_name
        ]);

        Config::where('config_key', 'app_theme')->update([
            'config_value' => $request->app_theme,
        ]);

        Config::where('config_key', 'default_theme')->update([
            'config_value' => $request->theme_id,
        ]);

        // App name
        $appName = str_replace('"', "", $request->app_name);
        $appName = str_replace("'", "", $appName);

        // Set new values using putenv (app name)
        $this->updateEnvFile('APP_NAME', '"' . $appName . '"');

        // Check website logo
        if (isset($request->site_logo)) {
            $validator = $request->validate([
                'site_logo' => 'mimes:jpeg,png,jpg,gif,svg|max:' . env("SIZE_LIMIT") . '',
            ]);

            $site_logo = '/images/web/elements/' . uniqid() . '.' . $request->site_logo->extension();
            $request->site_logo->move(public_path('images/web/elements'), $site_logo);

            // Update details
            Setting::where('id', '1')->update([
                'site_logo' => $site_logo
            ]);
        }

        // Check favicon
        if (isset($request->favi_icon)) {
            $validator = $request->validate([
                'favi_icon' => 'mimes:jpeg,png,jpg,gif,svg|max:' . env("SIZE_LIMIT") . '',
            ]);

            $favi_icon = '/images/web/elements/' . uniqid() . '.' . $request->favi_icon->extension();
            $request->favi_icon->move(public_path('images/web/elements'), $favi_icon);

            // Update details
            Setting::where('id', '1')->update([
                'favicon' => $favi_icon
            ]);
        }

        // Check primary image for website banner
        if (isset($request->primary_image)) {
            $validator = $request->validate([
                'primary_image' => 'mimes:jpeg,png,jpg,gif,svg|max:' . env("SIZE_LIMIT") . '',
            ]);

            $primary_image = '/images/web/elements/' . uniqid() . '.' . $request->primary_image->extension();
            $request->primary_image->move(public_path('/images/web/elements'), $primary_image);

            // Update image
            Config::where('config_key', 'primary_image')->update([
                'config_value' => $primary_image,
            ]);
        }

        // Update settings details
        Setting::where('id', '1')->update([
            'site_name' => $request->site_name, 'custom_css' => $request->custom_css, 'custom_js' => $request->custom_js
        ]);

        // Page redirect
        return redirect()->route('admin.website.settings')->with('success', trans('Website Settings Updated Successfully!'));
    }


    // Update change values in .env file
    public function updateEnvFile($key, $value)
    {
        $envPath = base_path('.env');

        // Check if the .env file exists
        if (file_exists($envPath)) {

            // Read the .env file
            $contentArray = file($envPath);

            // Loop through each line to find the key and update its value
            foreach ($contentArray as &$line) {

                // Split the line by '=' to get key and value
                $parts = explode('=', $line, 2);

                // Check if the key matches and update its value
                if (isset($parts[0]) && $parts[0] === $key) {
                    $line = $key . '=' . $value . PHP_EOL;
                }
            }

            // Implode the array back to a string and write it to the .env file
            $newContent = implode('', $contentArray);
            file_put_contents($envPath, $newContent);

            // Reload the environment variables
            putenv($key . '=' . $value);
            $_ENV[$key] = $value;
            $_SERVER[$key] = $value;
        }
    }
}
