<?php
/**
 * Asset Card Manager
 * Handles CRUD operations for activated asset cards database
 */

// Detect and start the correct user session
require_once __DIR__ . '/session_manager.php';

$isLoggedIn = detectAndStartUserSession();

header('Content-Type: application/json');

$databasePath = '../js/database/activated-asset-cards.json';

// Get current username from session
if (!$isLoggedIn || !isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in', 'debug' => 'No session found']);
    exit;
}

$username = $_SESSION['username'];

// Read database
function readDatabase($path) {
    if (!file_exists($path)) {
        return [];
    }
    $content = file_get_contents($path);
    return json_decode($content, true) ?? [];
}

// Write database
function writeDatabase($path, $data) {
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    return file_put_contents($path, $json) !== false;
}

// Get request data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

$response = ['success' => false, 'message' => ''];

switch ($action) {
    case 'load':
        // Load all asset cards for current user
        $database = readDatabase($databasePath);
        $userCards = $database[$username] ?? [];
        $response = ['success' => true, 'data' => $userCards];
        break;

    case 'add':
        // Add new asset card
        $assetName = $input['assetName'] ?? '';
        $active = $input['active'] ?? true;
        $pinned = $input['pinned'] ?? false;

        if (empty($assetName)) {
            $response['message'] = 'Asset name is required';
            break;
        }

        $database = readDatabase($databasePath);
        
        if (!isset($database[$username])) {
            $database[$username] = [];
        }

        // Set all other cards to inactive if this one is active
        if ($active) {
            foreach ($database[$username] as $key => $card) {
                $database[$username][$key]['status']['active'] = false;
            }
        }

        $database[$username][$assetName] = [
            'status' => [
                'active' => $active,
                'pinned' => $pinned
            ],
            'creation' => [
                'date' => date('d-m-Y'),
                'time' => date('H:i:s'),
                'utc' => '+06:00'
            ],
            'manualPercentage' => [
                'status' => false,
                'percentage' => 80
            ]
        ];

        if (writeDatabase($databasePath, $database)) {
            $response = ['success' => true, 'message' => 'Asset card added'];
        } else {
            $response['message'] = 'Failed to write database';
        }
        break;

    case 'update':
        // Update asset card (active/pinned status)
        $assetName = $input['assetName'] ?? '';
        $active = $input['active'] ?? null;
        $pinned = $input['pinned'] ?? null;

        if (empty($assetName)) {
            $response['message'] = 'Asset name is required';
            break;
        }

        $database = readDatabase($databasePath);

        if (!isset($database[$username][$assetName])) {
            $response['message'] = 'Asset card not found';
            break;
        }

        // If setting active to true, set all others to false
        if ($active === true) {
            foreach ($database[$username] as $key => $card) {
                $database[$username][$key]['status']['active'] = false;
            }
        }

        if ($active !== null) {
            $database[$username][$assetName]['status']['active'] = $active;
        }
        if ($pinned !== null) {
            $database[$username][$assetName]['status']['pinned'] = $pinned;
        }

        if (writeDatabase($databasePath, $database)) {
            $response = ['success' => true, 'message' => 'Asset card updated'];
        } else {
            $response['message'] = 'Failed to write database';
        }
        break;

    case 'remove':
        // Remove asset card
        $assetName = $input['assetName'] ?? '';

        if (empty($assetName)) {
            $response['message'] = 'Asset name is required';
            break;
        }

        $database = readDatabase($databasePath);

        if (isset($database[$username][$assetName])) {
            unset($database[$username][$assetName]);

            if (writeDatabase($databasePath, $database)) {
                $response = ['success' => true, 'message' => 'Asset card removed'];
            } else {
                $response['message'] = 'Failed to write database';
            }
        } else {
            $response['message'] = 'Asset card not found';
        }
        break;

    case 'sync':
        // Sync all cards from frontend
        $cards = $input['cards'] ?? [];

        $database = readDatabase($databasePath);
        $database[$username] = [];

        foreach ($cards as $card) {
            $assetName = $card['name'] ?? '';
            if (!empty($assetName)) {
                $database[$username][$assetName] = [
                    'status' => [
                        'active' => $card['active'] ?? false,
                        'pinned' => $card['pinned'] ?? false
                    ],
                    'creation' => $card['creation'] ?? [
                        'date' => date('d-m-Y'),
                        'time' => date('H:i:s'),
                        'utc' => '+06:00'
                    ]
                ];
            }
        }

        if (writeDatabase($databasePath, $database)) {
            $response = ['success' => true, 'message' => 'Asset cards synced'];
        } else {
            $response['message'] = 'Failed to write database';
        }
        break;

    case 'updatePercentage':
        // Update manual payout percentage for asset
        $assetName = $input['assetName'] ?? '';
        $percentage = $input['percentage'] ?? null;
        $status = $input['status'] ?? false;

        if (empty($assetName)) {
            $response['message'] = 'Asset name is required';
            break;
        }

        if ($percentage !== null && ($percentage < 20 || $percentage > 93)) {
            $response['message'] = 'Percentage must be between 20 and 93';
            break;
        }

        $database = readDatabase($databasePath);

        if (!isset($database[$username][$assetName])) {
            $response['message'] = 'Asset card not found';
            break;
        }

        $database[$username][$assetName]['manualPercentage'] = [
            'status' => $status,
            'percentage' => $percentage ?? 80
        ];

        if (writeDatabase($databasePath, $database)) {
            $response = ['success' => true, 'message' => 'Payout percentage updated'];
        } else {
            $response['message'] = 'Failed to write database';
        }
        break;

    default:
        $response['message'] = 'Invalid action';
}

echo json_encode($response);
