<?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;

class BackblazeSettingController 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();

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

    // Update Backblaze S3 Setting
    public function changeBackblazeS3Settings(Request $request)
    {
        // Set new values using putenv (backblaze)
        $this->updateEnvFile('BACK_ENABLE', $request->backblaze_enable);
        $this->updateEnvFile('BACK_ACCESS_KEY_ID', $request->backblaze_access_key);
        $this->updateEnvFile('BACK_SECRET_ACCESS_KEY', $request->backblaze_secret_key);
        $this->updateEnvFile('BACK_DEFAULT_REGION', $request->backblaze_default_region);
        $this->updateEnvFile('BACK_BUCKET', $request->backblaze_bucket);
        $this->updateEnvFile('BACK_ENDPOINT', $request->backblaze_end_point);

        // Page redirect
        return redirect()->route('admin.backblaze.settings')->with('success', trans('Configurations 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;
        }
    }
}
