<?php
// ============================================
// Helper Functions
// ============================================

require_once __DIR__ . '/db.php';

// Session Management
function startSession() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

function isLoggedIn() {
    startSession();
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ' . getBasePath() . 'login.php');
        exit;
    }
}

function getBasePath() {
    // Detect if we're in a subdirectory
    $script = $_SERVER['SCRIPT_NAME'];
    if (strpos($script, '/pages/') !== false) {
        return '../';
    }
    return '';
}

function getCurrentUser() {
    startSession();
    if (!isLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch();
}

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

function generateCSRF() {
    startSession();
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCSRF($token) {
    startSession();
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Flash Messages
function setFlash($type, $message) {
    startSession();
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash() {
    startSession();
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

// Invoice Number Generator
function generateInvoiceNumber() {
    $db = getDB();
    $year = date('Y');
    $month = date('m');
    $stmt = $db->prepare("SELECT COUNT(*) as cnt FROM invoices WHERE YEAR(created_at) = ? AND MONTH(created_at) = ?");
    $stmt->execute([$year, $month]);
    $row = $stmt->fetch();
    $seq = str_pad($row['cnt'] + 1, 4, '0', STR_PAD_LEFT);
    return "INV-{$year}{$month}-{$seq}";
}

// Purchase Number Generator
function generatePurchaseNumber() {
    $db = getDB();
    $year = date('Y');
    $month = date('m');
    $stmt = $db->prepare("SELECT COUNT(*) as cnt FROM purchases WHERE YEAR(created_at) = ? AND MONTH(created_at) = ?");
    $stmt->execute([$year, $month]);
    $row = $stmt->fetch();
    $seq = str_pad($row['cnt'] + 1, 4, '0', STR_PAD_LEFT);
    return "PUR-{$year}{$month}-{$seq}";
}

// Format Currency
function formatCurrency($amount) {
    return CURRENCY_SYMBOL . number_format((float)$amount, 2);
}

// Format Date
function formatDate($date) {
    if (!$date) return '-';
    return date('d M Y', strtotime($date));
}

// Pagination
function paginate($query, $params, $page, $perPage = 10) {
    $db = getDB();
    $offset = ($page - 1) * $perPage;

    // Count total
    $countQuery = preg_replace('/SELECT .+? FROM/i', 'SELECT COUNT(*) as total FROM', $query);
    $countQuery = preg_replace('/ORDER BY.+$/i', '', $countQuery);
    $countQuery = preg_replace('/LIMIT.+$/i', '', $countQuery);
    $stmt = $db->prepare($countQuery);
    $stmt->execute($params);
    $total = $stmt->fetchColumn();

    // Get results
    $stmt = $db->prepare($query . " LIMIT $perPage OFFSET $offset");
    $stmt->execute($params);
    $results = $stmt->fetchAll();

    return [
        'data'        => $results,
        'total'       => $total,
        'page'        => $page,
        'perPage'     => $perPage,
        'totalPages'  => ceil($total / $perPage),
    ];
}

// Dashboard Stats
function getDashboardStats() {
    $db = getDB();

    $stats = [];

    $stats['total_products']  = $db->query("SELECT COUNT(*) FROM products WHERE status='active'")->fetchColumn();
    $stats['total_customers'] = $db->query("SELECT COUNT(*) FROM customers WHERE status='active'")->fetchColumn();
    $stats['total_invoices']  = $db->query("SELECT COUNT(*) FROM invoices")->fetchColumn();
    $stats['total_revenue']   = $db->query("SELECT COALESCE(SUM(total_amount),0) FROM invoices WHERE status='paid'")->fetchColumn();
    $stats['pending_invoices']= $db->query("SELECT COUNT(*) FROM invoices WHERE status IN ('sent','draft')")->fetchColumn();
    $stats['low_stock']       = $db->query("SELECT COUNT(*) FROM products WHERE stock_quantity < 10 AND status='active'")->fetchColumn();

    // Monthly revenue (last 6 months)
    $stmt = $db->query("
        SELECT DATE_FORMAT(invoice_date,'%b %Y') as month,
               COALESCE(SUM(total_amount),0) as revenue
        FROM invoices
        WHERE invoice_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
          AND status = 'paid'
        GROUP BY YEAR(invoice_date), MONTH(invoice_date)
        ORDER BY invoice_date ASC
    ");
    $stats['monthly_revenue'] = $stmt->fetchAll();

    // Recent invoices
    $stmt = $db->query("
        SELECT i.*, c.name as customer_name
        FROM invoices i
        JOIN customers c ON i.customer_id = c.id
        ORDER BY i.created_at DESC LIMIT 5
    ");
    $stats['recent_invoices'] = $stmt->fetchAll();

    return $stats;
}

// Status Badge HTML
function statusBadge($status) {
    $map = [
        'active'    => ['bg-emerald-100 text-emerald-700', 'Active'],
        'inactive'  => ['bg-slate-100 text-slate-600', 'Inactive'],
        'paid'      => ['bg-emerald-100 text-emerald-700', 'Paid'],
        'draft'     => ['bg-amber-100 text-amber-700', 'Draft'],
        'sent'      => ['bg-blue-100 text-blue-700', 'Sent'],
        'overdue'   => ['bg-red-100 text-red-700', 'Overdue'],
        'cancelled' => ['bg-slate-100 text-slate-600', 'Cancelled'],
    ];
    $class = $map[$status][0] ?? 'bg-slate-100 text-slate-600';
    $label = $map[$status][1] ?? ucfirst($status);
    return "<span class=\"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {$class}\">{$label}</span>";
}
