<?php
/**
 * Database Configuration
 * Koperasi Management System
 */

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check environment
$is_local = false;
if (isset($_SERVER['HTTP_HOST'])) {
    $host_name = $_SERVER['HTTP_HOST'];
    if (
        strpos($host_name, 'localhost') !== false ||
        strpos($host_name, '127.0.0.1') !== false ||
        strpos($host_name, '192.168.') !== false ||
        $host_name == '::1'
    ) {
        $is_local = true;
    }
}

if ($is_local) {
    // Database configuration LOCAL
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'koperasi_db');
    define('DB_USER', 'root');
    define('DB_PASS', '');
} else {
    // Database configuration HOSTING (Adjust with your hosting details)
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'absw5172_koperasi'); // Adjust based on your actual hosting DB name
    define('DB_USER', 'absw5172_koperasi'); // Adjust based on your actual hosting DB user
    define('DB_PASS', 'koperasi');          // Adjust based on your actual hosting DB password
}
define('DB_CHARSET', 'utf8mb4');

// Application configuration
define('APP_NAME', 'Koperasi Tsuroyya Bersama');
define('APP_URL', 'http://192.168.1.14/koperasi');
define('APP_VERSION', '1.0.0');

// Base path
define('BASE_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);

// Helpers for URL
define('ASSETS_URL', APP_URL . '/assets');

/**
 * Get PDO database connection
 */
function getDB()
{
    static $pdo = null;

    if ($pdo === null) {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            die("Koneksi database gagal: " . $e->getMessage());
        }
    }

    return $pdo;
}

/**
 * Get application setting from database
 */
function getSetting($key, $default = '')
{
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT nilai FROM pengaturan WHERE kunci = ?");
        $stmt->execute([$key]);
        $result = $stmt->fetch();
        return $result ? $result['nilai'] : $default;
    } catch (Exception $e) {
        return $default;
    }
}

/**
 * Format currency to IDR
 * @param float $amount The amount to format
 * @param bool $prefix Whether to include 'Rp' prefix (default: true)
 */
function formatRupiah($amount, $prefix = true)
{
    $formatted = number_format($amount, 0, ',', '.');
    return $prefix ? 'Rp ' . $formatted : $formatted;
}

/**
 * Format date to Indonesian format
 */
function formatTanggal($date)
{
    $bulan = [
        1 => 'Januari',
        2 => 'Februari',
        3 => 'Maret',
        4 => 'April',
        5 => 'Mei',
        6 => 'Juni',
        7 => 'Juli',
        8 => 'Agustus',
        9 => 'September',
        10 => 'Oktober',
        11 => 'November',
        12 => 'Desember'
    ];
    $d = new DateTime($date);
    return $d->format('d') . ' ' . $bulan[(int) $d->format('m')] . ' ' . $d->format('Y');
}

/**
 * Format month (YYYY-MM) to Indonesian text format
 */
if (!function_exists('formatBulan')) {
    function formatBulan($bulan)
    {
        $bulanArray = [
            1 => 'Januari',
            2 => 'Februari',
            3 => 'Maret',
            4 => 'April',
            5 => 'Mei',
            6 => 'Juni',
            7 => 'Juli',
            8 => 'Agustus',
            9 => 'September',
            10 => 'Oktober',
            11 => 'November',
            12 => 'Desember'
        ];

        if (strpos($bulan, '-') !== false) {
            $parts = explode('-', $bulan);
            $year = $parts[0];
            $month = $parts[1] ?? 0;
            return ($bulanArray[(int) $month] ?? '') . ' ' . $year;
        }

        return $bulanArray[(int) $bulan] ?? '';
    }
}

/**
 * Generate unique number (for member/loan IDs)
 */
function generateNumber($prefix, $table, $column)
{
    $db = getDB();
    $stmt = $db->query("SELECT MAX($column) as last_number FROM $table");
    $result = $stmt->fetch();

    if ($result['last_number']) {
        $lastNum = intval(str_replace($prefix . '-', '', $result['last_number']));
        $newNum = $lastNum + 1;
    } else {
        $newNum = 1;
    }

    return $prefix . '-' . str_pad($newNum, 4, '0', STR_PAD_LEFT);
}

/**
 * Sanitize input
 */
function sanitize($input)
{
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Set flash message
 */
function setFlash($type, $message)
{
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

/**
 * Get and clear flash message
 */
function getFlash()
{
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}
/**
 * Update application setting in database
 */
function updateSetting($key, $value)
{
    try {
        $db = getDB();
        $stmt = $db->prepare("UPDATE pengaturan SET nilai = ? WHERE kunci = ?");
        return $stmt->execute([$value, $key]);
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Get monthly consumption limit for a specific month (1-12)
 * @param int $month Month number (1-12)
 * @param float $default Default limit if not found
 */
function getKonsumsiLimitBulanan($month, $default = 50000)
{
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT batas FROM konsumsi_batas_bulanan WHERE bulan = ?");
        $stmt->execute([$month]);
        $result = $stmt->fetch();
        return $result ? (float) $result['batas'] : $default;
    } catch (Exception $e) {
        return $default;
    }
}

/**
 * Update monthly consumption limit for a specific month
 * @param int $month Month number (1-12)
 * @param float $batas Spending limit
 */
function updateKonsumsiLimitBulanan($month, $batas)
{
    try {
        $db = getDB();
        // Try to update first
        $stmt = $db->prepare("UPDATE konsumsi_batas_bulanan SET batas = ? WHERE bulan = ?");
        $stmt->execute([$batas, $month]);

        // If no rows affected, insert new record
        if ($stmt->rowCount() === 0) {
            $stmt = $db->prepare("INSERT INTO konsumsi_batas_bulanan (bulan, batas) VALUES (?, ?)");
            $stmt->execute([$month, $batas]);
        }
        return true;
    } catch (Exception $e) {
        return false;
    }
}

/**
 * Get member's consumption limit for a specific month (member override or default monthly limit)
 * @param int $anggotaId Member ID
 * @param int $month Month number (1-12)
 * @param float $defaultMonthlyLimit Default monthly limit if not found
 */
function getKonsumsiLimitAnggota($anggotaId, $month, $defaultMonthlyLimit = 50000)
{
    try {
        $db = getDB();
        // Check for member-specific override first
        $stmt = $db->prepare("SELECT batas FROM konsumsi_batas_anggota WHERE anggota_id = ? AND bulan = ?");
        $stmt->execute([$anggotaId, $month]);
        $result = $stmt->fetch();

        if ($result) {
            return (float) $result['batas'];
        }

        // Fall back to monthly limit
        return getKonsumsiLimitBulanan($month, $defaultMonthlyLimit);
    } catch (Exception $e) {
        return $defaultMonthlyLimit;
    }
}

/**
 * Set member's consumption limit for a specific month (override monthly limit)
 * @param int $anggotaId Member ID
 * @param int $month Month number (1-12)
 * @param float $batas Spending limit
 */
function setKonsumsiLimitAnggota($anggotaId, $month, $batas)
{
    try {
        $db = getDB();

        if ($batas <= 0) {
            // Delete override if limit is 0 or negative
            $stmt = $db->prepare("DELETE FROM konsumsi_batas_anggota WHERE anggota_id = ? AND bulan = ?");
            return $stmt->execute([$anggotaId, $month]);
        }

        // Try to update first
        $stmt = $db->prepare("UPDATE konsumsi_batas_anggota SET batas = ? WHERE anggota_id = ? AND bulan = ?");
        $stmt->execute([$batas, $anggotaId, $month]);

        // If no rows affected, insert new record
        if ($stmt->rowCount() === 0) {
            $stmt = $db->prepare("INSERT INTO konsumsi_batas_anggota (anggota_id, bulan, batas) VALUES (?, ?, ?)");
            $stmt->execute([$anggotaId, $month, $batas]);
        }
        return true;
    } catch (Exception $e) {
        return false;
    }
}
