<?php
// ============================================================
// FILE: includes/functions.php
// Kumpulan fungsi helper yang dipakai di seluruh aplikasi
// ============================================================

require_once __DIR__ . '/db.php';

// ---- Format & Sanitasi ----------------------------------------

/** Format angka menjadi Rupiah. Contoh: 150000 => "Rp 150.000" */
function formatRupiah(float $angka): string {
    return 'Rp ' . number_format($angka, 0, ',', '.');
}

/** Bersihkan output dari XSS. Selalu pakai ini saat tampilkan data ke HTML. */
function e(string $str): string {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

/** Buat slug URL-friendly. Contoh: "Kusen Kayu Jati" => "kusen-kayu-jati" */
function buatSlug(string $teks): string {
    $teks = strtolower(trim($teks));
    $teks = preg_replace('/[^a-z0-9\s-]/', '', $teks);
    $teks = preg_replace('/[\s-]+/', '-', $teks);
    return trim($teks, '-');
}

/** Generate kode pesanan unik. Format: BJ-20250628-0001 */
function generateKodePesanan(): string {
    $pdo     = db();
    $tanggal = date('Ymd');
    $prefix  = 'BJ-' . $tanggal . '-';
    $stmt    = $pdo->prepare("SELECT COUNT(*) FROM pesanan WHERE kode_pesanan LIKE ?");
    $stmt->execute([$prefix . '%']);
    $urut    = $stmt->fetchColumn() + 1;
    return $prefix . str_pad($urut, 4, '0', STR_PAD_LEFT);
}

/** Tampilkan pesan flash dari session lalu hapus. */
function flashMessage(): string {
    $html = '';
    if (!empty($_SESSION['flash'])) {
        $tipe  = $_SESSION['flash']['tipe'];
        $pesan = e($_SESSION['flash']['pesan']);
        $html  = "<div class='alert alert-{$tipe} alert-dismissible fade show' role='alert'>
                    {$pesan}
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                  </div>";
        unset($_SESSION['flash']);
    }
    return $html;
}

/** Set pesan flash ke session. */
function setFlash(string $tipe, string $pesan): void {
    $_SESSION['flash'] = ['tipe' => $tipe, 'pesan' => $pesan];
}

/** Redirect ke URL dan hentikan eksekusi. */
function redirect(string $url): void {
    header('Location: ' . $url);
    exit;
}

// ---- Upload File -----------------------------------------------

/**
 * Upload gambar ke folder tujuan. Return nama file baru atau false jika gagal.
 * @param array  $file    Elemen dari $_FILES
 * @param string $folder  Subfolder di dalam uploads/ (misal: 'produk')
 */
function uploadGambar(array $file, string $folder): string|false {
    if ($file['error'] !== UPLOAD_ERR_OK)     return false;
    if ($file['size'] > MAX_FILE_SIZE)         return false;

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($file['tmp_name']);
    if (!in_array($mime, ALLOWED_IMG, true))   return false;

    $ekstensi = pathinfo($file['name'], PATHINFO_EXTENSION);
    $namaFile = uniqid('img_', true) . '.' . strtolower($ekstensi);
    $tujuan   = UPLOAD_PATH . '/' . $folder . '/' . $namaFile;

    if (!is_dir(dirname($tujuan))) mkdir(dirname($tujuan), 0755, true);

    return move_uploaded_file($file['tmp_name'], $tujuan) ? $namaFile : false;
}

/** Hapus file gambar dari server. */
function hapusGambar(string $namaFile, string $folder): void {
    $path = UPLOAD_PATH . '/' . $folder . '/' . $namaFile;
    if (file_exists($path)) unlink($path);
}

// ---- Keranjang -------------------------------------------------

/** Ambil total item di keranjang (untuk badge navbar). */
function jumlahKeranjang(): int {
    $pdo  = db();
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM keranjang WHERE session_id=?");
    $stmt->execute([session_id()]);
    return (int) $stmt->fetchColumn();
}

/** Hitung total harga semua item di keranjang. */
function totalKeranjang(): float {
    $pdo  = db();
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(k.jumlah * p.harga),0)
        FROM keranjang k JOIN produk p ON k.produk_id = p.id
        WHERE k.session_id = ?
    ");
    $stmt->execute([session_id()]);
    return (float) $stmt->fetchColumn();
}

// ---- Status Pesanan --------------------------------------------

/** Return badge Bootstrap sesuai status pesanan. */
function statusBadge(string $status): string {
    $map = [
        'pending'      => 'warning',
        'dibayar'      => 'info',
        'diverifikasi' => 'primary',
        'diproses'     => 'secondary',
        'selesai'      => 'success',
        'dibatalkan'   => 'danger',
    ];
    $warna = $map[$status] ?? 'light';
    return "<span class='badge bg-{$warna}'>" . ucfirst($status) . "</span>";
}

/** Label + ikon untuk setiap langkah tracking pesanan. */
function langkahTracking(): array {
    return [
        'pending'      => ['icon' => 'clock',         'label' => 'Menunggu Pembayaran'],
        'dibayar'      => ['icon' => 'upload',        'label' => 'Bukti Dikirim'],
        'diverifikasi' => ['icon' => 'check-circle',  'label' => 'Pembayaran Dikonfirmasi'],
        'diproses'     => ['icon' => 'gear',          'label' => 'Pesanan Diproses'],
        'selesai'      => ['icon' => 'house-check',   'label' => 'Selesai'],
        ];
        
}

// ============================================================
// FUNGSI BARU UNTUK PENGATURAN TOKO (Dinamis)
// ============================================================

/**
 * Ambil semua pengaturan toko dari database
 * @return array Pengaturan dengan key_name sebagai indeks
 */
function getPengaturanToko(): array {
    $pdo = db();
    // Cek apakah tabel pengaturan_toko sudah ada
    try {
        $stmt = $pdo->query("SELECT key_name, value_text, value_json FROM pengaturan_toko");
        $result = [];
        while ($row = $stmt->fetch()) {
            if ($row['value_json'] !== null) {
                $result[$row['key_name']] = json_decode($row['value_json'], true);
            } else {
                $result[$row['key_name']] = $row['value_text'];
            }
        }
        return $result;
    } catch (PDOException $e) {
        // Tabel belum ada, return array kosong
        return [];
    }
}

/**
 * Update pengaturan tipe teks
 * @param string $key Key name
 * @param string $value Nilai text
 * @return bool
 */
function updatePengaturanText(string $key, string $value): bool {
    $pdo = db();
    $sql = "INSERT INTO pengaturan_toko (key_name, value_text, value_json) 
            VALUES (:key, :value, NULL)
            ON DUPLICATE KEY UPDATE value_text = :value, value_json = NULL";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute([':key' => $key, ':value' => $value]);
}

/**
 * Update pengaturan tipe JSON
 * @param string $key Key name
 * @param array $data Array yang akan di-json-kan
 * @return bool
 */
function updatePengaturanJson(string $key, array $data): bool {
    $pdo = db();
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
    $sql = "INSERT INTO pengaturan_toko (key_name, value_text, value_json) 
            VALUES (:key, NULL, :json)
            ON DUPLICATE KEY UPDATE value_text = NULL, value_json = :json";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute([':key' => $key, ':json' => $json]);
}

/**
 * Upload background hero
 * @param array $file File dari $_FILES['hero_bg']
 * @return string|false Nama file (path relatif) jika sukses, false jika gagal
 */
function uploadHeroBackground($file): string|false {
    // Validasi error
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }
    
    // Validasi tipe
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);
    
    $allowed = ['image/jpeg', 'image/png', 'image/webp', 'image/jpg'];
    if (!in_array($mime, $allowed, true)) {
        return false;
    }
    
    // Validasi ukuran (max 2MB)
    if ($file['size'] > 2 * 1024 * 1024) {
        return false;
    }
    
    // Buat folder jika belum ada
    $uploadDir = UPLOAD_PATH . '/pengaturan/hero/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    // Generate nama file unik
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $newName = 'hero-bg-' . date('Ymd_His') . '.' . $ext;
    $targetPath = $uploadDir . $newName;
    
    // Upload file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return 'hero/' . $newName;
    }
    
    return false;
}
