<?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,
                    foto_serah_terima_url as delivery_photo,
                    COALESCE(
                        NULLIF(reviewer_photo_url, ''),
                        NULLIF(foto_serah_terima_url, '')
                    ) as profile_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 sesuai kebutuhan halaman (hemat query DB)
function getPageData($pdo, $page, $id = 0) {
    $data = [
        'products'     => [],
        'promos'       => [],
        'testimonials' => [],
        'articles'     => [],
    ];

    // Halaman yang butuh semua data (home)
    if ($page === '' || $page === 'home') {
        $data['products']     = getAllProducts($pdo);
        $data['promos']       = getAllPromos($pdo);
        $data['testimonials'] = getAllTestimonials($pdo);
        $data['articles']     = getAllArticles($pdo);
        return $data;
    }

    // Data spesifik per halaman
    switch ($page) {
        case 'produk':
        case 'produk-detail':
        case 'simulasi':
            $data['products'] = getAllProducts($pdo);
            break;
        case 'promo':
        case 'promo-detail':
            $data['promos']   = getAllPromos($pdo);
            $data['products'] = getAllProducts($pdo); // untuk WA context
            break;
        case 'artikel':
        case 'artikel-detail':
            $data['articles'] = getAllArticles($pdo);
            break;
        case 'testimoni':
            $data['testimonials'] = getAllTestimonials($pdo);
            break;
        case 'tradein':
            $data['products'] = getAllProducts($pdo); // untuk dropdown
            break;
        case 'kontak':
            // Tidak butuh data besar
            break;
        default:
            // Fallback: muat semua
            $data['products']     = getAllProducts($pdo);
            $data['promos']       = getAllPromos($pdo);
            $data['testimonials'] = getAllTestimonials($pdo);
            $data['articles']     = getAllArticles($pdo);
    }

    return $data;
}

// 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
function cfg($config, $key, $fallback = '') {
    return !empty($config[$key]) ? $config[$key] : $fallback;
}

?>