<?php
if (!headers_sent()) { ob_start(); }
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/database.php';

function sanitize_input(string $value): string
{
    return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
}

function redirect_with_message(string $location, string $message, string $type = 'success'): void
{
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = $type;
    header('Location: ' . $location);
    exit;
}

function set_flash_message(string $message, string $type = 'success'): void
{
    $_SESSION['flash_message'] = $message;
    $_SESSION['flash_type'] = $type;
}

function get_flash_message(): array
{
    $message = $_SESSION['flash_message'] ?? '';
    $type = $_SESSION['flash_type'] ?? 'info';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
    return [$message, $type];
}

function base_url(string $path = ''): string
{
    $base = BASE_PATH;
    $path = ltrim($path, '/');

    if ($base === '') {
        return $path === '' ? '/' : '/' . $path;
    }

    return $path === '' ? $base . '/' : $base . '/' . $path;
}

function is_logged_in(): bool
{
    return isset($_SESSION['user']);
}

function current_user(): ?array
{
    return $_SESSION['user'] ?? null;
}

function require_login(): void
{
    if (!is_logged_in()) {
        header('Location: ' . base_url('index.php'));
        exit;
    }
}

function require_role(array $roles): void
{
    $user = current_user();
    if (!$user || !in_array($user['role'], $roles, true)) {
        redirect_with_message(base_url('dashboard.php'), 'Anda tidak memiliki akses ke halaman tersebut.', 'danger');
    }
}

function format_currency(float $amount): string
{
    return 'Rp ' . number_format($amount, 0, ',', '.');
}

function format_date(?string $date): string
{
    if (!$date) {
        return '-';
    }
    $dt = new DateTime($date);
    return $dt->format('d M Y');
}

function generate_invoice_number(): string
{
    return 'INV-' . strtoupper(bin2hex(random_bytes(4))) . '-' . date('Ymd');
}

function generate_client_code(): string
{
    return 'C' . date('ymd') . strtoupper(substr(bin2hex(random_bytes(3)), 0, 4));
}

/**
 * ✅ FIX CSRF
 * - csrf_token(): hanya buat token sekali per session
 * - validate_csrf_token(): cek saja, jangan auto-unset
 */
function csrf_token(): string
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validate_csrf_token(?string $token): bool
{
    if (!isset($_SESSION['csrf_token']) || !$token) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}

function status_badge_class(string $status): string
{
    $map = [
        'active' => 'active',
        'suspended' => 'suspended',
        'terminated' => 'terminated',
        'paid' => 'paid',
        'pending' => 'pending',
        'overdue' => 'overdue',
        'inactive' => 'suspended',
    ];
    return $map[$status] ?? 'secondary';
}

function get_summary_cards(): array
{
    $db = get_db_connection();

    $summary = [
        'active_clients' => 0,
        'monthly_revenue' => 0.0,
        'pending_invoices' => 0,
        'active_packages' => 0,
    ];

    $queries = [
        'active_clients' => "SELECT COUNT(*) AS total FROM clients WHERE status = 'active'",
        'monthly_revenue' => "SELECT COALESCE(SUM(amount),0) AS total FROM payments WHERE payment_status = 'paid' AND MONTH(payment_date) = MONTH(CURRENT_DATE()) AND YEAR(payment_date) = YEAR(CURRENT_DATE())",
        'pending_invoices' => "SELECT COUNT(*) AS total FROM payments WHERE payment_status = 'pending'",
        'active_packages' => "SELECT COUNT(*) AS total FROM packages WHERE status = 'active'",
    ];

    foreach ($queries as $key => $sql) {
        $result = $db->query($sql);
        if ($result) {
            $row = $result->fetch_assoc();
            $summary[$key] = $key === 'monthly_revenue' ? (float) $row['total'] : (int) $row['total'];
        }
    }

    return $summary;
}

function get_recent_payments(int $limit = 5): array
{
    $db = get_db_connection();
    $sql = 'SELECT p.invoice_number, c.full_name, p.amount, p.payment_status, p.payment_date
            FROM payments p
            JOIN clients c ON c.id = p.client_id
            ORDER BY p.created_at DESC
            LIMIT ?';
    $stmt = $db->prepare($sql);
    $stmt->bind_param('i', $limit);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_all(MYSQLI_ASSOC);
}

function get_revenue_chart_data(): array
{
    $db = get_db_connection();
    $sql = "SELECT DATE_FORMAT(payment_date, '%b %Y') AS period, SUM(amount) AS total
            FROM payments
            WHERE payment_status = 'paid' AND payment_date IS NOT NULL
            GROUP BY YEAR(payment_date), MONTH(payment_date)
            ORDER BY YEAR(payment_date), MONTH(payment_date)
            LIMIT 12";
    $result = $db->query($sql);
    $labels = [];
    $values = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $labels[] = $row['period'];
            $values[] = (float) $row['total'];
        }
    }
    return ['labels' => $labels, 'values' => $values];
}

function get_all_packages(): array
{
    $db = get_db_connection();
    $result = $db->query("SELECT id, package_name, price FROM packages WHERE status = 'active' ORDER BY package_name");
    return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}

function get_client_options(): array
{
    $db = get_db_connection();
    $result = $db->query('SELECT id, full_name FROM clients ORDER BY full_name');
    return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
?>