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

// 1. Ambil Konfigurasi Cabang
function getConfig($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM config_cabang LIMIT 1");
        return $stmt->fetch();
    } catch (Exception $e) { return false; }
}

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

// 3. Ambil Data Kredit Komplit
function getCreditData($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' => []];
    }
}

// 4. Ambil Semua Produk (Mobil) - Urut A-Z
function getAllProducts($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 {
        $stmt = $pdo->query($sql);
        return $stmt->fetchAll();
    } catch (Exception $e) { return []; }
}

// 5. Ambil Semua Promo
function getAllPromos($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 {
        $stmt = $pdo->query($sql);
        return $stmt->fetchAll();
    } catch (Exception $e) { return []; }
}

// 6. Ambil Testimoni
function getAllTestimonials($pdo) {
    $sql = "SELECT *, nama_customer as name, judul_serah_terima as car, isi_testimoni as text, foto_serah_terima_url as delivery_photo 
            FROM testimoni WHERE is_visible = 1 AND status_isi = 'sudah_diisi' ORDER BY created_at DESC";
    try {
        $stmt = $pdo->query($sql);
        return $stmt->fetchAll();
    } catch (Exception $e) { return []; }
}

// 7. Ambil Artikel (HANYA YANG PUBLISHED)
function getAllArticles($pdo) {
    $sql = "SELECT *, judul as title, meta_description as meta, DATE_FORMAT(tanggal_buat, '%d %b %Y') as date, gambar_cover_url as image, konten as content 
            FROM artikel 
            WHERE status = 'published'
            ORDER BY id DESC";
    try {
        $stmt = $pdo->query($sql);
        return $stmt->fetchAll();
    } catch (Exception $e) { return []; }
}

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