@extends('layouts.app')

@section('content')
<div class="space-y-8">
    <div>
        <h1 class="text-3xl font-bold text-gray-800">Pengaturan Umum</h1>
        <p class="text-gray-500 mt-1">Kelola informasi umum, branding, dan pengaturan email untuk perusahaan kontraktor Anda.</p>
    </div>

    <div class="bg-white p-8 rounded-xl shadow-md border border-gray-200">
        
        {{-- Pesan Sukses (Update Pengaturan) --}}
        @if (session('success'))
            <div class="mb-6 bg-green-50 border-l-4 border-green-400 text-green-700 p-4 rounded-lg" role="alert">
                <p class="font-bold">{{ session('success') }}</p>
            </div>
        @endif

        {{-- [TAMBAHAN BARU] Pesan Sukses (Email Tes) --}}
        @if (session('test_success'))
            <div class="mb-6 bg-blue-50 border-l-4 border-blue-400 text-blue-700 p-4 rounded-lg" role="alert">
                <p class="font-bold">{{ session('test_success') }}</p>
            </div>
        @endif

        {{-- [TAMBAHAN BARU] Pesan Gagal (Email Tes) --}}
        @if (session('test_error'))
            <div class="mb-6 bg-red-50 border-l-4 border-red-400 text-red-700 p-4 rounded-lg" role="alert">
                <p class="font-bold">Tes Gagal!</p>
                <p class="text-sm mt-1">{{ session('test_error') }}</p>
            </div>
        @endif
        
        {{-- Pesan Error Validasi Umum (dari Simpan Pengaturan) --}}
        @if ($errors->any() && !$errors->has('test_email'))
            <div class="mb-6 bg-red-50 border-l-4 border-red-400 text-red-700 p-4 rounded-lg" role="alert">
                <p class="font-bold">Oops! Ada beberapa kesalahan:</p>
                <ul class="mt-2 list-disc list-inside text-sm">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('settings.update') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
            @csrf
            
            {{-- PENGATURAN UMUM --}}
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                {{-- Kolom Kiri: Input Form --}}
                <div class="md:col-span-2 space-y-6">
                    <div>
                        <label for="company_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Kontraktor</label>
                        <input type="text" name="company_name" id="company_name" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('company_name', $settings['company_name'] ?? '') }}" placeholder="Contoh: CV. Jaya Konstruksi">
                    </div>
                    <div>
                        <label for="company_address" class="block text-sm font-medium text-gray-700 mb-1">Alamat Perusahaan</label>
                        <textarea name="company_address" id="company_address" rows="3" class="w-full p-2 border border-gray-300 rounded-lg" placeholder="Masukkan alamat lengkap">{{ old('company_address', $settings['company_address'] ?? '') }}</textarea>
                    </div>
                    <div>
                        <label for="company_phone" class="block text-sm font-medium text-gray-700 mb-1">Nomor Telepon</label>
                        <input type="text" name="company_phone" id="company_phone" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('company_phone', $settings['company_phone'] ?? '') }}" placeholder="Contoh: 081234567890">
                    </div>
                </div>

                {{-- Kolom Kanan: Logo Upload --}}
                <div class="space-y-2">
                    <label class="block text-sm font-medium text-gray-700">Logo Perusahaan</label>
                    <div class="mt-1 flex justify-center items-center p-6 border-2 border-gray-300 border-dashed rounded-md">
                        <div class="space-y-1 text-center">
                            
                            {{-- [BAGIAN DIUBAH] --}}
                            {{-- Logika diubah untuk menambahkan ID dan memastikan preview berfungsi --}}
                            @if(isset($settings['company_logo']) && $settings['company_logo'])
                                {{-- Tampilkan logo yang ada --}}
                                <img id="logo_preview_image" src="{{ asset('storage/' . $settings['company_logo']) }}" alt="Logo saat ini" class="mx-auto max-h-24 w-auto object-contain mb-4">
                                {{-- Placeholder SVG (disembunyikan) --}}
                                <svg id="logo_preview_placeholder" class="mx-auto h-12 w-12 text-gray-400 hidden" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                    <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                </svg>
                            @else
                                {{-- Tampilkan image tag kosong (disembunyikan) untuk diisi preview --}}
                                <img id="logo_preview_image" src="" alt="Preview Logo" class="mx-auto max-h-24 w-auto object-contain mb-4 hidden">
                                {{-- Tampilkan placeholder SVG --}}
                                <svg id="logo_preview_placeholder" class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                    <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                </svg>
                            @endif
                            {{-- [AKHIR BAGIAN DIUBAH] --}}

                            <label for="company_logo" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                                {{-- [DIUBAH] Tambahkan ID untuk teks --}}
                                <span id="logo_upload_text">{{ (isset($settings['company_logo']) && $settings['company_logo']) ? 'Ganti Logo' : 'Unggah Logo' }}</span>
                                <input id="company_logo" name="company_logo" type="file" class="sr-only" accept="image/png, image/jpeg, image/jpg">
                            </label>
                            <p class="text-xs text-gray-500">PNG, JPG, JPEG hingga 1MB</p>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Pemisah --}}
            <div class="border-t border-gray-200 pt-6">
                <h2 class="text-xl font-semibold text-gray-700">Pengaturan Email (SMTP)</h2>
                <p class="text-gray-500 mt-1 text-sm">Konfigurasi server email untuk mengirim notifikasi.</p>
            </div>

            {{-- PENGATURAN SMTP BARU --}}
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="mail_mailer" class="block text-sm font-medium text-gray-700 mb-1">Mail Mailer</label>
                    <select name="mail_mailer" id="mail_mailer" class="w-full p-2 border border-gray-300 rounded-lg">
                        <option value="smtp" {{ (old('mail_mailer', $settings['mail_mailer'] ?? 'smtp') == 'smtp') ? 'selected' : '' }}>SMTP</option>
                        <option value="sendmail" {{ (old('mail_mailer', $settings['mail_mailer'] ?? '') == 'sendmail') ? 'selected' : '' }}>Sendmail</option>
                        <option value="log" {{ (old('mail_mailer', $settings['mail_mailer'] ?? '') == 'log') ? 'selected' : '' }}>Log (Testing)</option>
                    </select>
                </div>
                <div>
                    <label for="mail_host" class="block text-sm font-medium text-gray-700 mb-1">SMTP Host</label>
                    <input type="text" name="mail_host" id="mail_host" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('mail_host', $settings['mail_host'] ?? '') }}" placeholder="Contoh: smtp.mailgun.org">
                </div>
                <div>
                    <label for="mail_port" class="block text-sm font-medium text-gray-700 mb-1">SMTP Port</label>
                    <input type="text" name="mail_port" id="mail_port" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('mail_port', $settings['mail_port'] ?? '587') }}" placeholder="Contoh: 587">
                </div>
                <div>
                    <label for="mail_username" class="block text-sm font-medium text-gray-700 mb-1">SMTP Username</label>
                    <input type="text" name="mail_username" id="mail_username" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('mail_username', $settings['mail_username'] ?? '') }}" placeholder="Masukkan username email">
                </div>
                <div>
                    <label for="mail_password" class="block text-sm font-medium text-gray-700 mb-1">SMTP Password</label>
                    <input type="password" name="mail_password" id="mail_password" class="w-full p-2 border border-gray-300 rounded-lg" placeholder="Biarkan kosong jika tidak ingin mengubah">
                </div>
                <div>
                    <label for="mail_encryption" class="block text-sm font-medium text-gray-700 mb-1">Enkripsi</label>
                    <select name="mail_encryption" id="mail_encryption" class="w-full p-2 border border-gray-300 rounded-lg">
                        <option value="tls" {{ (old('mail_encryption', $settings['mail_encryption'] ?? 'tls') == 'tls') ? 'selected' : '' }}>TLS</option>
                        <option value="ssl" {{ (old('mail_encryption', $settings['mail_encryption'] ?? '') == 'ssl') ? 'selected' : '' }}>SSL</option>
                        <option value="null" {{ (old('mail_encryption', $settings['mail_encryption'] ?? '') == 'null') ? 'selected' : '' }}>None</option>
                    </select>
                </div>
                <div class="md:col-span-2">
                    <label for="mail_from_address" class="block text-sm font-medium text-gray-700 mb-1">Email Pengirim (From Address)</label>
                    <input type="email" name="mail_from_address" id="mail_from_address" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('mail_from_address', $settings['mail_from_address'] ?? '') }}" placeholder="Contoh: noreply@perusahaan.com">
                </div>
                <div class="md:col-span-2">
                    <label for="mail_from_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Pengirim (From Name)</label>
                    <input type="text" name="mail_from_name" id="mail_from_name" class="w-full p-2 border border-gray-300 rounded-lg" value="{{ old('mail_from_name', $settings['mail_from_name'] ?? $settings['company_name'] ?? '') }}" placeholder="Contoh: Admin CV. Jaya Konstruksi">
                </div>
            </div>

            {{-- Tombol Aksi (Form Utama) --}}
            <div class="flex justify-end pt-4 border-t border-gray-200 mt-6">
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-bold">Simpan Pengaturan</button>
            </div>
        </form>

        {{-- [BAGIAN DIPISAH] FORMULIR UNTUK TES EMAIL --}}
        {{-- Formulir ini dipisah dari form utama --}}
        <div class="border-t border-gray-200 pt-6 mt-6">
            <h3 class="text-lg font-medium text-gray-900">Tes Pengiriman Email</h3>
            <p class="mt-1 text-sm text-gray-500">Kirim email percobaan untuk memverifikasi pengaturan SMTP Anda. Pastikan Anda telah **menyimpan pengaturan** di atas sebelum melakukan tes.</p>
            
            <form action="{{ route('settings.test.smtp') }}" method="POST" class="mt-4 flex items-end space-x-3">
                @csrf
                <div class="flex-grow">
                    <label for="test_email" class="block text-sm font-medium text-gray-700">Email Tujuan Tes</label>
                    <input type="email" name="test_email" id="test_email" class="w-full p-2 mt-1 border border-gray-300 rounded-lg" placeholder="Masukkan email Anda..." required value="{{ old('test_email', auth()->user()->email ?? '') }}">
                    
                    {{-- [TAMBAHAN BARU] Pesan Validasi (Email Tes) --}}
                    @error('test_email')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror

                </div>
                <button type="submit" class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 font-medium">
                    Kirim Email Tes
                </button>
            </form>
        </div>
        {{-- [AKHIR BAGIAN DIPISAH] --}}

    </div>
</div>

{{-- [SCRIPT BARU UNTUK PREVIEW LOGO] --}}
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // Ambil elemen-elemen yang diperlukan
        const logoInput = document.getElementById('company_logo');
        const logoPreview = document.getElementById('logo_preview_image');
        const logoPlaceholder = document.getElementById('logo_preview_placeholder');
        const logoUploadText = document.getElementById('logo_upload_text');

        // Tambahkan event listener ke input file
        logoInput.addEventListener('change', function (event) {
            const file = event.target.files[0];

            if (file) {
                // Buat FileReader untuk membaca file
                const reader = new FileReader();

                // Saat file selesai dibaca
                reader.onload = function (e) {
                    // Set 'src' dari <img> preview dengan hasil data URL
                    logoPreview.src = e.target.result;
                    
                    // Tampilkan <img> preview
                    logoPreview.classList.remove('hidden');
                    
                    // Sembunyikan placeholder SVG
                    logoPlaceholder.classList.add('hidden');
                    
                    // Ubah teks tombol menjadi "Ganti Logo"
                    logoUploadText.textContent = 'Ganti Logo';
                };

                // Baca file sebagai Data URL (base64)
                reader.readAsDataURL(file);
            }
        });
    });
</script>
{{-- [AKHIR SCRIPT BARU] --}}

@endsection