<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Hash, Log, File, Artisan};
use Illuminate\Support\Str;

class AdminController extends Controller
{
    public function index()
    {
        // Menggunakan session bawaan untuk cek login
        if (!session('admin_logged_in')) {
            return redirect()->route('admin.login');
        }
        return view('admin.dashboard');
    }

    public function showLogin() {
        if (session('admin_logged_in')) {
            return redirect()->route('admin.dashboard');
        }
        return view('admin.login');
    }

    public function login(Request $request) {
        $inputPassword = $request->password;
        $storedHash = env('ADMIN_PASSWORD');

        try {
            // Memastikan hash diawali dengan format Bcrypt
            if ($storedHash && str_starts_with($storedHash, '$2y$')) {
                if (Hash::check($inputPassword, $storedHash)) {
                    session(['admin_logged_in' => true]);
                    // Simpan session secara manual ke disk agar tidak hilang saat env berubah
                    session()->save(); 
                    return redirect()->route('admin.dashboard');
                }
            }
        } catch (\Exception $e) { 
            return back()->withErrors(['msg' => 'Login Error: ' . $e->getMessage()]); 
        }

        return back()->withErrors(['msg' => 'Password salah!']);
    }

    public function logout() {
        session()->forget('admin_logged_in');
        return redirect()->route('admin.login');
    }

    /**
     * Route dinamis manifest tanpa file fisik
     */
    public function manifest()
    {
        return response()->json([
            "name" => env('PWA_NAME', 'Dramasubs'),
            "short_name" => env('PWA_SHORT_NAME', 'Dramasubs'),
            "start_url" => "/",
            "background_color" => env('PWA_BG_COLOR', '#000000'),
            "display" => "fullscreen",
            "description" => env('PWA_DESCRIPTION', 'Nonton Drama Pendek Gratis'),
            "theme_color" => env('PWA_THEME_COLOR', '#000000'),
            "icons" => [
                ["src" => env('FAVICON_URL', '/images/logo-s.png'), "sizes" => "512x512", "type" => "image/png"]
            ]
        ]);
    }

    public function update(Request $request)
    {
        if (!session('admin_logged_in')) return abort(403);

        $data = $request->except(['_token', 'footer_script']);
        
        // Simpan Footer Script dalam Base64
        $data['FOOTER_SCRIPT'] = base64_encode($request->input('footer_script', ''));

        // Mapping KEY ASLI Iklan & PWA
        $keys = [
            'FLOATING_IMAGE_URL_LEFT', 'FLOATING_TARGET_LINK_LEFT',
            'FLOATING_IMAGE_URL_RIGHT', 'FLOATING_TARGET_LINK_RIGHT',
            'PWA_SHORT_NAME', 'PWA_DESCRIPTION', 'PWA_THEME_COLOR', 'PWA_BG_COLOR'
        ];
        foreach ($keys as $key) {
            $data[$key] = $request->input($key);
        }

        // Branding Assets handling
        $brandingFields = ['LOGO_BIG_URL', 'LOGO_SM_URL', 'FAVICON_URL', 'OG_IMAGE'];
        foreach ($brandingFields as $field) {
            if ($request->hasFile($field . '_FILE')) {
                $file = $request->file($field . '_FILE');
                $filename = Str::slug($field) . '_' . time() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('uploads/branding'), $filename);
                $data[$field] = '/uploads/branding/' . $filename;
            }
            unset($data[$field . '_FILE']);
        }

        // Switch Booleans
        $booleans = ['SHOW_BANNER', 'ADS_HOME', 'FLOATING_ADS', 'APP_DEBUG', 'MINIFY_HTML', 'VIDEO_ADS'];
        foreach ($booleans as $key) {
            $data[$key] = $request->has($key) ? 'true' : 'false';
        }

        // Update ENV
        $this->updateEnv($data);
        
        // JANGAN gunakan Artisan::call('config:clear') karena ini penyebab autologout
        
        return back()->with('success', 'Konfigurasi tersimpan tanpa logout otomatis!');
    }

    private function updateEnv(array $data)
    {
        $path = base_path('.env');
        if (!File::exists($path)) return;
        $content = File::get($path);

        foreach ($data as $key => $value) {
            $value = str_replace(["\n", "\r"], '', $value);
            // Bungkus password dengan kutip tunggal agar karakter $2y$ tidak hancur
            $safeValue = (str_contains($value, '$')) ? "'$value'" : "\"$value\"";

            if (preg_match("/^{$key}=/m", $content)) {
                $content = preg_replace("/^{$key}=.*/m", "{$key}={$safeValue}", $content);
            } else {
                $content .= "\n{$key}={$safeValue}";
            }
        }
        File::put($path, trim($content));
    }
}