<?php
// config.php - Konfiguracija za TapTap Card

// BITNO: Promijeni lozinku baze odmah!
define('DB_HOST', 'localhost');
define('DB_NAME', 'taptapcp_cardbaza');
define('DB_USER', 'taptapcp_cardbazauser');
define('DB_PASS', '(bC.vE}JY.@G?xCl');
define('DB_CHARSET', 'utf8mb4');

// SECURITY: Disable dangerous PHP functions
if (function_exists('ini_set')) {
    ini_set('expose_php', 0);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/error_log');
    ini_set('session.cookie_httponly', 1);
    ini_set('session.cookie_secure', 1);
    ini_set('session.cookie_samesite', 'Strict');
}

// SECURITY: Input sanitization helper
function sanitizeInput($data) {
    if (is_array($data)) {
        return array_map('sanitizeInput', $data);
    }
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// SECURITY: Validate slug format
function isValidSlug($slug) {
    return preg_match('/^[a-zA-Z0-9_-]{3,50}$/', $slug);
}

// SECURITY: Rate limiting (simple)
function checkRateLimit($ip, $action = 'general', $maxAttempts = 100, $timeWindow = 3600) {
    return; // PRIVREMENO ISKLJUČENO
}

// JWT Secret (PROMIJENI!)
define('JWT_SECRET', 'k9mP2vL8xQ4nR7wT3yU6sH1jF5gD0zC9bN8mK7lP4xW2qE5tY8uI3oA6sD9fG2hJ');

// Base URL
define('BASE_URL', 'https://card.taptap.ba');

// Uploads folder
define('UPLOAD_DIR', __DIR__ . '/uploads/');
define('UPLOAD_URL', BASE_URL . '/uploads/');

// Error reporting (production)
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Timezone
date_default_timezone_set('Europe/Sarajevo');

// 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) {
            http_response_code(500);
            die(json_encode(['error' => 'Greška pri spajanju na bazu']));
        }
    }
    
    return $pdo;
}

// Helper funkcije
function jsonResponse($data, $code = 200) {
    http_response_code($code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

function getAuthToken() {
    $headers = getallheaders();
    if (isset($headers['Authorization'])) {
        $auth = $headers['Authorization'];
        if (preg_match('/Bearer\s+(.*)$/i', $auth, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

function verifyToken($token) {
    if (!$token) return false;
    
    // Jednostavna JWT verifikacija (za produkciju koristi biblioteku)
    $parts = explode('.', $token);
    if (count($parts) !== 3) return false;
    
    list($header, $payload, $signature) = $parts;
    
    $valid_signature = hash_hmac('sha256', "$header.$payload", JWT_SECRET, true);
    $valid_signature = base64_encode($valid_signature);
    $valid_signature = str_replace(['+', '/', '='], ['-', '_', ''], $valid_signature);
    
    if ($signature !== $valid_signature) return false;
    
    $payload_data = json_decode(base64_decode($payload), true);
    
    if (!isset($payload_data['exp']) || $payload_data['exp'] < time()) {
        return false;
    }
    
    return $payload_data;
}

function createToken($admin_id, $remember = false) {
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    
    // Ako je remember me, token traje 30 dana, inače 24h
    $expiry = $remember ? (30 * 24 * 60 * 60) : (24 * 60 * 60);
    
    $payload = json_encode([
        'id' => $admin_id,
        'exp' => time() + $expiry
    ]);
    
    $base64_header = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64_payload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    $signature = hash_hmac('sha256', "$base64_header.$base64_payload", JWT_SECRET, true);
    $base64_signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    return "$base64_header.$base64_payload.$base64_signature";
}

function requireAuth() {
    $token = getAuthToken();
    $payload = verifyToken($token);
    
    if (!$payload) {
        jsonResponse(['error' => 'Neautorizirani pristup'], 401);
    }
    
    return $payload;
}

function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

function generateHtaccessRedirects($db) {
    $stmt = $db->query('SELECT old_slug, new_slug FROM slug_redirects');
    $redirects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $htaccess = file_get_contents('.htaccess');
    
    // Makni stare redirect linije
    $htaccess = preg_replace('/# SLUG REDIRECTS START.*# SLUG REDIRECTS END\n/s', '', $htaccess);
    
    // Dodaj nove
    $redirectLines = "\n# SLUG REDIRECTS START\n";
    foreach ($redirects as $r) {
        $redirectLines .= "Redirect 301 /{$r['old_slug']} /{$r['new_slug']}\n";
    }
    $redirectLines .= "# SLUG REDIRECTS END\n";
    
    file_put_contents('.htaccess', $htaccess . $redirectLines);
}

// Generiranje lozinke (6-8 znakova: slova, brojevi, . , ? -)
function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.?-';
    $password = '';
    $max = strlen($chars) - 1;
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[random_int(0, $max)];
    }
    
    return $password;
}

// Dohvati platform setting
function getPlatformSetting($key, $default = null) {
    $db = getDB();
    $stmt = $db->prepare('SELECT setting_value FROM platform_settings WHERE setting_key = ?');
    $stmt->execute([$key]);
    $result = $stmt->fetchColumn();
    return $result !== false ? $result : $default;
}

// Spremi platform setting
function savePlatformSetting($key, $value) {
    $db = getDB();
    $stmt = $db->prepare('REPLACE INTO platform_settings (setting_key, setting_value) VALUES (?, ?)');
    return $stmt->execute([$key, $value]);
}

// ========== USER TOKEN FUNKCIJE ==========

function createUserToken($user_id) {
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $payload = json_encode([
        'user_id' => $user_id,
        'type' => 'user',
        'exp' => time() + (30 * 24 * 60 * 60) // 30 dana
    ]);
    
    $base64_header = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64_payload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    $signature = hash_hmac('sha256', "$base64_header.$base64_payload", JWT_SECRET, true);
    $base64_signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    return "$base64_header.$base64_payload.$base64_signature";
}

function requireUserAuth() {
    $token = getAuthToken();
    $payload = verifyToken($token);
    
    if (!$payload || !isset($payload['user_id']) || $payload['type'] !== 'user') {
        jsonResponse(['error' => 'Neautorizirani pristup'], 401);
    }
    
    return $payload['user_id'];
}

// Upload slika
function uploadImage($file, $prefix = 'img') {
    $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    if (!in_array($file['type'], $allowed)) {
        return false;
    }
    
    if ($file['size'] > 5 * 1024 * 1024) { // 5MB max
        return false;
    }
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $prefix . '-' . time() . '-' . rand(1000, 9999) . '.' . $ext;
    $filepath = UPLOAD_DIR . $filename;
    
    if (!is_dir(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return '/uploads/' . $filename;
    }
    
    return false;
}

// ============================================
// ROLE & PERMISSION SISTEM
// ============================================

/**
 * Dohvati role korisnika iz baze
 * @param int $accountId - ID admina ili usera
 * @param string $accountType - 'admin' ili 'user'
 * @return string - role (super_admin, admin, reseller, user)
 */
function getUserRole($accountId, $accountType) {
    $db = getDB();
    
    if ($accountType === 'admin') {
        $stmt = $db->prepare('SELECT role FROM admin_users WHERE id = ?');
        $stmt->execute([$accountId]);
        $result = $stmt->fetch();
        return $result['role'] ?? 'admin';
    } else {
        $stmt = $db->prepare('SELECT role FROM user_accounts WHERE id = ?');
        $stmt->execute([$accountId]);
        $result = $stmt->fetch();
        return $result['role'] ?? 'user';
    }
}

/**
 * Provjeri da li role ima određeni permission
 * @param string $role
 * @param string $permission
 * @return bool
 */
function hasPermission($role, $permission) {
    $db = getDB();
    $stmt = $db->prepare('SELECT allowed FROM role_permissions WHERE role = ? AND permission = ?');
    $stmt->execute([$role, $permission]);
    $result = $stmt->fetch();
    
    // Ako nema explicitno definiran permission, deny po defaultu
    return $result ? (bool)$result['allowed'] : false;
}

/**
 * Require auth + role info (zamjena za stari requireAuth)
 * @return array - ['id' => X, 'account_type' => 'admin/user', 'role' => 'super_admin/admin/reseller/user', 'user_id' => Y]
 */
function requireAuthWithRole() {
    $token = getAuthToken();
    $payload = verifyToken($token);
    
    if (!$payload) {
        jsonResponse(['error' => 'Neautorizirani pristup'], 401);
    }
    
    // Token format: "account_id:account_type" (iz api.php linija 71)
    $tokenData = explode(':', $payload['id']);
    $accountId = (int)$tokenData[0];
    $accountType = $tokenData[1] ?? 'admin';
    
    $role = getUserRole($accountId, $accountType);
    
    // Za user account, dohvati user_id iz user_accounts
    $userId = null;
    if ($accountType === 'user') {
        $db = getDB();
        $stmt = $db->prepare('SELECT user_id FROM user_accounts WHERE id = ?');
        $stmt->execute([$accountId]);
        $result = $stmt->fetch();
        $userId = $result['user_id'] ?? null;
    } else {
        // Admin/reseller nema user_id, ali može imat created_by tracking
        $userId = $accountId;
    }
    
    return [
        'id' => $accountId,
        'account_type' => $accountType,
        'role' => $role,
        'user_id' => $userId
    ];
}

/**
 * Zahtijeva određeni permission - baca 403 ako nema
 * @param string $permission
 * @return array - auth data ako ima permission
 */
function requirePermission($permission) {
    $auth = requireAuthWithRole();
    
    if (!hasPermission($auth['role'], $permission)) {
        jsonResponse([
            'error' => 'Nemate dozvolu za ovu akciju',
            'required_permission' => $permission,
            'your_role' => $auth['role']
        ], 403);
    }
    
    return $auth;
}

/**
 * Dohvati package features za user_id
 * @param int $userId
 * @return array|null
 */
function getUserPackageFeatures($userId) {
    $db = getDB();
    
    // Dohvati package name
    $stmt = $db->prepare('SELECT package FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if (!$user || !$user['package']) {
        return null;
    }
    
    // Dohvati package features
    $stmt = $db->prepare('SELECT features FROM packages WHERE name = ?');
    $stmt->execute([$user['package']]);
    $pkg = $stmt->fetch();
    
    if (!$pkg) {
        return null;
    }
    
    return json_decode($pkg['features'], true);
}

/**
 * Provjeri može li user koristiti određeni modul
 * @param int $userId
 * @param string $moduleName
 * @return bool
 */
function canUseModule($userId, $moduleName) {
    $features = getUserPackageFeatures($userId);
    
    if (!$features || !isset($features['modules'])) {
        return false;
    }
    
    return in_array($moduleName, $features['modules']);
}
?>