<?php
// File: includes/functions.php

require_once __DIR__ . '/cache.php';

// 1. Ambil Konfigurasi Cabang
function getConfig($pdo) {
    return cacheRemember('config_cabang', function() use ($pdo) {
        try {
            return $pdo->query("SELECT * FROM config_cabang LIMIT 1")->fetch();
        } catch (Exception $e) { return false; }
    }, 600); // cache 10 menit
}

// 2. Ambil Profil Sales
function getSalesProfile($pdo) {
    return cacheRemember('sales_profile', function() use ($pdo) {
        try {
            return $pdo->query("SELECT * FROM sales_profile LIMIT 1")->fetch();
        } catch (Exception $e) { return false; }
    }, 600);
}

// 3. Ambil Data Kredit Komplit
function getCreditData($pdo) {
    return cacheRemember('credit_data', function() use ($pdo) {
        try {
            $umum   = $pdo->query("SELECT * FROM kredit_umum LIMIT 1")->fetch();
            $tenors = $pdo->query("SELECT * FROM kredit_tenor WHERE is_active = 1 ORDER BY tenor_tahun ASC")->fetchAll();
            try { $ins = $pdo->query("SELECT * FROM rate_asuransi ORDER BY min_price ASC")->fetchAll(); } catch (Exception $e) { $ins = []; }
            return ['umum' => $umum, 'tenors' => $tenors, 'insurance' => $ins];
        } catch (Exception $e) { return ['umum' => [], 'tenors' => [], 'insurance' => []]; }
    }, 600);
}

// 4. Ambil Semua Produk
function getAllProducts($pdo) {
    return cacheRemember('all_products', function() use ($pdo) {
        $sql = "SELECT *, nama_mobil as name, harga_otr as price, gambar_utama_url as image,
                deskripsi as `desc`, video_youtube_id as video, brosur_url as brochure
                FROM produk ORDER BY nama_mobil ASC";
        try { return $pdo->query($sql)->fetchAll(); } catch (Exception $e) { return []; }
    }, 300);
}

// 5. Ambil Semua Promo
function getAllPromos($pdo) {
    return cacheRemember('all_promos', function() use ($pdo) {
        $sql = "SELECT *, judul as title, deskripsi as `desc`, meta_description as meta,
                gambar_url as image, tipe as type, video_id as video, tanggal_berakhir as expired
                FROM promo ORDER BY id DESC";
        try { return $pdo->query($sql)->fetchAll(); } catch (Exception $e) { return []; }
    }, 300);
}

// 6. Ambil Testimoni
function getAllTestimonials($pdo) {
    return cacheRemember('all_testimonials', function() use ($pdo) {
        $sql = "SELECT *,
                    nama_customer        as name,
                    judul_serah_terima   as car,
                    isi_testimoni        as text,
                    reviewer_photo_url   as profile_photo,
                    -- AUDIT FIX: delivery_photo HANYA dari foto_serah_terima_url
                    -- dan HANYA jika bukan URL foto profil Google (lh3.googleusercontent.com)
                    CASE
                        WHEN foto_serah_terima_url != ''
                         AND foto_serah_terima_url NOT LIKE '%lh3.googleusercontent.com%'
                         AND foto_serah_terima_url NOT LIKE '%lh5.googleusercontent.com%'
                        THEN foto_serah_terima_url
                        ELSE NULL
                    END as delivery_photo
                FROM testimoni
                WHERE is_visible = 1 AND status_isi = 'sudah_diisi'
                ORDER BY created_at DESC";
        try { return $pdo->query($sql)->fetchAll(); } catch (Exception $e) { return []; }
    }, 300);
}

// 7. Ambil Artikel — sertakan raw_date untuk ISO 8601 schema
function getAllArticles($pdo) {
    return cacheRemember('all_articles', function() use ($pdo) {
        $sql = "SELECT *, judul as title, meta_description as meta,
                DATE_FORMAT(tanggal_buat, '%d %b %Y') as date,
                tanggal_buat as raw_date,
                gambar_cover_url as image, konten as content
                FROM artikel WHERE status = 'published' ORDER BY id DESC";
        try { return $pdo->query($sql)->fetchAll(); } catch (Exception $e) { return []; }
    }, 300);
}

// 8. Hitung Aggregate Rating dari testimoni (untuk Rich Snippet bintang di SERP)
function getAggregateRating($pdo, $minReviews = 3) {
    return cacheRemember('aggregate_rating', function() use ($pdo, $minReviews) {
        try {
            $stmt = $pdo->query(
                "SELECT COUNT(*) as total, AVG(rating) as avg_rating FROM testimoni
                 WHERE is_visible = 1 AND status_isi = 'sudah_diisi'
                 AND rating IS NOT NULL AND rating > 0"
            );
            $row = $stmt->fetch();
            if (!$row || (int)$row['total'] < $minReviews) return null;
            return ['ratingValue' => round((float)$row['avg_rating'], 1), 'reviewCount' => (int)$row['total']];
        } catch (Exception $e) { return null; }
    }, 600);
}

// 9. Muat data untuk SPA (Semua data dimuat di awal agar navigasi JS lancar)
function getPageData($pdo, $page, $id = 0) {
    return [
        'products'     => getAllProducts($pdo),
        'promos'       => getAllPromos($pdo),
        'testimonials' => getAllTestimonials($pdo),
        'articles'     => getAllArticles($pdo),
    ];
}

// 10. Helper Format Rupiah
function formatRupiah($angka) {
    return "Rp " . number_format((float)$angka, 0, ',', '.');
}

// 11. Helper pastikan URL absolut
function makeAbsoluteUrl($url, $baseUrl) {
    if (empty($url)) return '';
    if (strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0) return $url;
    return rtrim($baseUrl, '/') . '/' . ltrim($url, '/');
}

// 12. Helper ambil nilai config dengan fallback aman
// AUDIT FIX: tambah guard untuk config null atau bukan array
function cfg($config, $key, $fallback = '') {
    if (!is_array($config) || !isset($config[$key]) || $config[$key] === null || $config[$key] === '') {
        return $fallback;
    }
    return $config[$key];
}

?>