<?php
// File: admin/do_sync_google_review.php
// AJAX endpoint — tarik review dari Google Places API lalu simpan ke tabel testimoni

ini_set('display_errors', 0);
error_reporting(E_ALL);
ob_start();

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

// Wajib login
if (!isset($_SESSION['admin_id']) || !validateAdminSession()) {
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Sesi habis, silakan login ulang.']);
    exit;
}

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

header('Content-Type: application/json');

// Hanya terima POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Method tidak valid.']);
    exit;
}

// Verifikasi CSRF
verifyCsrf();

// ----------------------------------------------------------------
// Ambil konfigurasi dari DB
// ----------------------------------------------------------------
try {
    $row = $pdo->query("SELECT google_places_api_key, google_place_id FROM config_cabang LIMIT 1")->fetch();
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Gagal baca konfigurasi: ' . $e->getMessage()]);
    exit;
}

$apiKey  = trim($row['google_places_api_key'] ?? '');
$placeId = trim($row['google_place_id']         ?? '');

if (empty($apiKey)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Google Places API Key belum diisi. Isi di menu Web Profile → bagian Google Review.']);
    exit;
}
if (empty($placeId)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Google Place ID belum diisi. Isi di menu Web Profile → bagian Google Review.']);
    exit;
}

// ----------------------------------------------------------------
// Cek cURL tersedia
// ----------------------------------------------------------------
if (!function_exists('curl_init')) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Ekstensi cURL tidak tersedia di server. Hubungi hosting untuk mengaktifkannya.']);
    exit;
}

// ----------------------------------------------------------------
// Panggil Google Places API
// ----------------------------------------------------------------
$fields  = 'reviews,name,rating,user_ratings_total';
$url     = "https://maps.googleapis.com/maps/api/place/details/json"
         . "?place_id=" . urlencode($placeId)
         . "&fields="   . urlencode($fields)
         . "&language=id"
         . "&reviews_sort=newest"
         . "&key="      . urlencode($apiKey);

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_USERAGENT      => 'DealerWebsite/1.0',
]);
$response  = curl_exec($ch);
$httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($response === false || !empty($curlError)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Gagal menghubungi Google API: ' . $curlError]);
    exit;
}

if ($httpCode !== 200) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => "Google API merespons dengan kode HTTP $httpCode."]);
    exit;
}

$data = json_decode($response, true);

// Cek status dari Google
$status = $data['status'] ?? 'UNKNOWN';
if ($status !== 'OK') {
    $errorMsg = [
        'REQUEST_DENIED'    => 'API Key ditolak Google. Pastikan Places API sudah diaktifkan di Google Cloud Console.',
        'INVALID_REQUEST'   => 'Place ID tidak valid atau kosong.',
        'NOT_FOUND'         => 'Bisnis dengan Place ID tersebut tidak ditemukan di Google Maps.',
        'OVER_QUERY_LIMIT'  => 'Kuota API Key sudah habis untuk hari ini. Coba lagi besok.',
        'ZERO_RESULTS'      => 'Tidak ada hasil ditemukan untuk Place ID ini.',
    ];
    $msg = $errorMsg[$status] ?? "Google API error: $status — " . ($data['error_message'] ?? '');
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => $msg]);
    exit;
}

$reviews = $data['result']['reviews'] ?? [];
if (empty($reviews)) {
    // Update last sync time
    $pdo->prepare("UPDATE config_cabang SET google_review_last_sync = NOW() WHERE id = 1")->execute();
    ob_end_clean();
    echo json_encode(['success' => true, 'inserted' => 0, 'skipped' => 0,
        'message' => 'Sync berhasil, tapi bisnis ini belum memiliki review di Google Maps.']);
    exit;
}

// ----------------------------------------------------------------
// Proses setiap review → simpan ke tabel testimoni
// ----------------------------------------------------------------
$inserted = 0;
$skipped  = 0;
$errors   = [];

foreach ($reviews as $review) {
    // Buat ID unik berdasarkan nama + waktu review
    $authorName  = trim($review['author_name'] ?? 'Anonim');
    $reviewTime  = (int)($review['time'] ?? 0);
    $reviewText  = trim($review['text'] ?? '');
    $rating      = (int)($review['rating'] ?? 5);
    $photoUrl    = $review['profile_photo_url'] ?? '';
    $relativeTime = $review['relative_time_description'] ?? '';

    // Google review ID: hash dari author + timestamp (stabil dan unik)
    $googleReviewId = md5($placeId . '_' . $authorName . '_' . $reviewTime);
    $reviewDate     = $reviewTime > 0 ? date('Y-m-d', $reviewTime) : date('Y-m-d');

    // Cek apakah sudah ada di DB (hindari duplikat)
    try {
        $check = $pdo->prepare("SELECT id FROM testimoni WHERE google_review_id = ? LIMIT 1");
        $check->execute([$googleReviewId]);
        if ($check->fetch()) {
            $skipped++;
            continue;
        }
    } catch (Exception $e) {
        // Kolom google_review_id belum ada → migrasi belum dijalankan
        ob_end_clean();
        echo json_encode([
            'success' => false,
            'message' => 'Kolom database belum tersedia. Jalankan file migrate_add_google_review.sql di phpMyAdmin terlebih dahulu.'
        ]);
        exit;
    }

    // Foto profil Google: gunakan foto Google jika ada,
    // fallback ke placeholder
    $foto = !empty($photoUrl) ? $photoUrl : '';
    if (empty($foto)) {
        // Gunakan foto placeholder berbasis inisial nama
        $initial = mb_strtoupper(mb_substr($authorName, 0, 1));
        $foto    = "https://ui-avatars.com/api/?name=" . urlencode($authorName)
                 . "&size=200&background=EB0A1E&color=ffffff&bold=true";
    }

    // Judul: "Review Google" + nama reviewer
    $judul = 'Review Google: ' . mb_substr($authorName, 0, 80);
    
    // Token unik untuk link testimoni (tidak dipakai untuk Google review)
    $token = bin2hex(random_bytes(32));

    try {
        $pdo->prepare("
            INSERT INTO testimoni (
                token, judul_serah_terima, foto_serah_terima_url, tanggal_serah_terima,
                nama_customer, isi_testimoni, rating,
                is_visible, status_isi,
                source, google_review_id, reviewer_photo_url
            ) VALUES (
                ?, ?, ?, ?,
                ?, ?, ?,
                0, 'sudah_diisi',
                'google', ?, ?
            )
        ")->execute([
            $token,
            $judul,
            $foto,
            $reviewDate,
            $authorName,
            $reviewText,
            min(5, max(1, $rating)),
            $googleReviewId,
            $photoUrl,
        ]);
        $inserted++;
    } catch (Exception $e) {
        $errors[] = "Gagal simpan review dari {$authorName}: " . $e->getMessage();
    }
}

// Update waktu sync terakhir
try {
    $pdo->prepare("UPDATE config_cabang SET google_review_last_sync = NOW() WHERE id = 1")->execute();
} catch (Exception $e) {
    // Kolom belum ada — tidak fatal
}

// Bersihkan cache agar testimoni baru muncul
cacheFlush();

$message = "$inserted review baru berhasil diimpor. $skipped review sudah ada (dilewati).";
if (!empty($errors)) {
    $message .= " " . count($errors) . " gagal: " . implode('; ', array_slice($errors, 0, 3));
}

ob_end_clean();
echo json_encode([
    'success'       => true,
    'inserted'      => $inserted,
    'skipped'       => $skipped,
    'total_fetched' => count($reviews),
    'message'       => $message,
    'place_name'    => $data['result']['name'] ?? '',
    'place_rating'  => $data['result']['rating'] ?? null,
    'total_reviews' => $data['result']['user_ratings_total'] ?? null,
]);
