<?php
// Admin Config - DO NOT share publicly
// Database configuration (same as main API)
// OLD credentials (commented out)
// define('DB_HOST', 'localhost');
// define('DB_NAME', 'playbdqv_engweb');
// define('DB_USER', 'playbdqv_engweb');
// define('DB_PASS', 'playbdqv_engweb');

// Database credentials (OLD - howdoyou.space - commented out)
// define('DB_HOST', 'localhost');
// define('DB_NAME', 'playbdqv_ensipayments');
// define('DB_USER', 'playbdqv_ensipayments');
// define('DB_PASS', 'playbdqv_ensipayments');

// Database credentials (ensi.online - ACTIVE)
define('DB_HOST', 'localhost');
define('DB_NAME', 'moodkuqp_ensi');
define('DB_USER', 'moodkuqp_ensi');
define('DB_PASS', 'moodkuqp_ensi');

// Admin session settings
define('ADMIN_SESSION_TIMEOUT', 3600); // 1 hour
define('ADMIN_SESSION_NAME', 'ensi_admin_session');

// Security settings
define('ADMIN_MAX_LOGIN_ATTEMPTS', 5);
define('ADMIN_LOCKOUT_TIME', 900); // 15 minutes

// Database connection
function getDBConnection() {
    try {
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
        $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);
        return $pdo;
    } catch (PDOException $e) {
        error_log("Database connection failed: " . $e->getMessage());
        return null;
    }
}

// JSON response helper
function jsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// Admin authentication check
function requireAdminAuth() {
    if (session_status() === PHP_SESSION_NONE) {
        session_name(ADMIN_SESSION_NAME);
        session_start();
    }
    
    if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_username'])) {
        header('Location: login.php');
        exit;
    }
    
    // Check session timeout
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > ADMIN_SESSION_TIMEOUT)) {
        session_unset();
        session_destroy();
        header('Location: login.php?timeout=1');
        exit;
    }
    
    $_SESSION['last_activity'] = time();
    return $_SESSION['admin_id'];
}

// Get current admin info
function getCurrentAdmin() {
    if (!isset($_SESSION['admin_id'])) {
        return null;
    }
    
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT id, username, full_name, email, role FROM admins WHERE id = ? AND is_active = 1");
    $stmt->execute([$_SESSION['admin_id']]);
    return $stmt->fetch();
}

// Log admin activity
function logAdminActivity($adminId, $action, $description = null) {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, description, ip_address, user_agent) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $adminId,
            $action,
            $description,
            $_SERVER['REMOTE_ADDR'] ?? null,
            $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
    } catch (Exception $e) {
        error_log("Failed to log admin activity: " . $e->getMessage());
    }
}

// Sanitize input
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

// Check admin role permission
function hasPermission($requiredRole = 'admin') {
    $admin = getCurrentAdmin();
    if (!$admin) return false;
    
    $roleHierarchy = ['super_admin' => 3, 'admin' => 2, 'moderator' => 1];
    $adminLevel = $roleHierarchy[$admin['role']] ?? 0;
    $requiredLevel = $roleHierarchy[$requiredRole] ?? 0;
    
    return $adminLevel >= $requiredLevel;
}
