<?php
// api.php - TapTap Card API v2 - Role & Permission System

require_once 'config.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// SECURITY: Rate limiting
$userIP = getUserIP();
checkRateLimit($userIP);

// SECURITY: Validate input size
if ($_SERVER['REQUEST_METHOD'] === 'POST' || $_SERVER['REQUEST_METHOD'] === 'PUT') {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    if (strpos($contentType, 'application/json') !== false) {
        $rawInput = file_get_contents('php://input');
        if (strlen($rawInput) > 1048576) { // 1MB limit
            jsonResponse(['error' => 'Payload prevelik'], 413);
        }
    }
}

// Dohvati path iz URL-a
$request_uri = $_SERVER['REQUEST_URI'];
$uri_parts = parse_url($request_uri);
$path = isset($uri_parts['path']) ? trim($uri_parts['path'], '/') : '';

$path = str_replace('api.php/', '', $path);
$path = str_replace('api.php', '', $path);

$method = $_SERVER['REQUEST_METHOD'];

// ===== ROUTING =====

// Health check
if ($path === 'api/health' || $path === 'health') {
    jsonResponse(['status' => 'OK', 'message' => 'API je aktivan']);
}

// ============================================
// AUTH ENDPOINTS
// ============================================

// AUTH - Login
elseif (($path === 'api/auth/login' || $path === 'auth/login') && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $username = $data['username'] ?? '';
    $password = $data['password'] ?? '';
    
    $db = getDB();
    
    // Provjeri admin_users
    $stmt = $db->prepare('SELECT *, "admin" as account_type FROM admin_users WHERE username = ?');
    $stmt->execute([$username]);
    $account = $stmt->fetch();
    
    // Ako nije admin, provjeri user_accounts
    if (!$account) {
        $stmt = $db->prepare('SELECT *, "user" as account_type FROM user_accounts WHERE email = ?');
        $stmt->execute([$username]);
        $account = $stmt->fetch();
    }
    
    if (!$account || !password_verify($password, $account['password'])) {
        jsonResponse(['error' => 'Pogrešni podaci'], 401);
    }
    
    $token = createToken($account['id'] . ':' . $account['account_type']);
    jsonResponse([
        'token' => $token, 
        'username' => $account['username'] ?? $account['email'],
        'role' => $account['role'] ?? 'user',
        'account_type' => $account['account_type']
    ]);
}

// PASSWORD RESET - Request
elseif (($path === 'api/auth/request-reset' || $path === 'auth/request-reset') && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $email = $data['email'] ?? '';
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        jsonResponse(['error' => 'Nevažeći email'], 400);
    }
    
    $db = getDB();
    
    // Provjeri postoji li account
    $stmt = $db->prepare('SELECT id FROM admin_users WHERE username = ?');
    $stmt->execute([$email]);
    $account = $stmt->fetch();
    
    if (!$account) {
        $stmt = $db->prepare('SELECT id FROM user_accounts WHERE email = ?');
        $stmt->execute([$email]);
        $account = $stmt->fetch();
    }
    
    if (!$account) {
        jsonResponse(['message' => 'Ako email postoji, poslali smo link']);
        exit;
    }
    
    // Generiraj token
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    // Spremi
    $stmt = $db->prepare('INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?) 
                          ON DUPLICATE KEY UPDATE token = ?, expires_at = ?');
    $stmt->execute([$email, $token, $expires, $token, $expires]);
    
    // Pošalji email
    $resetLink = "https://card.taptap.ba/admin.php?reset=$token";
    
    $to = $email;
    $subject = 'Reset lozinke - TapTap Card';
    $message = "Link za reset:\n$resetLink\n\nVrijedi 1 sat.";
    $headers = "From: no-reply@taptap.ba\r\n";
    
    mail($to, $subject, $message, $headers);
    
    jsonResponse(['message' => 'Ako email postoji, poslali smo link']);
}

// PASSWORD RESET - Confirm
elseif (($path === 'api/auth/reset-password' || $path === 'auth/reset-password') && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $token = $data['token'] ?? '';
    $newPassword = $data['password'] ?? '';
    
    if (strlen($newPassword) < 6) {
        jsonResponse(['error' => 'Lozinka minimalno 6 znakova'], 400);
    }
    
    $db = getDB();
    
    // Provjeri token
    $stmt = $db->prepare('SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW()');
    $stmt->execute([$token]);
    $reset = $stmt->fetch();
    
    if (!$reset) {
        jsonResponse(['error' => 'Token nevažeći ili istekao'], 400);
    }
    
    $email = $reset['email'];
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    
    // Update password
    $stmt = $db->prepare('UPDATE admin_users SET password = ? WHERE username = ?');
    $stmt->execute([$hashedPassword, $email]);
    
    if ($stmt->rowCount() === 0) {
        $stmt = $db->prepare('UPDATE user_accounts SET password = ? WHERE email = ?');
        $stmt->execute([$hashedPassword, $email]);
    }
    
    // Obriši token
    $stmt = $db->prepare('DELETE FROM password_resets WHERE token = ?');
    $stmt->execute([$token]);
    
    jsonResponse(['message' => 'Lozinka uspješno promijenjena']);
}

// ============================================
// USERS ENDPOINTS - Sada sa permission checkovima
// ============================================

// USERS - Get all (filtrirano po role)
elseif (($path === 'api/users' || $path === 'users') && $method === 'GET') {
    $auth = requirePermission('users.view_own'); // Svi moraju imati barem view_own
    
    $db = getDB();
    
    // Ako je reseller, vidi samo svoje
    if ($auth['role'] === 'reseller') {
        $stmt = $db->prepare('SELECT * FROM users WHERE created_by = ? AND created_by_type = ? ORDER BY created_at DESC');
        $stmt->execute([$auth['id'], 'reseller']);
    }
    // Ako je user, ne vidi ništa (ide na user/me endpoint)
    elseif ($auth['role'] === 'user') {
        $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$auth['user_id']]);
    }
    // Admin i super_admin vide sve
    else {
        $stmt = $db->query('SELECT * FROM users ORDER BY created_at DESC');
    }
    
    $users = $stmt->fetchAll();
    
    jsonResponse($users);
}

// USERS - Get one by ID or slug (sa permission checkom)
elseif (preg_match('#^(api/)?users/([a-zA-Z0-9_-]+)$#', $path, $matches) && $method === 'GET') {
    $identifier = $matches[2];
    
    $db = getDB();
    
    if (is_numeric($identifier)) {
        $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([$identifier]);
    } else {
        $stmt = $db->prepare('SELECT * FROM users WHERE slug = ?');
        $stmt->execute([$identifier]);
    }
    
    $user = $stmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'Korisnik nije pronađen'], 404);
    }
    
    // Provjeri permission - ako nije public poziv
    if (getAuthToken()) {
        $auth = requireAuthWithRole();
        
        // Reseller može vidjeti samo svoje
        if ($auth['role'] === 'reseller') {
            if ($user['created_by'] != $auth['id'] || $user['created_by_type'] !== 'reseller') {
                jsonResponse(['error' => 'Nemate pristup ovom korisniku'], 403);
            }
        }
        // User može vidjeti samo sebe
        elseif ($auth['role'] === 'user') {
            if ($user['id'] != $auth['user_id']) {
                jsonResponse(['error' => 'Nemate pristup ovom korisniku'], 403);
            }
        }
    }
    
    $stmt = $db->prepare('SELECT * FROM links WHERE user_id = ? ORDER BY sort_order');
    $stmt->execute([$user['id']]);
    $user['links'] = $stmt->fetchAll();
    
    $stmt = $db->prepare('SELECT * FROM modules WHERE user_id = ?');
    $stmt->execute([$user['id']]);
    $user['modules'] = $stmt->fetchAll();
    
    jsonResponse($user);
}

// USERS - Create or Update
elseif (preg_match('#^(api/)?users(/(\d+))?$#', $path, $matches) && $method === 'POST') {
    $isUpdate = isset($_POST['_method']) && $_POST['_method'] === 'PUT';
    
    // Permission check
    if ($isUpdate) {
        $auth = requirePermission('users.edit_own');
    } else {
        $auth = requirePermission('users.create');
    }
    
    $userId = $isUpdate ? ($_POST['user_id'] ?? ($matches[3] ?? null)) : null;
    
    if ($isUpdate && !$userId) {
        jsonResponse(['error' => 'Nedostaje user_id za update'], 400);
    }
    
    // Ako je reseller ili user, dodatna provjera
    if ($isUpdate) {
        $db = getDB();
        $stmt = $db->prepare('SELECT created_by, created_by_type FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $existingUser = $stmt->fetch();
        
        if ($auth['role'] === 'reseller') {
            if ($existingUser['created_by'] != $auth['id'] || $existingUser['created_by_type'] !== 'reseller') {
                jsonResponse(['error' => 'Nemate pravo mjenjati ovog korisnika'], 403);
            }
        } elseif ($auth['role'] === 'user') {
            if ($userId != $auth['user_id']) {
                jsonResponse(['error' => 'Nemate pravo mjenjati ovog korisnika'], 403);
            }
        }
    }
    
    $slug = $_POST['slug'] ?? '';
    
    // SECURITY: Validate slug
    if (!isValidSlug($slug)) {
        jsonResponse(['error'] => 'Nevažeći slug format (3-50 znakova, samo slova, brojevi, - i _)'], 400);
    }
    
    $ime = $_POST['ime'] ?? '';
    $prezime = $_POST['prezime'] ?? '';
    $opis = $_POST['opis'] ?? '';
    $email = $_POST['email'] ?? '';
    $telefon = $_POST['telefon'] ?? '';
    $whatsapp = $_POST['whatsapp'] ?? '';
    $viber = $_POST['viber'] ?? '';
    $adresa = $_POST['adresa'] ?? '';
    $grad = $_POST['grad'] ?? '';
    $drzava = $_POST['drzava'] ?? '';
    $displayTemplate = $_POST['display_template'] ?? 'business';
    $accentColor = $_POST['accent_color'] ?? '#3b82f6';
    $backgroundType = $_POST['background_type'] ?? 'accent';
    $backgroundColor = $_POST['background_color'] ?? null;
    $analyticsKey = $_POST['analytics_key'] ?? null;
    $analyticsShortCode = $_POST['analytics_short_code'] ?? null;
    $active = isset($_POST['active']) ? (int)$_POST['active'] : 1;
    $activeFrom = !empty($_POST['active_from']) ? $_POST['active_from'] : null;
    $activeUntil = !empty($_POST['active_until']) ? $_POST['active_until'] : null;
    $package = $_POST['package'] ?? 'basic'; // NOVO
    
    // Upload profilne slike
    $slika = null;
    if (isset($_FILES['slika']) && $_FILES['slika']['error'] === 0) {
        $slika = uploadImage($_FILES['slika'], 'profile');
    }
    
    // Upload background slike
    $backgroundImage = null;
    if (isset($_FILES['background_image']) && $_FILES['background_image']['error'] === 0) {
        $backgroundImage = uploadImage($_FILES['background_image'], 'bg');
    }
    
    $db = getDB();
    
    if ($isUpdate) {
        // UPDATE
        $updates = [];
        $params = [];
        
        $updates[] = 'slug = ?';
        $params[] = $slug;
        $updates[] = 'ime = ?';
        $params[] = $ime;
        $updates[] = 'prezime = ?';
        $params[] = $prezime;
        $updates[] = 'opis = ?';
        $params[] = $opis;
        $updates[] = 'email = ?';
        $params[] = $email;
        $updates[] = 'telefon = ?';
        $params[] = $telefon;
        $updates[] = 'whatsapp = ?';
        $params[] = $whatsapp;
        $updates[] = 'viber = ?';
        $params[] = $viber;
        $updates[] = 'adresa = ?';
        $params[] = $adresa;
        $updates[] = 'grad = ?';
        $params[] = $grad;
        $updates[] = 'drzava = ?';
        $params[] = $drzava;
        $updates[] = 'display_template = ?';
        $params[] = $displayTemplate;
        $updates[] = 'accent_color = ?';
        $params[] = $accentColor;
        $updates[] = 'background_type = ?';
        $params[] = $backgroundType;
        
        if ($backgroundColor) {
            $updates[] = 'background_color = ?';
            $params[] = $backgroundColor;
        }
        
        if ($analyticsKey) {
            $updates[] = 'analytics_key = ?';
            $params[] = $analyticsKey;
        }
        
        if ($analyticsShortCode) {
            $updates[] = 'analytics_short_code = ?';
            $params[] = $analyticsShortCode;
        }
        
        if ($slika) {
            $updates[] = 'slika = ?';
            $params[] = $slika;
        }
        
        if ($backgroundImage) {
            $updates[] = 'background_image = ?';
            $params[] = $backgroundImage;
        }
        
        // Samo admin/super_admin mogu mjenjati active status i paket
        if (in_array($auth['role'], ['super_admin', 'admin'])) {
            $updates[] = 'active = ?';
            $params[] = $active;
            $updates[] = 'active_from = ?';
            $params[] = $activeFrom;
            $updates[] = 'active_until = ?';
            $params[] = $activeUntil;
            $updates[] = 'package = ?';
            $params[] = $package;
        }
        
        $params[] = $userId;
        
        $sql = 'UPDATE users SET ' . implode(', ', $updates) . ' WHERE id = ?';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        
        jsonResponse(['message' => 'Korisnik ažuriran', 'user_id' => $userId]);
        
    } else {
        // CREATE
        $stmt = $db->prepare('INSERT INTO users (
            slug, ime, prezime, opis, email, telefon, whatsapp, viber, adresa, grad, drzava,
            display_template, accent_color, background_type, background_color, analytics_key, 
            analytics_short_code, slika, background_image, active, active_from, active_until,
            created_by, created_by_type, package
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        
        $createdByType = $auth['account_type'] === 'admin' ? 
            ($auth['role'] === 'reseller' ? 'reseller' : 'admin') : 
            'user';
        
        $stmt->execute([
            $slug, $ime, $prezime, $opis, $email, $telefon, $whatsapp, $viber, $adresa, $grad, $drzava,
            $displayTemplate, $accentColor, $backgroundType, $backgroundColor, $analyticsKey, 
            $analyticsShortCode, $slika, $backgroundImage, $active, $activeFrom, $activeUntil,
            $auth['id'], $createdByType, $package
        ]);
        
        $newUserId = $db->lastInsertId();
        
        // Dodaj defaultne module (ovisno o paketu)
        $features = getUserPackageFeatures($newUserId);
        if ($features && isset($features['modules'])) {
            $stmt = $db->prepare('INSERT INTO modules (user_id, modul_name, aktivan) VALUES (?, ?, 1)');
            foreach ($features['modules'] as $moduleName) {
                $stmt->execute([$newUserId, $moduleName]);
            }
        }
        
        // Pošalji email notifikaciju
        require_once 'email.php';
        $emailService = new EmailService();
        $createdByName = $auth['account_type'] === 'admin' ? 
            ($stmt = $db->prepare('SELECT username FROM admin_users WHERE id = ?'), $stmt->execute([$auth['id']]), ($r = $stmt->fetch()) ? $r['username'] : 'Admin') :
            ($stmt = $db->prepare('SELECT email FROM user_accounts WHERE id = ?'), $stmt->execute([$auth['id']]), ($r = $stmt->fetch()) ? $r['email'] : 'User');
        
        $emailService->sendAccountCreatedEmail($createdByName, $auth['role'], [
            'ime' => $ime,
            'prezime' => $prezime,
            'slug' => $slug,
            'email' => $email,
            'package' => $package,
            'active' => $active,
            'active_from' => $activeFrom,
            'active_until' => $activeUntil
        ]);
        
        jsonResponse(['message' => 'Korisnik kreiran', 'user_id' => $newUserId]);
    }
}

// USERS - Delete
elseif (preg_match('#^(api/)?users/(\d+)$#', $path, $matches) && $method === 'DELETE') {
    $auth = requirePermission('users.delete');
    $userId = $matches[2];
    
    $db = getDB();
    
    // Provjeri može li brisati (reseller može brisati samo svoje)
    if ($auth['role'] === 'reseller') {
        $stmt = $db->prepare('SELECT created_by, created_by_type FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        if (!$user || $user['created_by'] != $auth['id'] || $user['created_by_type'] !== 'reseller') {
            jsonResponse(['error' => 'Nemate pravo brisati ovog korisnika'], 403);
        }
    }
    
    // Super admin ne može biti obrisan od strane admina
    if ($auth['role'] === 'admin') {
        $stmt = $db->prepare('SELECT created_by_type FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        if ($user && $user['created_by_type'] === 'super_admin') {
            jsonResponse(['error' => 'Ne možete brisati korisnike kreirane od super admina'], 403);
        }
    }
    
    // Obriši
    $stmt = $db->prepare('DELETE FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    
    // Obriši povezane podatke
    $stmt = $db->prepare('DELETE FROM links WHERE user_id = ?');
    $stmt->execute([$userId]);
    
    $stmt = $db->prepare('DELETE FROM modules WHERE user_id = ?');
    $stmt->execute([$userId]);
    
    $stmt = $db->prepare('DELETE FROM user_accounts WHERE user_id = ?');
    $stmt->execute([$userId]);
    
    jsonResponse(['message' => 'Korisnik obrisan']);
}

// ============================================
// ADMIN MANAGEMENT ENDPOINTS
// ============================================

// CREATE RESELLER
elseif (($path === 'api/admin/create-reseller' || $path === 'admin/create-reseller') && $method === 'POST') {
    $auth = requirePermission('resellers.create');
    
    $data = json_decode(file_get_contents('php://input'), true);
    $username = $data['username'] ?? '';
    $password = $data['password'] ?? '';
    
    if (strlen($username) < 3 || strlen($password) < 6) {
        jsonResponse(['error' => 'Username minimalno 3, lozinka minimalno 6 znakova'], 400);
    }
    
    $db = getDB();
    
    // Provjeri postoji li već
    $stmt = $db->prepare('SELECT id FROM admin_users WHERE username = ?');
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Username već postoji'], 400);
    }
    
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    $stmt = $db->prepare('INSERT INTO admin_users (username, password, role) VALUES (?, ?, ?)');
    $stmt->execute([$username, $hashedPassword, 'reseller']);
    
    $resellerId = $db->lastInsertId();
    
    // Email notifikacija
    $message = "
═══════════════════════════════════════
   NOVI RESELLER ACCOUNT KREIRAN
═══════════════════════════════════════

KREIRAO:       {$auth['id']} ({$auth['role']})
DATUM:         " . date('d.m.Y H:i') . "

NOVI RESELLER:
  • Username:  {$username}
  • Role:      reseller
  • ID:        {$resellerId}

═══════════════════════════════════════
";
    
    mail('info@taptap.ba', 'Novi RESELLER account kreiran', $message, "From: no-reply@taptap.ba\r\n");
    
    jsonResponse(['message' => 'Reseller kreiran', 'reseller_id' => $resellerId]);
}

// CREATE ADMIN
elseif (($path === 'api/admin/create-admin' || $path === 'admin/create-admin') && $method === 'POST') {
    $auth = requirePermission('admins.create'); // Samo super_admin
    
    $data = json_decode(file_get_contents('php://input'), true);
    $username = $data['username'] ?? '';
    $password = $data['password'] ?? '';
    
    if (strlen($username) < 3 || strlen($password) < 6) {
        jsonResponse(['error' => 'Username minimalno 3, lozinka minimalno 6 znakova'], 400);
    }
    
    $db = getDB();
    
    // Provjeri postoji li već
    $stmt = $db->prepare('SELECT id FROM admin_users WHERE username = ?');
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Username već postoji'], 400);
    }
    
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    $stmt = $db->prepare('INSERT INTO admin_users (username, password, role) VALUES (?, ?, ?)');
    $stmt->execute([$username, $hashedPassword, 'admin']);
    
    $adminId = $db->lastInsertId();
    
    // Email notifikacija
    $message = "
═══════════════════════════════════════
   NOVI ADMIN ACCOUNT KREIRAN
═══════════════════════════════════════

KREIRAO:       {$auth['id']} (super_admin)
DATUM:         " . date('d.m.Y H:i') . "

NOVI ADMIN:
  • Username:  {$username}
  • Role:      admin
  • ID:        {$adminId}

═══════════════════════════════════════
";
    
    mail('info@taptap.ba', 'Novi ADMIN account kreiran', $message, "From: no-reply@taptap.ba\r\n");
    
    jsonResponse(['message' => 'Admin kreiran', 'admin_id' => $adminId]);
}

// CREATE USER ACCOUNT (login za običnog usera)
elseif (($path === 'api/admin/create-user-account' || $path === 'admin/create-user-account') && $method === 'POST') {
    $auth = requirePermission('users.create');
    
    $data = json_decode(file_get_contents('php://input'), true);
    $userId = $data['user_id'] ?? 0;
    $email = $data['email'] ?? '';
    $password = $data['password'] ?? generatePassword(8);
    
    if (!$userId || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        jsonResponse(['error' => 'Nedostaju podaci'], 400);
    }
    
    $db = getDB();
    
    // Provjeri postoji li user
    $stmt = $db->prepare('SELECT id FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    if (!$stmt->fetch()) {
        jsonResponse(['error' => 'User ne postoji'], 404);
    }
    
    // Provjeri postoji li već account
    $stmt = $db->prepare('SELECT id FROM user_accounts WHERE user_id = ? OR email = ?');
    $stmt->execute([$userId, $email]);
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Account već postoji'], 400);
    }
    
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
    $stmt = $db->prepare('INSERT INTO user_accounts (user_id, email, password, role) VALUES (?, ?, ?, ?)');
    $stmt->execute([$userId, $email, $hashedPassword, 'user']);
    
    // Pošalji email s pristupnim podacima
    $message = "
Vaš TapTap Card login je spreman!

Email: {$email}
Lozinka: {$password}

Login: https://card.taptap.ba/admin.php
";
    
    mail($email, 'Vaš TapTap Card pristup', $message, "From: no-reply@taptap.ba\r\n");
    
    jsonResponse(['message' => 'User account kreiran', 'email' => $email, 'password' => $password]);
}

// ============================================
// ROLE MANAGER ENDPOINTS
// ============================================

// GET ALL ROLES & PERMISSIONS
elseif (($path === 'api/roles/permissions' || $path === 'roles/permissions') && $method === 'GET') {
    $auth = requirePermission('roles.manage');
    
    $db = getDB();
    $stmt = $db->query('SELECT * FROM role_permissions ORDER BY role, permission');
    $permissions = $stmt->fetchAll();
    
    // Grupiraj po rolama
    $grouped = [];
    foreach ($permissions as $perm) {
        $role = $perm['role'];
        if (!isset($grouped[$role])) {
            $grouped[$role] = [];
        }
        $grouped[$role][] = [
            'permission' => $perm['permission'],
            'allowed' => (bool)$perm['allowed']
        ];
    }
    
    jsonResponse($grouped);
}

// UPDATE ROLE PERMISSION
elseif (($path === 'api/roles/permissions' || $path === 'roles/permissions') && $method === 'POST') {
    $auth = requirePermission('roles.manage');
    
    $data = json_decode(file_get_contents('php://input'), true);
    $role = $data['role'] ?? '';
    $permission = $data['permission'] ?? '';
    $allowed = isset($data['allowed']) ? (int)$data['allowed'] : 1;
    
    if (!$role || !$permission) {
        jsonResponse(['error' => 'Nedostaju podaci'], 400);
    }
    
    // Ne dopusti mijenjanje super_admin permissiona
    if ($role === 'super_admin') {
        jsonResponse(['error' => 'Ne možete mjenjati super_admin permissione'], 403);
    }
    
    $db = getDB();
    $stmt = $db->prepare('UPDATE role_permissions SET allowed = ? WHERE role = ? AND permission = ?');
    $stmt->execute([$allowed, $role, $permission]);
    
    jsonResponse(['message' => 'Permission ažuriran']);
}

// ============================================
// PACKAGES ENDPOINTS
// ============================================

// GET ALL PACKAGES
elseif (($path === 'api/packages' || $path === 'packages') && $method === 'GET') {
    // Public endpoint
    $db = getDB();
    $stmt = $db->query('SELECT * FROM packages ORDER BY price ASC');
    $packages = $stmt->fetchAll();
    
    jsonResponse($packages);
}

// ============================================
// ANALYTICS & CONTACT (bez izmjena)
// ============================================

// CONTACT - Send message
elseif (preg_match('#^(api/)?contact/(\d+)$#', $path, $matches) && $method === 'POST') {
    $userId = $matches[2];
    $data = json_decode(file_get_contents('php://input'), true);
    
    $senderName = $data['sender_name'] ?? '';
    $senderEmail = $data['sender_email'] ?? '';
    $senderPhone = $data['sender_phone'] ?? '';
    $message = $data['message'] ?? '';
    
    if (!$senderName || !$senderEmail || !$message) {
        jsonResponse(['error' => 'Nedostaju podaci'], 400);
    }
    
    $db = getDB();
    
    // Spremi u bazu
    $stmt = $db->prepare('INSERT INTO contact_messages (user_id, sender_name, sender_email, sender_phone, message) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$userId, $senderName, $senderEmail, $senderPhone, $message]);
    
    // Dohvati user email
    $stmt = $db->prepare('SELECT email FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if ($user && $user['email']) {
        $to = $user['email'];
        $subject = 'Nova poruka sa TapTap kartice';
        $mailMessage = "Od: {$senderName} ({$senderEmail})\nTelefon: {$senderPhone}\n\n{$message}";
        $headers = "From: no-reply@taptap.ba\r\n";
        
        mail($to, $subject, $mailMessage, $headers);
    }
    
    jsonResponse(['message' => 'Poruka poslana']);
}

// ANALYTICS - Track event
elseif (($path === 'api/analytics' || $path === 'analytics') && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $userId = $data['user_id'] ?? 0;
    $eventType = $data['event_type'] ?? '';
    $eventData = $data['event_data'] ?? [];
    
    if (!$userId || !$eventType) {
        jsonResponse(['error' => 'Nedostaju podaci'], 400);
    }
    
    $db = getDB();
    $stmt = $db->prepare('INSERT INTO analytics (user_id, event_type, event_data) VALUES (?, ?, ?)');
    $stmt->execute([$userId, $eventType, json_encode($eventData)]);
    
    jsonResponse(['message' => 'Event tracked']);
}

// ============================================
// USER PANEL ENDPOINTS
// ============================================

// USER - Get current user (me)
elseif (($path === 'api/user/me' || $path === 'user/me') && $method === 'GET') {
    $userId = requireUserAuth();
    
    $db = getDB();
    $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if (!$user) {
        jsonResponse(['error' => 'Korisnik nije pronađen'], 404);
    }
    
    // Dohvati linkove
    $stmt = $db->prepare('SELECT * FROM links WHERE user_id = ? ORDER BY sort_order');
    $stmt->execute([$userId]);
    $user['links'] = $stmt->fetchAll();
    
    // Dohvati module
    $stmt = $db->prepare('SELECT * FROM modules WHERE user_id = ?');
    $stmt->execute([$userId]);
    $modules = $stmt->fetchAll();
    
    // Parsiraj config JSON
    foreach ($modules as &$module) {
        if ($module['config']) {
            $module['config'] = json_decode($module['config'], true);
        }
    }
    $user['modules'] = $modules;
    
    jsonResponse($user);
}

// USER - Update profile
elseif (($path === 'api/user/profile' || $path === 'user/profile') && $method === 'POST') {
    $userId = requireUserAuth();
    $data = json_decode(file_get_contents('php://input'), true);
    
    $db = getDB();
    $stmt = $db->prepare('UPDATE users SET 
        ime = ?, prezime = ?, opis = ?, email = ?, telefon = ?, 
        whatsapp = ?, viber = ?, adresa = ?, grad = ?, drzava = ?
        WHERE id = ?');
    
    $stmt->execute([
        $data['ime'] ?? '',
        $data['prezime'] ?? '',
        $data['opis'] ?? '',
        $data['email'] ?? '',
        $data['telefon'] ?? '',
        $data['whatsapp'] ?? '',
        $data['viber'] ?? '',
        $data['adresa'] ?? '',
        $data['grad'] ?? '',
        $data['drzava'] ?? '',
        $userId
    ]);
    
    jsonResponse(['message' => 'Profil ažuriran']);
}

// USER - Update design (with image upload)
elseif (($path === 'api/user/design' || $path === 'user/design') && $method === 'POST') {
    $userId = requireUserAuth();
    
    $db = getDB();
    $updates = [];
    $params = [];
    
    // Accent color
    if (isset($_POST['accent_color'])) {
        $updates[] = 'accent_color = ?';
        $params[] = $_POST['accent_color'];
    }
    
    // Background image upload
    if (isset($_FILES['background_image']) && $_FILES['background_image']['error'] === 0) {
        $upload = uploadImage($_FILES['background_image'], 'bg');
        if ($upload) {
            $updates[] = 'background_image = ?';
            $params[] = $upload;
        }
    }
    
    // Profile image upload
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === 0) {
        $upload = uploadImage($_FILES['profile_image'], 'profile');
        if ($upload) {
            $updates[] = 'slika = ?';
            $params[] = $upload;
        }
    }
    
    if (count($updates) > 0) {
        $params[] = $userId;
        $sql = 'UPDATE users SET ' . implode(', ', $updates) . ' WHERE id = ?';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
    }
    
    jsonResponse(['message' => 'Dizajn ažuriran']);
}

// USER - Update links
elseif (($path === 'api/user/links' || $path === 'user/links') && $method === 'POST') {
    $userId = requireUserAuth();
    $data = json_decode(file_get_contents('php://input'), true);
    $links = $data['links'] ?? [];
    
    $db = getDB();
    
    // Obriši stare
    $stmt = $db->prepare('DELETE FROM links WHERE user_id = ?');
    $stmt->execute([$userId]);
    
    // Dodaj nove
    $stmt = $db->prepare('INSERT INTO links (user_id, tip, url, sort_order) VALUES (?, ?, ?, ?)');
    foreach ($links as $index => $link) {
        if (!empty($link['url'])) {
            $stmt->execute([$userId, $link['tip'], $link['url'], $index]);
        }
    }
    
    jsonResponse(['message' => 'Linkovi ažurirani']);
}

// USER - Update module
elseif (($path === 'api/user/module' || $path === 'user/module') && $method === 'POST') {
    $userId = requireUserAuth();
    $data = json_decode(file_get_contents('php://input'), true);
    $moduleName = $data['module_name'] ?? '';
    $config = $data['config'] ?? [];
    
    $db = getDB();
    
    // Provjeri je li modul zaključan
    $stmt = $db->prepare('SELECT locked FROM modules WHERE user_id = ? AND modul_name = ?');
    $stmt->execute([$userId, $moduleName]);
    $module = $stmt->fetch();
    
    if ($module && $module['locked']) {
        jsonResponse(['error' => 'Ovaj modul je zaključao administrator'], 403);
    }
    
    // Provjeri može li koristiti modul prema paketu
    if (!canUseModule($userId, $moduleName)) {
        jsonResponse(['error' => 'Vaš paket ne podržava ovaj modul'], 403);
    }
    
    // Update config
    $stmt = $db->prepare('UPDATE modules SET config = ? WHERE user_id = ? AND modul_name = ?');
    $stmt->execute([json_encode($config), $userId, $moduleName]);
    
    jsonResponse(['message' => 'Modul ažuriran']);
}

// USER - Contact form (poslano sa public kartice)
elseif (($path === 'api/user/contact' || $path === 'user/contact') && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $userId = $data['user_id'] ?? 0;
    $senderName = $data['sender_name'] ?? '';
    $senderEmail = $data['sender_email'] ?? '';
    $message = $data['message'] ?? '';
    
    if (!$userId || !$senderName || !$senderEmail || !$message) {
        jsonResponse(['error' => 'Nedostaju podaci'], 400);
    }
    
    $db = getDB();
    
    // Spremi u bazu
    $stmt = $db->prepare('INSERT INTO contact_messages (user_id, sender_name, sender_email, message) VALUES (?, ?, ?, ?)');
    $stmt->execute([$userId, $senderName, $senderEmail, $message]);
    
    // Dohvati user email
    $stmt = $db->prepare('SELECT email FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    if ($user && $user['email']) {
        require_once 'email.php';
        $emailService = new EmailService();
        $emailService->sendContactMessage($user['email'], $senderName, $senderEmail, $message);
    }
    
    jsonResponse(['message' => 'Poruka poslana']);
}

// Not found
else {
    jsonResponse([
        'error' => 'Endpoint nije pronađen',
        'debug' => [
            'path' => $path,
            'method' => $method,
            'uri' => $request_uri
        ]
    ], 404);
}
?>
