<?php
require_once __DIR__ . '/database.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Get current user data from DB
function currentUser() {
    if (!isLoggedIn()) return null;
    static $user = null;
    if ($user === null) {
        $pdo = getDB();
        $stmt = $pdo->prepare("SELECT u.*, r.role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();
    }
    return $user;
}

// Check if user has a specific role
function hasRole($roleNames) {
    if (!isLoggedIn()) return false;
    if (!is_array($roleNames)) $roleNames = [$roleNames];
    return in_array($_SESSION['role_name'] ?? '', $roleNames);
}

// Get role-based redirect URL
function getRedirectUrl() {
    if (!isLoggedIn()) return '/DigiMobiz/auth/login.php';
    $map = [
        1 => '/DigiMobiz/admin/dashboard.php',
        2 => '/DigiMobiz/admin/dashboard.php',
        3 => '/DigiMobiz/pos/pos.php',
        4 => '/DigiMobiz/repairs/technician_panel.php',
        5 => '/DigiMobiz/products/products.php',
        6 => '/DigiMobiz/reports/profit_loss_report.php',
        7 => '/DigiMobiz/customers/customers.php',
    ];
    return $map[$_SESSION['role_id']] ?? '/DigiMobiz/admin/dashboard.php';
}

// Check if user has specific permission
function hasPermission($slug) {
    if (!isLoggedIn()) return false;
    if ($_SESSION['role_id'] == 1) return true;

    $pdo = getDB();
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM role_permissions rp
        JOIN permissions p ON rp.permission_id = p.id
        WHERE rp.role_id = ? AND p.permission_key = ?
    ");
    $stmt->execute([$_SESSION['role_id'], $slug]);
    return $stmt->fetchColumn() > 0;
}

// Require login
function requireLogin() {
    if (!isLoggedIn()) {
        $_SESSION['error'] = 'Please login to continue.';
        header('Location: /DigiMobiz/auth/login.php');
        exit;
    }
}

// Require specific permission
function requirePermission($slug) {
    requireLogin();
    if (!hasPermission($slug)) {
        $_SESSION['error'] = 'You do not have permission to access this page.';
        header('Location: ' . getRedirectUrl());
        exit;
    }
}

// Log user activity
function logActivity($action, $module_name, $record_id = null, $description = '') {
    if (!isLoggedIn()) return;
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO audit_logs (user_id, action, module_name, record_id, new_data, ip_address) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $_SESSION['user_id'],
        $action,
        $module_name,
        $record_id,
        json_encode(['note' => $description]),
        $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
    ]);
}

// Get setting value
function getSetting($key, $default = '') {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $row = $stmt->fetch();
    return $row ? $row['setting_value'] : $default;
}

// Format currency
function formatCurrency($amount) {
    $symbol = getSetting('currency_symbol', 'Rs.');
    return $symbol . ' ' . number_format($amount, 2);
}

// Format date
function formatDate($date, $format = 'Y-m-d') {
    if (!$date || $date == '0000-00-00') return '-';
    return date($format, strtotime($date));
}

// Format datetime
function formatDateTime($datetime, $format = 'Y-m-d h:i A') {
    if (!$datetime) return '-';
    return date($format, strtotime($datetime));
}

// Generate code with prefix (generic)
function generateCode($prefix, $table, $column = 'id') {
    $pdo = getDB();
    $stmt = $pdo->query("SELECT COUNT(*) FROM $table");
    $count = $stmt->fetchColumn();
    return $prefix . str_pad($count + 1, 6, '0', STR_PAD_LEFT);
}

// Generate invoice number
function generateInvoiceNo($prefix = 'INV-') {
    return generateCode($prefix, 'sales_invoices');
}

// Generate job number
function generateJobNo($prefix = 'JOB-') {
    return generateCode($prefix, 'repair_jobs');
}

// Generate return number
function generateReturnNo($prefix = 'RET-') {
    return generateCode($prefix, 'returns_');
}

// Generate claim number
function generateClaimNo($prefix = 'CLM-') {
    return generateCode($prefix, 'warranty_claims');
}

// Generate purchase number
function generatePurchaseNo($prefix = 'PO-') {
    return generateCode($prefix, 'purchases');
}

// Generate expense number
function generateExpenseNo($prefix = 'EXP-') {
    return generateCode($prefix, 'expenses');
}

// Generate payment number
function generatePaymentNo($prefix = 'PMT-') {
    return generateCode($prefix, 'payments');
}

// Generate customer code
function generateCustomerCode($prefix = 'CUST-') {
    return generateCode($prefix, 'customers');
}

// Generate supplier code
function generateSupplierCode($prefix = 'SUP-') {
    return generateCode($prefix, 'suppliers');
}

// Generate product code
function generateProductCode($prefix = 'PROD-') {
    return generateCode($prefix, 'products');
}

// Sanitize input
function sanitizeInput($data) {
    if (is_array($data)) {
        return array_map('sanitizeInput', $data);
    }
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Upload image
function uploadImage($file, $directory = null) {
    if ($file['error'] !== UPLOAD_ERR_OK) return null;
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) return null;
    $dir = $directory ?: __DIR__ . '/../assets/uploads/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    $filename = uniqid() . '_' . time() . '.' . $ext;
    if (move_uploaded_file($file['tmp_name'], $dir . $filename)) {
        return 'assets/uploads/' . $filename;
    }
    return null;
}

// Time elapsed
function timeElapsed($datetime) {
    if (!$datetime) return '-';
    $diff = time() - strtotime($datetime);
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff / 60) . ' min ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
    return floor($diff / 86400) . ' days ago';
}

// Check low stock
function checkStock($product_id) {
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT current_stock, low_stock_qty FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $p = $stmt->fetch();
    return $p ? ['current' => $p['current_stock'], 'low' => $p['low_stock_qty'], 'is_low' => $p['current_stock'] <= $p['low_stock_qty']] : null;
}

