<?php
// ================================================================
// GESTOR DE CONTRASEÑAS - PodoCLINIC
// Archivo independiente — NO requiere login al sistema
// Subir a: /public_html/podoclinic/gestor_contrasenas.php
// Acceso: https://soporte-jp.com/podoclinic/gestor_contrasenas.php
// PROTEGIDO por clave maestra hardcodeada
// ================================================================

define('DB_HOST',    'localhost');
define('DB_NAME',    'soportej_podoclinic');
define('DB_USER',    'soportej_podo');
define('DB_PASS',    '#Alivale2002');
define('DB_CHARSET', 'utf8mb4');

// ── CLAVE MAESTRA PARA ACCEDER A ESTE GESTOR ──────────────────────────────────
// Cambia esto por una clave que solo tú conozcas
define('MASTER_KEY', 'PodoBela2024#Admin');

function getDB(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET;
        $pdo = new PDO($dsn, DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    }
    return $pdo;
}

$error   = '';
$success = '';
$users   = [];
$authed  = isset($_SESSION['gcauth']) && $_SESSION['gcauth'] === true;

session_start();
$authed = isset($_SESSION['gcauth']) && $_SESSION['gcauth'] === true;

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['master_key'])) {
    if ($_POST['master_key'] === MASTER_KEY) {
        $_SESSION['gcauth'] = true;
        $authed = true;
    } else {
        $error = 'Clave maestra incorrecta.';
    }
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle password change
if ($authed && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'])) {
    $uid  = (int)$_POST['user_id'];
    $pwd  = $_POST['new_password']  ?? '';
    $pwd2 = $_POST['confirm_password'] ?? '';
    if (strlen($pwd) < 4) {
        $error = 'La contraseña debe tener al menos 4 caracteres.';
    } elseif ($pwd !== $pwd2) {
        $error = 'Las contraseñas no coinciden.';
    } else {
        $hash = password_hash($pwd, PASSWORD_BCRYPT);
        $db = getDB();
        $st = $db->prepare("UPDATE users SET password_hash=? WHERE id=?");
        $st->execute([$hash, $uid]);
        $uname = $db->prepare("SELECT name, username FROM users WHERE id=? LIMIT 1");
        $uname->execute([$uid]);
        $u = $uname->fetch();
        $success = "✅ Contraseña actualizada para <strong>{$u['name']}</strong> ({$u['username']})";
    }
}

// Load users if authed
if ($authed) {
    $db    = getDB();
    $users = $db->query("SELECT id, username, name, role, active FROM users ORDER BY
        CASE role WHEN 'Super Admin' THEN 1 WHEN 'Administrador' THEN 2 WHEN 'Podólogo' THEN 3 ELSE 4 END, name ASC"
    )->fetchAll();
}

$roleColors = [
    'Super Admin'  => ['bg'=>'#1e1b4b','text'=>'#a5b4fc'],
    'Administrador'=> ['bg'=>'#1e3a5f','text'=>'#7dd3fc'],
    'Podólogo'     => ['bg'=>'#064e3b','text'=>'#6ee7b7'],
    'Recepcionista'=> ['bg'=>'#3b1f00','text'=>'#fcd34d'],
];
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gestor de Contraseñas — PodoCLINIC</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root {
    --bg:      #0d0f14;
    --surface: #161920;
    --border:  #252a35;
    --accent:  #4a9d8f;
    --accent2: #3b7d72;
    --text:    #e8edf3;
    --muted:   #6b7585;
    --danger:  #e05050;
    --success: #2ea87e;
    --radius:  12px;
  }
  *{box-sizing:border-box;margin:0;padding:0}
  body{font-family:'DM Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;
    display:flex;align-items:center;justify-content:center;padding:24px;
    background-image:radial-gradient(ellipse at 20% 20%,#0d2a2522 0%,transparent 60%),
                     radial-gradient(ellipse at 80% 80%,#1a1f2e 0%,transparent 60%)}

  /* ── LOGIN ── */
  .login-box{background:var(--surface);border:1px solid var(--border);border-radius:20px;
    padding:48px 40px;width:100%;max-width:400px;text-align:center;
    box-shadow:0 40px 80px #00000060}
  .logo{width:72px;height:72px;border-radius:16px;background:linear-gradient(135deg,#0d2a25,#1a4a40);
    display:flex;align-items:center;justify-content:center;margin:0 auto 20px;font-size:32px;
    border:1px solid #2a5a50;box-shadow:0 0 30px #4a9d8f20}
  .login-title{font-size:22px;font-weight:700;margin-bottom:4px}
  .login-sub{font-size:13px;color:var(--muted);margin-bottom:32px}
  .field{text-align:left;margin-bottom:16px}
  .field label{display:block;font-size:12px;font-weight:600;color:var(--muted);
    text-transform:uppercase;letter-spacing:.06em;margin-bottom:6px}
  .field input{width:100%;background:#0d0f14;border:1.5px solid var(--border);border-radius:8px;
    padding:11px 14px;color:var(--text);font-size:14px;font-family:'DM Mono',monospace;
    outline:none;transition:border-color .2s}
  .field input:focus{border-color:var(--accent)}
  .btn-primary{width:100%;background:var(--accent);color:#fff;border:none;border-radius:8px;
    padding:13px;font-size:14px;font-weight:600;cursor:pointer;transition:background .2s;
    font-family:'DM Sans',sans-serif;letter-spacing:.02em}
  .btn-primary:hover{background:var(--accent2)}
  .alert-error{background:#2a1010;border:1px solid #6b2020;border-radius:8px;
    padding:10px 14px;font-size:13px;color:#f87171;margin-bottom:16px}
  .alert-success{background:#0a2a1e;border:1px solid #1a5a40;border-radius:8px;
    padding:10px 14px;font-size:13px;color:#6ee7b7;margin-bottom:16px}

  /* ── MAIN ── */
  .container{width:100%;max-width:860px}
  .header{display:flex;align-items:center;justify-content:space-between;margin-bottom:28px;
    padding-bottom:20px;border-bottom:1px solid var(--border)}
  .header-left{display:flex;align-items:center;gap:14px}
  .header-logo{width:44px;height:44px;border-radius:10px;
    background:linear-gradient(135deg,#0d2a25,#1a4a40);
    display:flex;align-items:center;justify-content:center;font-size:22px;
    border:1px solid #2a5a50}
  .header-title{font-size:20px;font-weight:700}
  .header-sub{font-size:12px;color:var(--muted)}
  .btn-logout{background:transparent;border:1px solid var(--border);color:var(--muted);
    border-radius:8px;padding:7px 14px;font-size:12px;cursor:pointer;
    font-family:'DM Sans',sans-serif;transition:all .2s}
  .btn-logout:hover{border-color:var(--danger);color:var(--danger)}

  /* ── USER CARDS ── */
  .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:14px}
  .card{background:var(--surface);border:1.5px solid var(--border);border-radius:var(--radius);
    padding:20px;transition:border-color .2s}
  .card:hover{border-color:#3a4555}
  .card-header{display:flex;align-items:center;gap:12px;margin-bottom:16px}
  .avatar{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;
    justify-content:center;font-size:17px;font-weight:700;flex-shrink:0}
  .user-name{font-size:15px;font-weight:600;line-height:1.3}
  .user-meta{font-size:12px;color:var(--muted);font-family:'DM Mono',monospace}
  .role-badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:11px;
    font-weight:600;letter-spacing:.04em;margin-top:3px}
  .inactive-badge{background:#2a1f00;color:#fbbf24;padding:2px 8px;border-radius:20px;
    font-size:10px;font-weight:600;margin-left:6px}

  .pwd-form{border-top:1px solid var(--border);padding-top:14px;margin-top:4px}
  .pwd-form label{font-size:11px;font-weight:600;color:var(--muted);
    text-transform:uppercase;letter-spacing:.06em;display:block;margin-bottom:5px}
  .pwd-row{display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap}
  .pwd-input{flex:1;min-width:140px;background:#0d0f14;border:1.5px solid var(--border);
    border-radius:8px;padding:9px 12px;color:var(--text);font-size:13px;
    font-family:'DM Mono',monospace;outline:none;transition:border-color .2s}
  .pwd-input:focus{border-color:var(--accent)}
  .btn-save{background:var(--accent);color:#fff;border:none;border-radius:8px;
    padding:9px 16px;font-size:13px;font-weight:600;cursor:pointer;
    font-family:'DM Sans',sans-serif;white-space:nowrap;transition:background .2s;flex-shrink:0}
  .btn-save:hover{background:var(--accent2)}
  .pwd-hint{font-size:11px;color:var(--muted);margin-top:6px}

  .section-label{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;
    letter-spacing:.1em;margin:24px 0 10px;padding-left:2px}
  
  @media(max-width:500px){
    .grid{grid-template-columns:1fr}
    .login-box{padding:32px 24px}
  }
</style>
</head>
<body>

<?php if (!$authed): ?>
<!-- ── LOGIN ──────────────────────────────────────────────────────────────── -->
<div class="login-box">
  <div class="logo">🔑</div>
  <div class="login-title">Gestor de Contraseñas</div>
  <div class="login-sub">PodoCLINIC · Acceso administrativo</div>

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

  <form method="POST">
    <div class="field">
      <label>Clave Maestra</label>
      <input type="password" name="master_key" placeholder="••••••••••••" autofocus required>
    </div>
    <button type="submit" class="btn-primary">Ingresar →</button>
  </form>
</div>

<?php else: ?>
<!-- ── MAIN ───────────────────────────────────────────────────────────────── -->
<div class="container">
  <div class="header">
    <div class="header-left">
      <div class="header-logo">🔑</div>
      <div>
        <div class="header-title">Gestor de Contraseñas</div>
        <div class="header-sub">PodoCLINIC · <?= count($users) ?> usuarios registrados</div>
      </div>
    </div>
    <a href="?logout=1"><button class="btn-logout">Cerrar sesión</button></a>
  </div>

  <?php if ($error): ?>
    <div class="alert-error" style="margin-bottom:16px"><?= htmlspecialchars($error) ?></div>
  <?php endif ?>
  <?php if ($success): ?>
    <div class="alert-success" style="margin-bottom:16px"><?= $success ?></div>
  <?php endif ?>

  <?php
  $roleOrder = ['Super Admin','Administrador','Podólogo','Recepcionista'];
  $grouped   = [];
  foreach ($users as $u) $grouped[$u['role']][] = $u;
  ?>

  <?php foreach ($roleOrder as $role): ?>
    <?php if (empty($grouped[$role])) continue ?>
    <div class="section-label"><?= htmlspecialchars($role) ?> (<?= count($grouped[$role]) ?>)</div>
    <div class="grid">
    <?php foreach ($grouped[$role] as $u):
      $rc     = $roleColors[$role] ?? ['bg'=>'#1e2530','text'=>'#94a3b8'];
      $initials = strtoupper(mb_substr($u['name'], 0, 1));
      $active = (bool)$u['active'];
    ?>
    <div class="card">
      <div class="card-header">
        <div class="avatar" style="background:<?= $rc['bg'] ?>;color:<?= $rc['text'] ?>">
          <?= $initials ?>
        </div>
        <div style="flex:1;min-width:0">
          <div class="user-name">
            <?= htmlspecialchars($u['name']) ?>
            <?php if (!$active): ?>
              <span class="inactive-badge">INACTIVO</span>
            <?php endif ?>
          </div>
          <div class="user-meta">@<?= htmlspecialchars($u['username']) ?></div>
          <span class="role-badge" style="background:<?= $rc['bg'] ?>;color:<?= $rc['text'] ?>">
            <?= htmlspecialchars($role) ?>
          </span>
        </div>
      </div>

      <div class="pwd-form">
        <form method="POST">
          <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
          <label>Nueva contraseña</label>
          <div class="pwd-row">
            <input type="password" name="new_password" class="pwd-input"
              placeholder="Nueva contraseña" minlength="4" required>
            <input type="password" name="confirm_password" class="pwd-input"
              placeholder="Confirmar" minlength="4" required>
            <button type="submit" class="btn-save">Guardar</button>
          </div>
          <div class="pwd-hint">Mínimo 4 caracteres · Se hashea automáticamente con bcrypt</div>
        </form>
      </div>
    </div>
    <?php endforeach ?>
    </div>
  <?php endforeach ?>

  <div style="margin-top:32px;padding-top:20px;border-top:1px solid var(--border);
    font-size:11px;color:var(--muted);text-align:center">
    ⚠ Este archivo es de uso exclusivo del administrador del sistema.
    Elimínalo del servidor cuando no lo necesites.
  </div>
</div>
<?php endif ?>

</body>
</html>
