<?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('Acceso denegado');
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) die('ID inválido');

if ($role === 'master') {
    $client = $db->select('codes', '*', 'id = :id', '', [':id' => $id]);
} elseif ($role === 'super-reseller') {
    $owners = get_visible_client_owners($db, $role, $currentUser);
    $in = build_in_clause_params($owners, ':o');
    $params = array_merge([':id' => $id], $in['params']);
    $client = $db->select('codes', '*', "id = :id AND owner IN ({$in['sql']})", '', $params);
} else {
    $client = $db->select('codes', '*', 'id = :id AND owner = :o', '', [':id' => $id, ':o' => $currentUser]);
}

if (!$client) die('Cliente no encontrado');
$client = $client[0];

$me = $db->select('menualuser', 'credits', 'username = :u', '', [':u' => $currentUser]);
$myCredits = ($role === 'master') ? -1 : ($me[0]['credits'] ?? 0);
$myUnlimited = ($role === 'master') ? true : is_unlimited_credits($myCredits);
$downloadUrl = (string) settings_get($db, 'app_download_url', '');
$downloaderCode = (string) settings_get($db, 'app_downloader_code', '');

if ($_POST) {
    $client_name = trim($_POST['client_name'] ?? '');
    $client_whatsapp = trim($_POST['client_whatsapp'] ?? '');
    $status = in_array($_POST['status'] ?? 'active', ['active','blocked'], true) ? $_POST['status'] : 'active';
    $months = max(1, (int)($_POST['months'] ?? 1));

    if ($client_name === '' || $client_whatsapp === '') {
        $error = 'Nombre y WhatsApp son obligatorios';
    } elseif (!$myUnlimited && $role !== 'master' && $months > (int)$myCredits) {
        $error = 'No tienes créditos suficientes para cambiar el plan';
    } else {
        $current_exp = $client['expires_at'] ?? date('Y-m-d');
        $new_expiration = date('Y-m-d', strtotime('+' . $months . ' months', strtotime($current_exp)));
        $db->update('codes', [
            'client_name' => $client_name,
            'client_whatsapp' => $client_whatsapp,
            'expires_at' => $new_expiration,
            'status' => $status
        ], 'id = :id', [':id' => $id]);

        if ($role !== 'master' && !$myUnlimited) {
            $db->update('menualuser', ['credits' => ((int)$myCredits - $months)], 'username = :u', [':u' => $currentUser]);
        }

        echo "<script>alert('Cliente actualizado correctamente');window.location='clients.php';</script>";
        exit;
    }
}
?>

<div class="col-md-6 mx-auto">
<div class="card text-white" style="background:#1a1a1a">
<div class="card-header text-center">
    <h3><i class="fa fa-edit"></i> Editar Cliente / Cambiar Plan</h3>
</div>
<div class="card-body">

<?php if(!empty($error)): ?>
<div class="alert alert-danger"><?=htmlspecialchars($error)?></div>
<?php endif; ?>

<?php if ($role !== 'master'): ?>
<div class="alert alert-dark">Créditos disponibles: <b><?=credits_display($myCredits)?></b></div>
<?php endif; ?>

<?php if ($downloadUrl || $downloaderCode): ?>
<div class="alert alert-secondary">
    <?php if ($downloadUrl): ?><div><strong>Link de descarga:</strong> <span class="text-break"><?=htmlspecialchars($downloadUrl)?></span></div><?php endif; ?>
    <?php if ($downloaderCode): ?><div class="mt-1"><strong>Código downloader:</strong> <?=htmlspecialchars($downloaderCode)?></div><?php endif; ?>
</div>
<?php endif; ?>

<form method="post">
    <div class="form-group mb-2">
        <label>Nombre del Cliente</label>
        <input type="text" name="client_name" class="form-control" value="<?=htmlspecialchars($client['client_name'] ?? '')?>" required>
    </div>

    <div class="form-group mb-2">
        <label>WhatsApp</label>
        <input type="text" name="client_whatsapp" class="form-control" value="<?=htmlspecialchars($client['client_whatsapp'] ?? '')?>" required>
    </div>

    <div class="form-group mb-2">
        <label>Estado</label>
        <select name="status" class="form-control">
            <option value="active" <?=($client['status'] ?? 'active')==='active'?'selected':''?>>Activo</option>
            <option value="blocked" <?=($client['status'] ?? '')==='blocked'?'selected':''?>>Bloqueado</option>
        </select>
    </div>

    <div class="form-group mb-3">
        <label>Plan (meses)</label>
        <select name="months" class="form-control">
            <?php for($i=1;$i<=12;$i++): ?>
                <option value="<?=$i?>"><?=$i?> mes<?=$i>1?'es':''?></option>
            <?php endfor; ?>
        </select>
    </div>

    <button type="submit" class="btn btn-info"><i class="fa fa-save"></i> Guardar Cambios</button>
</form>

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

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