<?php
session_start();

// 1. MASUKKAN KREDENSIAL GOOGLE ANDA DISINI
$client_id     = '6424574978-rbjcpb5tn799sku2554a19023gvtf74p.apps.googleusercontent.com';
$client_secret = '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';
$redirect_uri  = 'https://omnich.majapahitnet.id/sync_google.php'; // Harus sama dengan di Cloud Console

// 2. KONFIGURASI DATABASE
$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';
$conn = new mysqli($host, $user, $pass, $db);

// FUNGSI MEMBERSIHKAN NOMOR HP (Ubah ke format 62)
function bersihkanNomor($phone) {
    $phone = preg_replace('/[^0-9]/', '', $phone); // Ambil angka saja
    if (substr($phone, 0, 1) === '0') {
        $phone = '62' . substr($phone, 1);
    } elseif (substr($phone, 0, 2) !== '62') {
        $phone = '62' . $phone;
    }
    return $phone;
}

// ALUR OAUTH 2.0
if (!isset($_GET['code'])) {
    // Langkah A: Minta izin ke Google
    $auth_url = "https://accounts.google.com/o/oauth2/v2/auth?" . http_build_query([
        'client_id'     => $client_id,
        'redirect_uri'  => $redirect_uri,
        'response_type' => 'code',
        'scope'         => 'https://www.googleapis.com/auth/contacts.readonly',
        'access_type'   => 'offline',
        'prompt'        => 'consent'
    ]);
    echo "<div style='text-align:center; padding-top:50px; font-family:sans-serif;'>";
    echo "<h2>Sinkronisasi Kontak Google</h2>";
    echo "<a href='$auth_url' style='padding:15px 25px; background:#4285f4; color:white; text-decoration:none; border-radius:5px;'>Login dengan Google & Sinkron</a>";
    echo "</div>";
    exit;
} else {
    // Langkah B: Tukar Kode dengan Access Token
    $code = $_GET['code'];
    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'code'          => $code,
        'client_id'     => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri'  => $redirect_uri,
        'grant_type'    => 'authorization_code'
    ]));
    $response = json_decode(curl_exec($ch), true);
    
    if (!isset($response['access_token'])) {
        die("Gagal mendapatkan token dari Google. Pastikan Client ID dan Secret benar.");
    }
    $access_token = $response['access_token'];

    // Langkah C: Ambil Data Kontak dari Google
    $url_contacts = "https://people.googleapis.com/v1/people/me/connections?personFields=names,phoneNumbers&pageSize=1000";
    $ch = curl_init($url_contacts);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $access_token]);
    $data_kontak = json_decode(curl_exec($ch), true);

    $count = 0;
    if (isset($data_kontak['connections'])) {
        foreach ($data_kontak['connections'] as $person) {
            $nama = isset($person['names'][0]['displayName']) ? $conn->real_escape_string($person['names'][0]['displayName']) : '';
            $nomor_raw = isset($person['phoneNumbers'][0]['value']) ? $person['phoneNumbers'][0]['value'] : '';
            
            if (!empty($nomor_raw) && !empty($nama)) {
                $phone = bersihkanNomor($nomor_raw);
                
                // Cek apakah nomor sudah ada di database majapahi_omnich
                $cek = $conn->query("SELECT id FROM contacts WHERE phone_number = '$phone'");
                
                if ($cek->num_rows > 0) {
                    // Jika sudah ada, update namanya saja
                    $conn->query("UPDATE contacts SET name = '$nama' WHERE phone_number = '$phone'");
                } else {
                    // ==============================================================
                    // PERBAIKAN: Masukkan sebagai 'saved', bukan 'open'.
                    // Ini membuat kontak bersembunyi sebagai buku telepon latar belakang.
                    // ==============================================================
                    $conn->query("INSERT INTO contacts (phone_number, name, status) VALUES ('$phone', '$nama', 'saved')");
                }
                $count++;
            }
        }
        
        // =========================================================================
        // PENYAPU OTOMATIS: Sembunyikan kontak yang sudah terlanjur menumpuk di Dashboard 
        // tapi sebenarnya tidak memiliki riwayat chat (pesan) sama sekali.
        // =========================================================================
        $conn->query("UPDATE contacts SET status = 'saved' WHERE status IN ('open', 'closed') AND phone_number NOT IN (SELECT DISTINCT phone_number FROM messages)");

        echo "<div style='text-align:center; padding-top:50px; font-family:sans-serif;'>";
        echo "<h2>Berhasil! $count kontak telah disinkronkan ke OmniDesk.</h2>";
        echo "<p style='color:green;'>Dashboard Anda juga sudah dirapikan kembali dari kontak kosong.</p><br>";
        echo "<a href='dashboard.php' style='padding:10px 20px; background:#00a884; color:white; text-decoration:none; border-radius:5px;'>Kembali ke Dashboard</a>";
        echo "</div>";
    } else {
        echo "<h3>Tidak ada kontak yang ditemukan atau izin ditolak.</h3>";
    }
}
?>