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

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

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

if (!in_array($role, ['master','ultra-reseller','super-reseller','reseller'])) {
    die("Acceso denegado");
}

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

$client = ($role === 'master')
    ? $db->select('codes','*','id = :id','',[':id'=>$id])
    : $db->select('codes','*','id = :id AND owner = :o','',[':id'=>$id, ':o'=>$currentUser]);

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

$myCredits = 0;
if ($role !== 'master') {
    $me = $db->select('menualuser','credits','username = :u','',[':u' => $currentUser]);
    $myCredits = $me[0]['credits'] ?? 0;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $client_name = trim($_POST['client_name'] ?? '');
    $client_whatsapp = trim($_POST['client_whatsapp'] ?? '');
    $status = in_array($_POST['status'] ?? 'active', ['active','blocked']) ? $_POST['status'] : 'active';
    $accountType = ($_POST['account_type'] ?? 'real') === 'demo' ? 'demo' : 'real';
    $months = max(1, min(12, (int)($_POST['months'] ?? 1)));
    $demoHours = max(1, min(72, (int)($_POST['demo_hours'] ?? 5)));
    $maxDevices = isset($_POST['max_devices']) ? (int)$_POST['max_devices'] : 1;

    if ($role === 'master') {
        $maxDevices = max(1, min(9999, $maxDevices));
    } else {
        $maxDevices = max(1, min(5, $maxDevices));
    }

    if ($client_name === '' || $client_whatsapp === '') {
        $error = "Nombre y WhatsApp son obligatorios";
    } elseif ($accountType === 'real' && $role !== 'master' && !is_unlimited_credits($myCredits) && $months > (int)$myCredits) {
        $error = "No tienes créditos suficientes para cambiar el plan";
    } else {
        if ($accountType === 'demo') {
            $new_expiration = date("Y-m-d H:i:s", strtotime("+{$demoHours} hours"));
            $isDemo = 1;
        } else {
            $new_expiration = date("Y-m-d", strtotime("+{$months} months"));
            $isDemo = 0;
            $demoHours = 0;
        }

        $db->update(
            'codes',
            [
                'client_name' => $client_name,
                'client_whatsapp' => $client_whatsapp,
                'expires_at' => $new_expiration,
                'status' => $status,
                'is_demo' => $isDemo,
                'demo_hours' => $demoHours,
                'max_devices' => $maxDevices
            ],
            'id = :id',
            [':id'=>$id]
        );

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

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

$currentIsDemo = !empty($client['is_demo']);
$currentMaxDevices = isset($client['max_devices']) ? max(1, (int)$client['max_devices']) : 5;
?>

<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</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><?=display_credits($myCredits)?></b><br>
<small>Los revendedores pueden asignar máximo 5 dispositivos por cliente.</small>
</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'] ?? 'active')=='blocked'?'selected':''?>>Bloqueado</option>
        </select>
    </div>

    <div class="form-group mb-2">
        <label>Tipo de cuenta</label>
        <select name="account_type" id="accountType" class="form-control">
            <option value="real" <?=$currentIsDemo?'':'selected'?>>Cuenta real</option>
            <option value="demo" <?=$currentIsDemo?'selected':''?>>Demo por horas</option>
        </select>
        <small class="text-muted">Puedes pasar una demo a cuenta real o una cuenta real a demo.</small>
    </div>

    <div class="form-group mb-3" id="monthsBox">
        <label>Plan cuenta real (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>

    <div class="form-group mb-3" id="demoBox">
        <label>Duración demo (horas)</label>
        <input type="number" name="demo_hours" class="form-control" value="<?=htmlspecialchars($client['demo_hours'] ?? 5)?>" min="1" max="72">
    </div>

    <div class="form-group mb-3">
        <label>Dispositivos permitidos</label>
        <input type="number" name="max_devices" class="form-control" value="<?=$currentMaxDevices?>" min="1" <?=($role === 'master' ? 'max="9999"' : 'max="5"')?> required>
        <small class="text-muted">
            <?php if($role === 'master'): ?>Como dueño puedes colocar la cantidad que necesites.<?php else: ?>Máximo 5 dispositivos.<?php endif; ?>
        </small>
    </div>

    <button type="submit" class="btn btn-info"><i class="fa fa-save"></i> Guardar Cambios</button>
    <a href="clients.php" class="btn btn-secondary">Cancelar</a>
</form>

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

<script>
function toggleTypeBoxes(){
    const type = document.getElementById('accountType').value;
    document.getElementById('monthsBox').style.display = type === 'real' ? 'block' : 'none';
    document.getElementById('demoBox').style.display = type === 'demo' ? 'block' : 'none';
}
document.getElementById('accountType').addEventListener('change', toggleTypeBoxes);
toggleTypeBoxes();
</script>

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