<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="row">
    <!-- Header -->
    <div class="col-12 mb-4">
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <h4 class="fw-bold text-dark mb-1">Pengaturan Penyimpanan File</h4>
                <span class="text-muted small">Hubungkan penyimpanan media aplikasi SIMAK langsung ke Google Drive Cloud (OAuth 2.0).</span>
            </div>
        </div>
    </div>

    <!-- Alert Status -->
    <?php if (session()->getFlashdata('success')): ?>
        <div class="col-12 mb-3">
            <div class="alert alert-success alert-dismissible fade show border-0 shadow-sm" role="alert">
                <i class="bi bi-check-circle-fill me-2"></i><?= session()->getFlashdata('success') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('error')): ?>
        <div class="col-12 mb-3">
            <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm" role="alert">
                <i class="bi bi-exclamation-triangle-fill me-2"></i><?= session()->getFlashdata('error') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
    <?php endif; ?>

    <!-- Status Aktif Driver & Otorisasi -->
    <?php 
    $activeDriver = $setting['storage_driver'] ?? 'local';
    $hasRefreshToken = !empty($setting['google_refresh_token']);
    ?>
    <div class="col-md-4 mb-4">
        <div class="card border-0 shadow-sm h-100 rounded-3">
            <div class="card-body p-4 text-center d-flex flex-column align-items-center justify-content-center">
                <div class="mb-3">
                    <?php if ($activeDriver === 'google' && $hasRefreshToken): ?>
                        <div class="bg-primary-subtle text-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 80px; height: 80px; font-size: 2.5rem;">
                            <i class="bi bi-cloud-check-fill"></i>
                        </div>
                    <?php else: ?>
                        <div class="bg-success-subtle text-success rounded-circle d-flex align-items-center justify-content-center" style="width: 80px; height: 80px; font-size: 2.5rem;">
                            <i class="bi bi-hdd-fill"></i>
                        </div>
                    <?php endif; ?>
                </div>
                <h5 class="fw-bold text-dark mb-1">Driver Aktif Saat Ini</h5>
                <p class="text-muted small mb-3">Penyimpanan Aktif:</p>
                <div class="mb-3">
                    <?php if ($activeDriver === 'google'): ?>
                        <span class="badge bg-primary fs-6 px-4 py-2 rounded-pill shadow-sm">
                            <i class="bi bi-google me-1"></i> Google Drive Cloud
                        </span>
                    <?php else: ?>
                        <span class="badge bg-success fs-6 px-4 py-2 rounded-pill shadow-sm">
                            <i class="bi bi-folder-fill me-1"></i> Lokal (Hosting Server)
                        </span>
                    <?php endif; ?>
                </div>

                <div class="border-top pt-3 w-100 mt-2">
                    <h6 class="fw-bold text-dark mb-2">Status Otorisasi Google:</h6>
                    <?php if ($hasRefreshToken): ?>
                        <span class="badge bg-success-subtle text-success border border-success border-opacity-25 px-3 py-2 fs-7 rounded-3">
                            <i class="bi bi-shield-fill-check me-1"></i> Terhubung (Token Valid)
                        </span>
                    <?php else: ?>
                        <span class="badge bg-danger-subtle text-danger border border-danger border-opacity-25 px-3 py-2 fs-7 rounded-3">
                            <i class="bi bi-shield-fill-x me-1"></i> Belum Terhubung
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Form Pengaturan -->
    <div class="col-md-8 mb-4">
        <div class="card border-0 shadow-sm h-100 rounded-3">
            <div class="card-header bg-white py-3 border-0">
                <h6 class="fw-bold text-dark m-0"><i class="bi bi-gear-fill text-primary me-2"></i>Konfigurasi Akses Google Drive</h6>
            </div>
            <div class="card-body px-4 pb-4 pt-2">
                <form method="POST" action="/settings/storage/save">
                    <input type="hidden" name="action" value="save">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold text-secondary">Pilih Media Penyimpanan</label>
                        <select name="storage_driver" id="storageDriverSelect" class="form-select form-select-lg" required>
                            <option value="local" <?= $activeDriver === 'local' ? 'selected' : '' ?>>Lokal (Simpan di Folder Server Hosting)</option>
                            <option value="google" <?= $activeDriver === 'google' ? 'selected' : '' ?>>Google Drive (Simpan di Cloud Google Drive)</option>
                        </select>
                        <div class="form-text small text-muted">
                            Pilih Google Drive jika Anda ingin file-file foto dan media disimpan langsung di Drive sekolah klien Anda.
                        </div>
                    </div>

                    <!-- Panel Konfigurasi Google Drive (Ditampilkan hanya jika driver = google) -->
                    <div id="googleDrivePanel" style="display: none;">
                        <div class="border-top pt-3 mt-3">
                            <div class="mb-3">
                                <label class="form-label fw-bold text-secondary">Google OAuth Client ID</label>
                                <input type="text" name="google_client_id" class="form-control font-monospace" style="font-size: 13px;"
                                       value="<?= esc($setting['google_client_id'] ?? '') ?>"
                                       placeholder="1234567890-abcdefg.apps.googleusercontent.com">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label fw-bold text-secondary">Google OAuth Client Secret</label>
                                <input type="password" name="google_client_secret" class="form-control font-monospace" style="font-size: 13px;"
                                       value="<?= esc($setting['google_client_secret'] ?? '') ?>"
                                       placeholder="••••••••••••••••••••••••">
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-bold text-secondary">Google Drive Folder ID</label>
                                <input type="text" name="google_drive_folder_id" class="form-control" 
                                       value="<?= esc($setting['google_drive_folder_id'] ?? '') ?>"
                                       placeholder="Contoh: 1a2b3c4d5e6f7g8h9i0j...">
                                <div class="form-text small text-muted">
                                    Masukkan ID Folder Google Drive tempat menyimpan file media (dilihat dari URL browser saat membuka folder).
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4 border-top pt-3 d-flex align-items-center justify-content-between">
                        <div>
                            <!-- Tombol Koneksi OAuth -->
                            <?php if ($activeDriver === 'google'): ?>
                                <?php if ($hasRefreshToken): ?>
                                    <button type="submit" name="action" value="disconnect" class="btn btn-outline-danger rounded-pill px-3">
                                        <i class="bi bi-link-45deg me-1"></i> Putuskan Koneksi Google Drive
                                    </button>
                                <?php else: ?>
                                    <a href="/settings/storage/oauth" class="btn btn-primary rounded-pill px-3 shadow-sm">
                                        <i class="bi bi-google me-1"></i> Hubungkan ke Google Drive
                                    </a>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        <button type="submit" class="btn btn-dark rounded-pill px-4">
                            <i class="bi sm-save me-1"></i> Simpan Konfigurasi
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Panduan Google Drive -->
    <div class="col-12">
        <div class="card border-0 shadow-sm rounded-3">
            <div class="card-header bg-white py-3 border-0 d-flex align-items-center justify-content-between">
                <h6 class="fw-bold text-dark m-0">
                    <i class="bi bi-book-half text-warning me-2"></i>Panduan Konfigurasi Integrasi Google Drive (OAuth 2.0)
                </h6>
                <button class="btn btn-sm btn-outline-secondary rounded-pill" type="button" data-bs-toggle="collapse" data-bs-target="#panduanCollapse">
                    <i class="bi bi-chevron-expand"></i> Buka/Tutup Panduan
                </button>
            </div>
            <div id="panduanCollapse" class="collapse show">
                <div class="card-body px-4 pb-4 pt-0 text-dark" style="font-size: 14px; line-height: 1.6;">
                    <div class="row g-4 border-top pt-3">
                        <div class="col-md-6">
                            <h6 class="fw-bold text-primary mb-2">A. Membuat Google OAuth Client ID & Client Secret</h6>
                            <ol class="ps-3 mb-4" style="font-size: 13px;">
                                <li>Buka halaman resmi <a href="https://console.cloud.google.com/" target="_blank" class="fw-bold">Google Cloud Console</a>.</li>
                                <li>Buat project baru dengan mengeklik menu dropdown di kiri atas, klik <strong>New Project</strong>. Isi Project Name dengan <strong>"SIMAK"</strong>, lalu klik <strong>Create</strong>.</li>
                                <li>Pastikan project aktif Anda adalah <strong>SIMAK</strong>. Buka menu pencarian di atas atau cari menu <strong>APIs & Services</strong> > <strong>Library</strong>. Cari <strong>"Google Drive API"</strong>, lalu klik tombol <strong>Enable (Aktifkan)</strong>.</li>
                                <li>Buka menu <strong>APIs & Services</strong> > <strong>OAuth Consent Screen</strong>:
                                    <ul class="ps-3 mb-2">
                                        <li>Pilih <strong>User Type: External</strong> (untuk pengguna Gmail gratisan), lalu klik <strong>Create</strong>.</li>
                                        <li>Isi App Information: App Name diisi <strong>"SIMAK APP"</strong> dan isi User Support Email dengan email Gmail Anda.</li>
                                        <li>Isi Developer Contact Information di bagian bawah dengan email Gmail Anda yang sama, klik <strong>Save and Continue</strong>.</li>
                                        <li>Di tab <strong>Scopes</strong>, Anda bisa langsung klik <strong>Save and Continue</strong> (tidak perlu menambahkan scope secara manual karena aplikasi akan memintanya secara otomatis).</li>
                                    </ul>
                                </li>
                                <li>Buka menu <strong>APIs & Services</strong> > <strong>Credentials</strong> di sebelah kiri:
                                    <ul class="ps-3 mb-2">
                                        <li>Klik tombol <strong>+ Create Credentials</strong> di bagian atas, pilih <strong>OAuth Client ID</strong>.</li>
                                        <li>Pilih Application Type: <strong>Web Application</strong>.</li>
                                        <li>Scroll ke bawah ke bagian <strong>Authorized Redirect URIs</strong>, klik tombol <strong>+ ADD URI</strong>, lalu tempelkan alamat URL callback dinamis di bawah ini:<br>
                                            <code class="bg-light p-1 border rounded text-danger text-break d-block mt-1"><?= base_url('settings/storage/oauth-callback') ?></code>
                                        </li>
                                    </ul>
                                </li>
                                <li>Klik tombol <strong>Create</strong> di bawah.</li>
                                <li>Pada tabel <strong>OAuth 2.0 Client IDs</strong> yang baru dibuat, klik <strong>ikon pensil (Edit)</strong> di sebelah kanan.</li>
                                <li>Di sisi kanan atas halaman tersebut, cari dan salin **Client ID** dan **Client Secret**, kemudian tempelkan (paste) ke kolom form di atas.</li>
                            </ol>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="fw-bold text-primary mb-2">B. Mendaftarkan Test User (Gmail Pengguna)</h6>
                            <div class="alert alert-warning border-0 bg-warning-subtle py-2 px-3 rounded text-dark small mb-3">
                                <i class="bi bi-exclamation-triangle-fill me-1"></i><strong>Penting:</strong> Karena aplikasi kita berstatus "Testing" di Google Developer, hanya email terdaftar di bawah ini saja yang diperbolehkan untuk login/menghubungkan Drive.
                            </div>
                            <ol class="ps-3 mb-4" style="font-size: 13px;">
                                <li>Kembali ke menu <strong>APIs & Services</strong> > <strong>OAuth Consent Screen</strong> di Google Console.</li>
                                <li>Scroll ke bagian paling bawah ke bagian panel <strong>Test Users</strong>.</li>
                                <li>Klik tombol <strong>+ ADD USERS</strong>.</li>
                                <li>Masukkan alamat email Gmail yang akan Anda gunakan untuk menyimpan data Google Drive (email sekolah/madrasah).</li>
                                <li>Klik <strong>Save</strong>. Pastikan email tersebut kini sudah muncul terdaftar di dalam tabel.</li>
                            </ol>

                            <h6 class="fw-bold text-primary mb-2">C. Menghubungkan Akun & Folder Google Drive</h6>
                            <ol class="ps-3 mb-3" style="font-size: 13px;">
                                <li>Buka akun <a href="https://drive.google.com/" target="_blank" class="fw-bold">Google Drive</a> Anda (menggunakan email Gmail yang didaftarkan pada bagian B).</li>
                                <li>Buat folder baru khusus di Drive Anda (misal nama folder: <code>Penyimpanan SIMAK</code>).</li>
                                <li>Buka folder tersebut, lalu salin string karakter kode unik setelah kata <code>/folders/</code> pada URL browser Anda.<br>
                                    <em>(Contoh URL: <code>drive.google.com/drive/folders/1ekTfQOlSMI17pl...</code>, maka Folder ID-nya adalah <code>1ekTfQOlSMI17pl...</code>)</em>.
                                </li>
                                <li>Tempelkan Folder ID tersebut ke kolom **Google Drive Folder ID** pada form di atas.</li>
                                <li>Klik tombol hitam **"Simpan Konfigurasi"** di atas.</li>
                                <li>Setelah konfigurasi tersimpan, klik tombol biru **"Hubungkan ke Google Drive"** yang muncul di kiri bawah.</li>
                                <li>Selesaikan login Google Anda. Pada peringatan keamanan Google, klik **Advanced (Lanjutan)** > klik **Buka SIMAK APP (tidak aman) / Go to SIMAK APP (unsafe)**.</li>
                                <li>Centang izin akses mengelola file Google Drive, lalu klik **Lanjutkan / Izinkan**. Halaman akan otomatis kembali ke SIMAK dengan status **Terhubung**.</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const driverSelect = document.getElementById('storageDriverSelect');
        const googlePanel = document.getElementById('googleDrivePanel');

        function togglePanel() {
            if (driverSelect.value === 'google') {
                googlePanel.style.display = 'block';
            } else {
                googlePanel.style.display = 'none';
            }
        }

        driverSelect.addEventListener('change', togglePanel);
        togglePanel(); // Trigger saat load halaman
    });
</script>

<?= $this->endSection() ?>
