<?php
// File: admin/sync_google_review.php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

require_once '../includes/security.php';
secureSessionStart();

if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    header("Location: login.php"); exit;
}

require_once '../includes/db_connect.php';
require_once '../includes/cache.php';
require_once '../includes/functions.php';

$success = '';
$error   = '';

// ----------------------------------------------------------------
// Simpan API Key + Place ID (via POST form settings)
// ----------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_config') {
    verifyCsrf();
    $apiKey  = sanitizeInput($_POST['google_places_api_key'] ?? '', 255);
    $placeId = sanitizeInput($_POST['google_place_id']       ?? '', 100);
    try {
        $pdo->prepare("
            UPDATE config_cabang
            SET google_places_api_key = ?,
                google_place_id       = ?
            WHERE id = 1
        ")->execute([$apiKey, $placeId]);
        cacheFlush();
        $success = 'Konfigurasi Google Review berhasil disimpan.';
    } catch (Exception $e) {
        // Cek apakah kolom belum ada
        if (strpos($e->getMessage(), "Unknown column") !== false) {
            $error = 'Kolom database belum tersedia. Jalankan <strong>migrate_add_google_review.sql</strong> di phpMyAdmin terlebih dahulu.';
        } else {
            $error = 'Gagal menyimpan: ' . htmlspecialchars($e->getMessage());
        }
    }
}

// ----------------------------------------------------------------
// Ambil konfigurasi + statistik
// ----------------------------------------------------------------
$config       = getConfig($pdo);
$apiKey       = '';
$placeId      = '';
$lastSync     = null;
$reviewStats  = ['total' => 0, 'google' => 0, 'pending' => 0];
$migrated     = true;

try {
    $row = $pdo->query("SELECT google_places_api_key, google_place_id, google_review_last_sync FROM config_cabang LIMIT 1")->fetch();
    $apiKey   = $row['google_places_api_key'] ?? '';
    $placeId  = $row['google_place_id']        ?? '';
    $lastSync = $row['google_review_last_sync'] ?? null;
} catch (Exception $e) {
    $migrated = false;
}

if ($migrated) {
    try {
        $stats = $pdo->query("
            SELECT
                COUNT(*) AS total,
                SUM(source = 'google') AS google,
                SUM(source = 'google' AND is_visible = 0) AS pending
            FROM testimoni
        ")->fetch();
        $reviewStats = [
            'total'   => (int)($stats['total']   ?? 0),
            'google'  => (int)($stats['google']  ?? 0),
            'pending' => (int)($stats['pending'] ?? 0),
        ];
    } catch (Exception $e) {
        $migrated = false;
    }
}

// Review Google yang sudah masuk (untuk tabel preview)
$googleReviews = [];
if ($migrated) {
    try {
        $googleReviews = $pdo->query("
            SELECT id, nama_customer, isi_testimoni, rating, is_visible,
                   tanggal_serah_terima, reviewer_photo_url, created_at
            FROM testimoni
            WHERE source = 'google'
            ORDER BY created_at DESC
            LIMIT 20
        ")->fetchAll();
    } catch (Exception $e) {}
}

$page_title = 'Sinkronisasi Google Review';
require 'includes/header.php';
?>

<main class="flex-1 overflow-y-auto p-4 md:p-8 bg-gray-50 w-full">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-3">
        <div>
            <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                <i class="fa-brands fa-google text-blue-500"></i> Sinkronisasi Google Review
            </h1>
            <p class="text-sm text-gray-500 mt-1">Tarik review dari Google Maps secara otomatis ke sistem testimoni</p>
        </div>
        <a href="crud_testimoni.php" class="flex items-center gap-2 text-gray-600 hover:text-gray-800 font-bold text-sm px-4 py-2 rounded-lg hover:bg-gray-200 transition border border-gray-300">
            <i class="fa-solid fa-comments"></i> Kelola Testimoni
        </a>
    </div>

    <?php if (!$migrated): ?>
    <!-- BANNER: Migrasi belum dilakukan -->
    <div class="bg-amber-50 border-2 border-amber-400 rounded-2xl p-6 mb-6">
        <div class="flex items-start gap-4">
            <div class="w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center flex-shrink-0">
                <i class="fa-solid fa-triangle-exclamation text-amber-600 text-xl"></i>
            </div>
            <div>
                <h3 class="font-bold text-amber-800 text-lg mb-1">Migrasi Database Diperlukan</h3>
                <p class="text-amber-700 text-sm mb-4">Sebelum menggunakan fitur ini, jalankan file SQL berikut di <strong>phpMyAdmin → Import</strong>:</p>
                <div class="bg-white border border-amber-200 rounded-xl p-4 font-mono text-sm text-amber-900 mb-4">
                    📄 <strong>migrate_add_google_review.sql</strong>
                    <span class="text-amber-500 text-xs ml-2">(ada di root folder website)</span>
                </div>
                <p class="text-amber-600 text-xs">File ini hanya perlu dijalankan sekali. Setelah itu refresh halaman ini.</p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="bg-green-50 border border-green-200 text-green-700 p-4 rounded-xl mb-6 flex items-center gap-2">
        <i class="fa-solid fa-circle-check"></i> <?= $success ?>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div class="bg-red-50 border border-red-200 text-red-700 p-4 rounded-xl mb-6 flex items-start gap-2">
        <i class="fa-solid fa-circle-exclamation mt-0.5 flex-shrink-0"></i>
        <div><?= $error ?></div>
    </div>
    <?php endif; ?>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        <!-- ====================================================
             KOLOM KIRI: Konfigurasi + Tombol Sync
             ==================================================== -->
        <div class="lg:col-span-1 space-y-6">

            <!-- Stat Cards -->
            <div class="grid grid-cols-3 gap-3">
                <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 text-center">
                    <div class="text-2xl font-black text-gray-800"><?= $reviewStats['total'] ?></div>
                    <div class="text-xs text-gray-400 mt-0.5">Total</div>
                </div>
                <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 text-center">
                    <div class="text-2xl font-black text-blue-600"><?= $reviewStats['google'] ?></div>
                    <div class="text-xs text-gray-400 mt-0.5">Google</div>
                </div>
                <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 text-center">
                    <div class="text-2xl font-black text-amber-500"><?= $reviewStats['pending'] ?></div>
                    <div class="text-xs text-gray-400 mt-0.5">Pending</div>
                </div>
            </div>

            <!-- Konfigurasi API -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="p-5 border-b border-gray-100">
                    <h3 class="font-bold text-gray-800 flex items-center gap-2">
                        <i class="fa-solid fa-key text-blue-500"></i> Konfigurasi API
                    </h3>
                </div>
                <form method="POST" class="p-5 space-y-4">
                    <?= csrfInput() ?>
                    <input type="hidden" name="action" value="save_config">

                    <div>
                        <label class="block text-xs font-bold text-gray-500 uppercase mb-1.5">
                            Google Places API Key
                        </label>
                        <input type="text" name="google_places_api_key"
                               value="<?= htmlspecialchars($apiKey) ?>"
                               placeholder="AIzaSy..."
                               class="w-full p-3 rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-blue-400 outline-none transition"
                               <?= !$migrated ? 'disabled' : '' ?>>
                        <p class="text-xs text-gray-400 mt-1">
                            Buat di <a href="https://console.cloud.google.com" target="_blank" class="text-blue-500 hover:underline">console.cloud.google.com</a>
                            → aktifkan <strong>Places API</strong>
                        </p>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-gray-500 uppercase mb-1.5">
                            Google Place ID
                        </label>
                        <input type="text" name="google_place_id"
                               value="<?= htmlspecialchars($placeId) ?>"
                               placeholder="ChIJ..."
                               class="w-full p-3 rounded-xl border border-gray-200 text-sm focus:ring-2 focus:ring-blue-400 outline-none transition"
                               <?= !$migrated ? 'disabled' : '' ?>>
                        <p class="text-xs text-gray-400 mt-1">
                            Cara dapat Place ID: lihat panduan di bawah ↓
                        </p>
                    </div>

                    <button type="submit" <?= !$migrated ? 'disabled' : '' ?>
                        class="w-full py-3 rounded-xl font-bold transition text-sm
                               <?= $migrated ? 'bg-blue-600 text-white hover:bg-blue-700 active:scale-95' : 'bg-gray-200 text-gray-400 cursor-not-allowed' ?>">
                        <i class="fa-solid fa-save mr-1"></i> Simpan Konfigurasi
                    </button>
                </form>
            </div>

            <!-- Tombol Sync -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
                <h3 class="font-bold text-gray-800 mb-1 flex items-center gap-2">
                    <i class="fa-solid fa-rotate text-green-500"></i> Sinkronisasi Sekarang
                </h3>
                <?php if ($lastSync): ?>
                <p class="text-xs text-gray-400 mb-4">
                    Terakhir sync: <?= date('d M Y, H:i', strtotime($lastSync)) ?> WIB
                </p>
                <?php else: ?>
                <p class="text-xs text-gray-400 mb-4">Belum pernah sync.</p>
                <?php endif; ?>

                <p class="text-xs text-gray-500 mb-4 leading-relaxed">
                    Google Places API mengembalikan <strong>maksimal 5 review terbaru</strong>.
                    Review baru akan masuk dengan status <span class="bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded font-bold">Pending</span> dan perlu disetujui sebelum tampil.
                </p>

                <button id="btn-sync" onclick="doSync()"
                    class="w-full py-3 rounded-xl font-bold text-sm transition
                           <?= ($migrated && !empty($apiKey) && !empty($placeId))
                               ? 'bg-green-600 text-white hover:bg-green-700 active:scale-95'
                               : 'bg-gray-200 text-gray-400 cursor-not-allowed' ?>"
                    <?= (!$migrated || empty($apiKey) || empty($placeId)) ? 'disabled' : '' ?>>
                    <i class="fa-solid fa-rotate mr-1"></i> Tarik Review dari Google
                </button>

                <div id="sync-result" class="hidden mt-4 p-4 rounded-xl text-sm"></div>
            </div>
        </div>

        <!-- ====================================================
             KOLOM KANAN: Review yang Sudah Masuk + Panduan
             ==================================================== -->
        <div class="lg:col-span-2 space-y-6">

            <!-- Tabel review Google yang sudah masuk -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <div class="p-5 border-b border-gray-100 flex justify-between items-center">
                    <h3 class="font-bold text-gray-800 flex items-center gap-2">
                        <i class="fa-brands fa-google text-blue-500"></i>
                        Review dari Google (<?= count($googleReviews) ?>)
                    </h3>
                    <?php if (!empty($googleReviews)): ?>
                    <a href="crud_testimoni.php" class="text-xs text-blue-500 hover:underline font-semibold">
                        Kelola semua →
                    </a>
                    <?php endif; ?>
                </div>

                <?php if (empty($googleReviews)): ?>
                <div class="flex flex-col items-center justify-center py-14 text-center">
                    <div class="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                        <i class="fa-brands fa-google text-2xl text-gray-300"></i>
                    </div>
                    <p class="text-gray-400 text-sm">Belum ada review Google yang diimpor.</p>
                    <p class="text-gray-300 text-xs mt-1">Klik "Tarik Review dari Google" untuk memulai.</p>
                </div>
                <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-gray-50 text-gray-500 text-xs uppercase border-b border-gray-100">
                            <tr>
                                <th class="py-3 px-4 text-left">Reviewer</th>
                                <th class="py-3 px-4 text-left">Ulasan</th>
                                <th class="py-3 px-4 text-center">Rating</th>
                                <th class="py-3 px-4 text-center">Status</th>
                                <th class="py-3 px-4 text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                        <?php foreach ($googleReviews as $r):
                            $stars = '';
                            for ($i = 1; $i <= 5; $i++) {
                                $stars .= $i <= $r['rating']
                                    ? '<i class="fa-solid fa-star text-yellow-400 text-xs"></i>'
                                    : '<i class="fa-regular fa-star text-gray-300 text-xs"></i>';
                            }
                            $photo = !empty($r['reviewer_photo_url'])
                                ? htmlspecialchars($r['reviewer_photo_url'])
                                : 'https://ui-avatars.com/api/?name=' . urlencode($r['nama_customer'] ?? 'G') . '&size=80&background=4285F4&color=ffffff&bold=true';
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="py-3 px-4">
                                <div class="flex items-center gap-2">
                                    <img src="<?= $photo ?>" alt="<?= htmlspecialchars($r['nama_customer'] ?? '') ?>"
                                         class="w-8 h-8 rounded-full object-cover border border-gray-200"
                                         onerror="this.src='https://ui-avatars.com/api/?name=G&size=80&background=4285F4&color=fff'">
                                    <div>
                                        <div class="font-semibold text-gray-800 text-xs"><?= htmlspecialchars($r['nama_customer'] ?? 'Anonim') ?></div>
                                        <div class="text-gray-400 text-[10px]"><?= date('d M Y', strtotime($r['tanggal_serah_terima'])) ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="py-3 px-4 max-w-xs">
                                <p class="text-gray-600 text-xs line-clamp-2">
                                    <?= htmlspecialchars(mb_substr($r['isi_testimoni'] ?? '-', 0, 120)) ?>
                                    <?= mb_strlen($r['isi_testimoni'] ?? '') > 120 ? '...' : '' ?>
                                </p>
                            </td>
                            <td class="py-3 px-4 text-center">
                                <div class="flex justify-center"><?= $stars ?></div>
                            </td>
                            <td class="py-3 px-4 text-center">
                                <?php if ($r['is_visible']): ?>
                                <span class="bg-green-100 text-green-700 text-xs font-bold px-2 py-1 rounded-full">Tampil</span>
                                <?php else: ?>
                                <span class="bg-amber-100 text-amber-700 text-xs font-bold px-2 py-1 rounded-full">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-4 text-center">
                                <a href="crud_testimoni.php"
                                   class="text-blue-500 hover:text-blue-700 text-xs font-semibold">
                                    Edit
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>

            <!-- Panduan cara dapat API Key + Place ID -->
            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <button onclick="toggleGuide()" class="w-full p-5 text-left flex justify-between items-center">
                    <h3 class="font-bold text-gray-800 flex items-center gap-2">
                        <i class="fa-solid fa-book text-indigo-500"></i> Panduan: Cara Mendapatkan API Key & Place ID
                    </h3>
                    <i class="fa-solid fa-chevron-down text-gray-400 transition-transform" id="guide-chevron"></i>
                </button>
                <div id="guide-content" class="hidden border-t border-gray-100">
                    <div class="p-5 space-y-6 text-sm">

                        <!-- Step 1: API Key -->
                        <div>
                            <div class="flex items-center gap-2 mb-3">
                                <div class="w-7 h-7 rounded-full bg-blue-600 text-white flex items-center justify-center text-xs font-black flex-shrink-0">1</div>
                                <h4 class="font-bold text-gray-800">Buat Google Places API Key</h4>
                            </div>
                            <ol class="space-y-2 text-gray-600 text-xs pl-9 list-decimal">
                                <li>Buka <a href="https://console.cloud.google.com" target="_blank" rel="noopener" class="text-blue-500 hover:underline font-semibold">console.cloud.google.com</a></li>
                                <li>Buat Project baru atau pilih project yang sudah ada</li>
                                <li>Di menu kiri → <strong>APIs &amp; Services → Library</strong></li>
                                <li>Cari <strong>"Places API"</strong> → klik → klik <strong>Enable</strong></li>
                                <li>Di menu kiri → <strong>Credentials → Create Credentials → API Key</strong></li>
                                <li>Salin API Key yang muncul → paste ke kolom di atas</li>
                                <li><em class="text-gray-400">Opsional tapi disarankan: batasi API Key hanya untuk Places API dan domain hosting Willie</em></li>
                            </ol>
                            <div class="mt-3 bg-blue-50 border border-blue-100 rounded-xl p-3 text-xs text-blue-700">
                                💡 <strong>Kuota gratis:</strong> Google memberikan $200 kredit gratis per bulan. Dengan pemakaian normal (sync beberapa kali sehari), ini tidak akan terlampaui.
                            </div>
                        </div>

                        <!-- Step 2: Place ID -->
                        <div>
                            <div class="flex items-center gap-2 mb-3">
                                <div class="w-7 h-7 rounded-full bg-green-600 text-white flex items-center justify-center text-xs font-black flex-shrink-0">2</div>
                                <h4 class="font-bold text-gray-800">Dapatkan Place ID Bisnis</h4>
                            </div>
                            <p class="text-gray-500 text-xs mb-3 pl-9">Place ID adalah kode unik Google untuk setiap bisnis di Maps.</p>
                            <ol class="space-y-2 text-gray-600 text-xs pl-9 list-decimal">
                                <li>Buka <a href="https://maps.google.com" target="_blank" rel="noopener" class="text-blue-500 hover:underline font-semibold">Google Maps</a></li>
                                <li>Cari nama dealer di kolom pencarian (contoh: "Tunas Toyota Ciputat")</li>
                                <li>Klik hasil yang muncul di peta</li>
                                <li>Lihat URL di browser — di akhir URL ada bagian seperti:
                                    <code class="bg-gray-100 px-2 py-0.5 rounded ml-1 text-gray-700">1s0x2e69ef31459bda4f</code>
                                </li>
                                <li>Atau pakai <a href="https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder" target="_blank" rel="noopener" class="text-blue-500 hover:underline font-semibold">Place ID Finder resmi Google</a> — lebih mudah</li>
                                <li>Place ID format: <code class="bg-gray-100 px-2 py-0.5 rounded text-gray-700">ChIJ5xS5QTjh1ToR...</code> (diawali "ChIJ")</li>
                            </ol>
                        </div>

                        <!-- Step 3: Catatan penting -->
                        <div>
                            <div class="flex items-center gap-2 mb-3">
                                <div class="w-7 h-7 rounded-full bg-amber-500 text-white flex items-center justify-center text-xs font-black flex-shrink-0">!</div>
                                <h4 class="font-bold text-gray-800">Catatan Penting</h4>
                            </div>
                            <ul class="space-y-1.5 text-gray-600 text-xs pl-9 list-disc">
                                <li>Google Places API hanya mengembalikan <strong>maksimal 5 review terbaru</strong> — ini kebijakan Google, tidak bisa diubah</li>
                                <li>Review yang ditarik masuk dengan status <strong>Pending</strong> — perlu disetujui di menu Testimoni sebelum tampil di website</li>
                                <li>Akun Google My Business dealer tidak perlu dimiliki Willie — cukup Place ID yang benar</li>
                                <li>Sync bisa dilakukan berkali-kali, review yang sudah ada tidak akan duplikat</li>
                            </ul>
                        </div>

                    </div>
                </div>
            </div>

        </div>
    </div>

</main>

<script>
function toggleGuide() {
    const content  = document.getElementById('guide-content');
    const chevron  = document.getElementById('guide-chevron');
    const isHidden = content.classList.toggle('hidden');
    chevron.style.transform = isHidden ? 'rotate(0deg)' : 'rotate(180deg)';
}

async function doSync() {
    const btn    = document.getElementById('btn-sync');
    const result = document.getElementById('sync-result');
    const origHtml = btn.innerHTML;

    btn.disabled  = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-1"></i> Menarik review dari Google...';
    result.className = 'hidden mt-4 p-4 rounded-xl text-sm';
    result.innerHTML = '';

    try {
        const fd = new FormData();
        fd.append('csrf_token', '<?= htmlspecialchars(csrfToken()) ?>');

        const res  = await fetch('do_sync_google_review.php', { method: 'POST', body: fd });
        const text = await res.text();
        let data;
        try {
            data = JSON.parse(text);
        } catch(e) {
            throw new Error('Respons server tidak valid. Cek error_log hosting.');
        }

        if (data.success) {
            let html = `<div class="font-bold text-green-700 mb-1">
                <i class="fa-solid fa-circle-check mr-1"></i> Berhasil!
            </div>
            <p class="text-green-700">${data.message}</p>`;

            if (data.place_name) {
                html += `<div class="mt-3 pt-3 border-t border-green-200 text-green-600 text-xs space-y-1">
                    <div><strong>Bisnis:</strong> ${data.place_name}</div>
                    ${data.place_rating ? `<div><strong>Rating Google:</strong> ${data.place_rating} ⭐ (${data.total_reviews} review)</div>` : ''}
                    <div><strong>Review diambil:</strong> ${data.total_fetched} dari Google</div>
                </div>`;
            }

            if (data.inserted > 0) {
                html += `<div class="mt-3">
                    <a href="crud_testimoni.php" class="inline-flex items-center gap-1 text-xs font-semibold text-green-700 underline">
                        Approve review di menu Testimoni →
                    </a>
                </div>`;
            }

            result.className = 'mt-4 p-4 rounded-xl text-sm bg-green-50 border border-green-200';
            result.innerHTML = html;

            // Reload setelah 2 detik untuk update tabel
            if (data.inserted > 0) {
                setTimeout(() => window.location.reload(), 2000);
            }
        } else {
            result.className = 'mt-4 p-4 rounded-xl text-sm bg-red-50 border border-red-200';
            result.innerHTML = `<div class="font-bold text-red-700 mb-1">
                <i class="fa-solid fa-circle-exclamation mr-1"></i> Gagal
            </div>
            <p class="text-red-700">${data.message}</p>`;
        }
    } catch(err) {
        result.className = 'mt-4 p-4 rounded-xl text-sm bg-red-50 border border-red-200';
        result.innerHTML = `<div class="font-bold text-red-700 mb-1">Error</div>
            <p class="text-red-700">${err.message}</p>`;
    } finally {
        btn.disabled  = false;
        btn.innerHTML = origHtml;
    }
}
</script>

<?php require_once 'includes/footer.php'; ?>