<?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'])) {
    die('Access denied');
}

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

// FETCH USER DATA
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];

/* =======================
   PROCESS FORM
======================= */
if(isset($_POST['save_changes'])){
    $newPass = sanitize($_POST['password']);
    $creditsChange = intval($_POST['credits']); // puede ser + o -

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

    // MASTER solo puede cambiar rol
    if($role==='master' && isset($_POST['role'])){
        $newRole = $_POST['role'];
        if(in_array($newRole,['reseller','super-reseller'])){
            $updateData['role'] = $newRole;
        }
    }

    // ACTUALIZA PASSWORD Y ROLE
    $db->update('menualuser',$updateData,'username = :u',[':u'=>$targetUser]);

    // ACTUALIZA CREDITS
    if($creditsChange !== 0){
        $currentCredits = intval($user['credits']);
        $allowedChange = $creditsChange;

        // RESTRICCIÓN: super-reseller no puede dar más de sus créditos
        if($role==='super-reseller' && $creditsChange > 0){
            $superCredits = intval($_SESSION['credits']);
            if($creditsChange > $superCredits){
                $allowedChange = $superCredits;
            }
            // se resta del super-reseller
            $_SESSION['credits'] -= $allowedChange;
            $db->update('menualuser',['credits'=>$_SESSION['credits']],'username = :u',[':u'=>$currentUser]);
        }

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

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

    // REDIRIGE A MYTEAM
    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" class="form-control" placeholder="Ej: 10 or -5">
<small>Current credits: <strong><?=$user['credits']?></strong></small>
<?php if($role==='super-reseller'): ?>
    <small>Your available credits: <strong><?=$_SESSION['credits']?></strong></small>
<?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>

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