<?php
require_once __DIR__ . '/includes/header.php';

if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name'];
$role        = $_SESSION['role'];

if (!in_array($role, ['master','super-reseller','reseller'], true)) {
    die('Access denied');
}

$targetUser = sanitize($_GET['username'] ?? '');
if ($targetUser === '') die('User not specified');

if ($role === 'master') {
    $userData = $db->select('menualuser', '*', 'username = :u', '', [':u' => $targetUser]);
} else {
    $userData = $db->select('menualuser', '*', 'username = :u AND parent = :p', '', [':u' => $targetUser, ':p' => $currentUser]);
}
if (!$userData) die('Access denied');

$user = $userData[0];

$me = $db->select('menualuser', 'credits', 'username = :u', '', [':u' => $currentUser]);
$myCredits = $me[0]['credits'] ?? ($_SESSION['credits'] ?? 0);
$myUnlimited = ($role === 'master') ? true : is_unlimited_credits($myCredits);

if (isset($_POST['save_changes'])) {
    $newPass = sanitize($_POST['password'] ?? '');
    $creditsChange = (int)($_POST['credits'] ?? 0);
    $markUnlimited = isset($_POST['credits_unlimited']) && $_POST['credits_unlimited'] === '1';

    $updateData = ['password' => $newPass];

    if ($role === 'master' && isset($_POST['role'])) {
        $newRole = sanitize($_POST['role']);
        if (in_array($newRole, ['reseller', 'super-reseller'], true)) {
            $updateData['role'] = $newRole;
        }
    }

    $db->update('menualuser', $updateData, 'username = :u', [':u' => $targetUser]);

    if ($role === 'master' && $markUnlimited) {
        $db->update('menualuser', ['credits' => -1], 'username = :u', [':u' => $targetUser]);
        $db->insert('credit_history', [
            'actor' => $currentUser,
            'target' => $targetUser,
            'action' => 'SET_UNLIMITED_CREDITS',
            'amount' => 0
        ]);
        header("Location: myteam.php");
        exit;
    }

    if ($creditsChange !== 0) {
        $currentCredits = is_unlimited_credits($user['credits']) ? -1 : (int)$user['credits'];
        $allowedChange = $creditsChange;

        if ($role === 'super-reseller' && $creditsChange > 0 && !$myUnlimited) {
            $available = (int)$myCredits;
            if ($creditsChange > $available) {
                $allowedChange = $available;
            }
            $db->update('menualuser', ['credits' => ($available - $allowedChange)], 'username = :u', [':u' => $currentUser]);
        }

        if (!is_unlimited_credits($user['credits'])) {
            $newCredits = max(0, $currentCredits + $allowedChange);
            $db->update('menualuser', ['credits' => $newCredits], 'username = :u', [':u' => $targetUser]);
        }

        $db->insert('credit_history', [
            'actor' => $currentUser,
            'target' => $targetUser,
            'action' => $allowedChange > 0 ? 'ADD_CREDITS' : 'REMOVE_CREDITS',
            'amount' => abs($allowedChange)
        ]);
    }

    header("Location: myteam.php");
    exit;
}
?>

<div class="col-md-6 mx-auto">
<div class="card text-white bg-dark shadow">
<div class="card-header bg-warning text-dark">
<h4><i class="fa fa-user-edit"></i> Edit User: <?=htmlspecialchars($targetUser)?></h4>
</div>

<div class="card-body">
<form method="post">

<div class="form-group mb-3">
<label>Username (readonly)</label>
<input type="text" class="form-control bg-secondary text-white"
value="<?=htmlspecialchars($user['username'])?>" readonly>
</div>

<div class="form-group mb-3">
<label>Password</label>
<input type="text" name="password" class="form-control"
value="<?=htmlspecialchars($user['password'])?>" required>
</div>

<div class="form-group mb-3">
<label>Credits (use negative to subtract)</label>
<input type="number" name="credits" id="creditsInput" class="form-control" placeholder="Ej: 10 or -5" <?=is_unlimited_credits($user['credits']) ? 'disabled' : ''?>>
<small>Current credits: <strong><?=credits_display($user['credits'])?></strong></small>
<?php if($role==='super-reseller'): ?>
    <small class="d-block">Your available credits: <strong><?=credits_display($myCredits)?></strong></small>
<?php endif; ?>
<?php if ($role === 'master'): ?>
    <div class="form-check mt-2">
        <input type="checkbox" class="form-check-input" id="creditsUnlimited" name="credits_unlimited" value="1" onchange="toggleUnlimitedCredits()" <?=is_unlimited_credits($user['credits']) ? 'checked' : ''?>>
        <label class="form-check-label" for="creditsUnlimited">Dejar créditos ilimitados</label>
    </div>
<?php endif; ?>
</div>

<?php if($role==='master'): ?>
<div class="form-group mb-3">
<label>Role</label>
<select name="role" class="form-control">
<option value="reseller" <?=$user['role']=='reseller'?'selected':''?>>Reseller</option>
<option value="super-reseller" <?=$user['role']=='super-reseller'?'selected':''?>>Super Reseller</option>
</select>
</div>
<?php endif; ?>

<button type="submit" name="save_changes" class="btn btn-warning w-100">
<i class="fa fa-save"></i> Save All Changes
</button>

</form>
</div>
</div>
</div>

<script>
function toggleUnlimitedCredits() {
    var chk = document.getElementById('creditsUnlimited');
    var input = document.getElementById('creditsInput');
    if (!chk || !input) return;
    input.disabled = chk.checked;
    if (chk.checked) {
        input.value = 0;
    }
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
