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

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =======================
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','super-reseller','reseller'])) {
    die("Acceso denegado");
}

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

/* =======================
OBTENER CLIENTE
======================= */
$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];

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

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

    if(!$client_name || !$client_whatsapp){
        $error = "Nombre y WhatsApp son obligatorios";
    } elseif($role !== 'master' && $months > $myCredits) {
        $error = "No tienes créditos suficientes para cambiar el plan";
    } else {
        // Calcular nueva fecha de expiración según plan seleccionado
        $current_exp = $client['expires_at'] ?? date('Y-m-d');
        $new_expiration = date("Y-m-d", strtotime("+$months months", strtotime($current_exp)));

        // Actualizar cliente
        $db->update(
            'codes',
            [
                'client_name' => $client_name,
                'client_whatsapp' => $client_whatsapp,
                'expires_at' => $new_expiration,
                'status' => $status
            ],
            'id = :id',
            [':id'=>$id]
        );

        // Descontar créditos si no es master
        if ($role !== 'master') {
            $db->update(
                'menualuser',
                ['credits'=>($myCredits-$months)],
                'username = :u',
                [':u'=>$currentUser]
            );
        }

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

/* =======================
FORMULARIO
======================= */
?>

<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><?=$myCredits?></b>
</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'?'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'; ?>