<?php
// ============================================================
//  login.php — Página de autenticação do sistema MKT Telecom
// ============================================================
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';

if (!empty($_SESSION['usuario_id'])) {
    header('Location: dashboard.php');
    exit;
}

$erro  = '';
$login = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = trim($_POST['login'] ?? '');
    $senha = $_POST['senha'] ?? '';
    if (!$login || !$senha) {
        $erro = 'Preencha o login e a senha.';
    } else {
        if (tentarLogin($login, $senha)) {
            session_regenerate_id(true);
            header('Location: dashboard.php');
            exit;
        } else {
            $erro = 'Login ou senha incorretos.';
            usleep(400_000);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Entrar — <?= APP_NAME ?></title>
  <link rel="preconnect" href="https://fonts.googleapis.com"/>
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
  <link href="https://fonts.googleapis.com/css2?family=Exo+2:ital,wght@0,300;0,400;0,600;0,700;0,800;0,900;1,300&family=Share+Tech+Mono&display=swap" rel="stylesheet"/>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
:root{
  --bg:#060c18;--surface:#0b1425;--card:#0f1d35;
  --border:#162847;--border2:#1e3d6e;
  --cyan:#00d4ff;--cyan-dim:#0891b2;--cyan-glow:rgba(0,212,255,.18);
  --green:#10b981;--red:#ef4444;
  --text:#d8eaf8;--muted:#4d7199;--muted2:#2a4a6e;
  --mono:'Share Tech Mono',monospace;--ui:'Exo 2',sans-serif;
}
html,body{height:100%;font-family:var(--ui);background:var(--bg);color:var(--text);overflow:hidden;}
canvas#bg{position:fixed;inset:0;z-index:0;opacity:.5;}
.grid-overlay{
  position:fixed;inset:0;z-index:1;pointer-events:none;
  background-image:linear-gradient(rgba(0,212,255,.04) 1px,transparent 1px),
    linear-gradient(90deg,rgba(0,212,255,.04) 1px,transparent 1px);
  background-size:48px 48px;
}
.scanlines{
  position:fixed;inset:0;z-index:2;pointer-events:none;
  background:repeating-linear-gradient(to bottom,transparent,transparent 2px,rgba(0,0,0,.07) 2px,rgba(0,0,0,.07) 4px);
}
.page{position:relative;z-index:10;min-height:100vh;display:grid;grid-template-columns:1fr 460px;}

/* ── PAINEL ESQUERDO ── */
.panel-left{
  display:flex;flex-direction:column;justify-content:center;
  padding:60px 64px;position:relative;overflow:hidden;
  animation:fadeLeft .8s ease both;
}
.panel-left::after{
  content:'';position:absolute;right:0;top:0;bottom:0;width:1px;
  background:linear-gradient(to bottom,transparent,var(--border2),transparent);
}
.brand-tag{font-family:var(--mono);font-size:10px;color:var(--cyan);letter-spacing:4px;margin-bottom:18px;opacity:0;animation:fadeUp .6s .3s ease both;}
.brand-name{font-size:clamp(54px,6vw,80px);font-weight:900;line-height:.92;letter-spacing:-3px;color:var(--text);opacity:0;animation:fadeUp .7s .45s ease both;}
.brand-name span{color:var(--cyan);text-shadow:0 0 48px rgba(0,212,255,.35);}
.brand-tagline{margin-top:20px;font-size:14px;font-weight:300;font-style:italic;color:var(--muted);max-width:340px;line-height:1.7;opacity:0;animation:fadeUp .7s .6s ease both;}
.brand-stats{display:flex;gap:36px;margin-top:52px;opacity:0;animation:fadeUp .7s .75s ease both;}
.bs-val{font-size:28px;font-weight:800;color:var(--text);font-family:var(--mono);}
.bs-val .unit{font-size:14px;color:var(--cyan);}
.bs-label{font-size:10px;font-family:var(--mono);color:var(--muted);letter-spacing:1.5px;margin-top:3px;}
.hex-svg{position:absolute;right:56px;bottom:70px;opacity:.06;pointer-events:none;}
.status-bar{
  position:absolute;bottom:0;left:0;right:0;border-top:1px solid var(--border);
  padding:12px 64px;display:flex;gap:24px;align-items:center;
  font-family:var(--mono);font-size:10px;color:var(--muted2);
  opacity:0;animation:fadeUp .6s 1s ease both;
}
.status-dot{width:6px;height:6px;border-radius:50%;background:var(--green);box-shadow:0 0 8px var(--green);display:inline-block;animation:blink 2s ease-in-out infinite;}
@keyframes blink{0%,100%{opacity:1}50%{opacity:.25}}
.status-item{display:flex;align-items:center;gap:7px;}

/* ── PAINEL DIREITO ── */
.panel-right{
  background:var(--surface);display:flex;flex-direction:column;
  justify-content:center;padding:56px 50px;position:relative;
  animation:fadeRight .8s ease both;
}
.panel-right::before{
  content:'';position:absolute;top:0;left:25%;right:25%;height:1px;
  background:linear-gradient(to right,transparent,var(--cyan-dim),transparent);
}
.form-header{margin-bottom:36px;}
.form-eyebrow{font-family:var(--mono);font-size:10px;color:var(--cyan);letter-spacing:3px;margin-bottom:10px;}
.form-title{font-size:26px;font-weight:800;letter-spacing:-.5px;}
.form-subtitle{font-size:13px;color:var(--muted);margin-top:5px;font-weight:300;}

/* Alerta erro */
.alert-error{
  background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);
  border-radius:8px;padding:12px 16px;font-size:13px;color:var(--red);
  margin-bottom:24px;display:flex;align-items:flex-start;gap:10px;
  animation:shake .4s ease;
}
.alert-icon{font-size:16px;flex-shrink:0;}
@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-5px)}40%,80%{transform:translateX(5px)}}

/* Campos */
.field{margin-bottom:20px;}
.field-label{display:block;font-family:var(--mono);font-size:10px;color:var(--muted);letter-spacing:2px;margin-bottom:8px;}
.input-wrap{position:relative;}
.field-input{
  width:100%;background:var(--card);border:1px solid var(--border);border-radius:8px;
  padding:13px 14px 13px 44px;font-family:var(--ui);font-size:14px;color:var(--text);
  outline:none;transition:border-color .2s,box-shadow .2s;
}
.field-input::placeholder{color:var(--muted2);}
.field-input:focus{border-color:var(--cyan-dim);box-shadow:0 0 0 3px var(--cyan-glow);}
.input-icon{position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:15px;color:var(--muted2);pointer-events:none;transition:color .2s;}
.input-wrap:focus-within .input-icon{color:var(--cyan-dim);}
.toggle-pass{
  position:absolute;right:12px;top:50%;transform:translateY(-50%);
  background:none;border:none;color:var(--muted2);cursor:pointer;
  font-size:15px;padding:4px;border-radius:4px;transition:color .2s;line-height:1;
}
.toggle-pass:hover{color:var(--text);}

/* Opções */
.row-opts{display:flex;justify-content:space-between;align-items:center;margin-bottom:26px;}
.check-label{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);cursor:pointer;user-select:none;}
.check-label input[type="checkbox"]{
  appearance:none;width:16px;height:16px;border:1px solid var(--border2);
  border-radius:4px;background:var(--card);cursor:pointer;position:relative;
  flex-shrink:0;transition:all .15s;
}
.check-label input[type="checkbox"]:checked{background:var(--cyan-dim);border-color:var(--cyan-dim);}
.check-label input[type="checkbox"]:checked::after{
  content:'✓';position:absolute;top:50%;left:50%;
  transform:translate(-50%,-50%);font-size:10px;color:#fff;font-weight:700;
}

/* Botão entrar */
.btn-login{
  width:100%;background:var(--cyan);color:#030c18;border:none;border-radius:8px;
  padding:14px;font-family:var(--ui);font-size:14px;font-weight:800;letter-spacing:.4px;
  cursor:pointer;transition:background .15s,box-shadow .2s,transform .1s;
  position:relative;overflow:hidden;
}
.btn-login::before{
  content:'';position:absolute;inset:0;
  background:linear-gradient(135deg,rgba(255,255,255,.15),transparent);
  opacity:0;transition:opacity .2s;
}
.btn-login:hover{background:#1de0ff;box-shadow:0 0 28px rgba(0,212,255,.5);}
.btn-login:hover::before{opacity:1;}
.btn-login:active{transform:scale(.98);}
.btn-login.loading{opacity:.75;pointer-events:none;}

/* Divisor */
.divider{display:flex;align-items:center;gap:12px;margin:26px 0;}
.div-line{flex:1;height:1px;background:var(--border);}
.div-text{font-family:var(--mono);font-size:9px;color:var(--muted2);letter-spacing:2px;white-space:nowrap;}

/* Cards de perfil */
.perfis-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;}
.perfil-card{
  background:var(--card);border:1px solid var(--border);border-radius:8px;
  padding:12px 8px 10px;text-align:center;cursor:pointer;
  transition:border-color .15s,background .15s,transform .12s;user-select:none;
}
.perfil-card:hover{border-color:var(--border2);background:rgba(0,212,255,.05);transform:translateY(-2px);}
.perfil-card:active{transform:translateY(0);}
.pf-icon{font-size:20px;margin-bottom:6px;display:block;}
.pf-nome{font-family:var(--mono);font-size:9px;color:var(--cyan);letter-spacing:1.5px;display:block;margin-bottom:3px;}
.pf-login{font-size:12px;font-weight:700;color:var(--text);}

/* Rodapé */
.form-footer{
  margin-top:30px;border-top:1px solid var(--border);padding-top:18px;
  text-align:center;font-family:var(--mono);font-size:10px;color:var(--muted2);letter-spacing:.8px;
}
.form-footer span{color:var(--muted);}

/* Animações */
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
@keyframes fadeLeft{from{opacity:0;transform:translateX(-18px)}to{opacity:1;transform:translateX(0)}}
@keyframes fadeRight{from{opacity:0;transform:translateX(18px)}to{opacity:1;transform:translateX(0)}}

/* Responsivo */
@media(max-width:900px){.page{grid-template-columns:1fr;}.panel-left{display:none;}.panel-right{padding:48px 30px;background:var(--bg);}}
@media(max-width:460px){.panel-right{padding:36px 20px;}.perfis-grid{grid-template-columns:1fr;}}
::-webkit-scrollbar{width:4px;}::-webkit-scrollbar-track{background:var(--bg);}::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px;}
</style>
</head>
<body>

<canvas id="bg"></canvas>
<div class="grid-overlay"></div>
<div class="scanlines"></div>

<div class="page">

  <!-- PAINEL ESQUERDO -->
  <div class="panel-left">
    <div class="brand-tag">◈ <?= APP_NAME ?> &middot; v<?= APP_VERSION ?></div>
    <div class="brand-name">MKT<br><span>Telecom</span></div>
    <p class="brand-tagline">
      Gestão operacional para provedores de internet &mdash;
      clientes, ordens de serviço, estoque e infraestrutura em um só painel.
    </p>
    <div class="brand-stats">
      <div><div class="bs-val">6<span class="unit"> cid.</span></div><div class="bs-label">COBERTURA</div></div>
      <div><div class="bs-val">5<span class="unit"> OLTs</span></div><div class="bs-label">INFRA</div></div>
      <div><div class="bs-val">3<span class="unit"> perfis</span></div><div class="bs-label">ACESSO</div></div>
    </div>

    <svg class="hex-svg" width="300" height="340" viewBox="0 0 300 340" fill="none">
      <polygon points="150,8 286,80 286,260 150,332 14,260 14,80" stroke="#00d4ff" stroke-width="1" fill="none"/>
      <polygon points="150,38 258,100 258,240 150,302 42,240 42,100" stroke="#00d4ff" stroke-width=".6" fill="none"/>
      <polygon points="150,78 230,124 230,216 150,262 70,216 70,124" stroke="#00d4ff" stroke-width=".4" fill="none"/>
      <circle cx="150" cy="170" r="3" fill="#00d4ff"/>
      <circle cx="150" cy="170" r="18" stroke="#00d4ff" stroke-width=".5" fill="none"/>
      <circle cx="150" cy="170" r="46" stroke="#00d4ff" stroke-width=".3" fill="none"/>
      <?php foreach([[150,8],[286,80],[286,260],[150,332],[14,260],[14,80]] as [$x,$y]): ?>
        <circle cx="<?=$x?>" cy="<?=$y?>" r="3" fill="#00d4ff" opacity=".6"/>
        <line x1="<?=$x?>" y1="<?=$y?>" x2="150" y2="170" stroke="#00d4ff" stroke-width=".3" opacity=".4"/>
      <?php endforeach; ?>
    </svg>

    <div class="status-bar">
      <div class="status-item"><span class="status-dot"></span> SISTEMA ONLINE</div>
      <div class="status-item">◈ <?= strtoupper(DB_NAME) ?></div>
      <div class="status-item" id="relogio">◉ <?= date('d/m/Y H:i:s') ?></div>
      <div class="status-item">▣ PHP <?= PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION ?></div>
    </div>
  </div>

  <!-- PAINEL DIREITO -->
  <div class="panel-right">

    <div class="form-header">
      <div class="form-eyebrow">◎ AUTENTICAÇÃO</div>
      <div class="form-title">Bem-vindo de volta</div>
      <div class="form-subtitle">Informe suas credenciais para acessar o sistema</div>
    </div>

    <?php if ($erro): ?>
    <div class="alert-error">
      <span class="alert-icon">⊘</span>
      <span><?= htmlspecialchars($erro, ENT_QUOTES, 'UTF-8') ?></span>
    </div>
    <?php endif; ?>

    <form method="post" id="form-login" autocomplete="off" novalidate>

      <div class="field">
        <label class="field-label" for="login">LOGIN / USUÁRIO</label>
        <div class="input-wrap">
          <input class="field-input" type="text" id="login" name="login"
            value="<?= htmlspecialchars($login, ENT_QUOTES, 'UTF-8') ?>"
            placeholder="Seu login de acesso"
            autocomplete="username" spellcheck="false" required autofocus/>
          <span class="input-icon">◎</span>
        </div>
      </div>

      <div class="field">
        <label class="field-label" for="senha">SENHA</label>
        <div class="input-wrap">
          <input class="field-input" type="password" id="senha" name="senha"
            placeholder="••••••••••" autocomplete="current-password" required/>
          <span class="input-icon">◈</span>
          <button type="button" class="toggle-pass" id="toggle-pass"
                  onclick="toggleSenha()" title="Mostrar/ocultar senha">👁</button>
        </div>
      </div>

      <div class="row-opts">
        <label class="check-label">
          <input type="checkbox" name="lembrar"/>
          Manter conectado
        </label>
      </div>

      <button type="submit" class="btn-login" id="btn-login">
        Entrar no Sistema &rarr;
      </button>

    </form>

    <div class="divider">
      <div class="div-line"></div>
      <div class="div-text">ACESSO RÁPIDO (DEV)</div>
      <div class="div-line"></div>
    </div>

    <div class="perfis-grid">
      <div class="perfil-card" onclick="preencherLogin('admin','admin123')">
        <span class="pf-icon">⬡</span>
        <span class="pf-nome">ADMIN</span>
        <span class="pf-login">admin</span>
      </div>
      <div class="perfil-card" onclick="preencherLogin('gustavo','password')">
        <span class="pf-icon">◈</span>
        <span class="pf-nome">TÉCNICO</span>
        <span class="pf-login">gustavo</span>
      </div>
      <div class="perfil-card" onclick="preencherLogin('operador','password')">
        <span class="pf-icon">◎</span>
        <span class="pf-nome">OPERADOR</span>
        <span class="pf-login">operador</span>
      </div>
    </div>

    <div class="form-footer">
      <?= APP_NAME ?> &copy; <?= date('Y') ?> &mdash;
      <span>v<?= APP_VERSION ?></span> &middot;
      <span><?= strtoupper(DB_NAME) ?></span>
    </div>

  </div>
</div>

<script>
'use strict';

function toggleSenha() {
  const i = document.getElementById('senha');
  const b = document.getElementById('toggle-pass');
  if (i.type === 'password') { i.type='text'; b.textContent='🙈'; }
  else { i.type='password'; b.textContent='👁'; }
}

function preencherLogin(login, senha) {
  document.getElementById('login').value = login;
  document.getElementById('senha').value = senha;
  const b = document.getElementById('btn-login');
  b.style.boxShadow = '0 0 36px rgba(0,212,255,.65)';
  setTimeout(() => b.style.boxShadow='', 700);
}

document.getElementById('login').addEventListener('keydown', e => {
  if (e.key==='Enter') { e.preventDefault(); document.getElementById('senha').focus(); }
});

document.getElementById('form-login').addEventListener('submit', function(e) {
  const l = document.getElementById('login').value.trim();
  const s = document.getElementById('senha').value.trim();
  if (!l||!s) { e.preventDefault(); return; }
  const b = document.getElementById('btn-login');
  b.classList.add('loading'); b.textContent='◈ Autenticando...';
});

// Relógio em tempo real
(function(){
  const el=document.getElementById('relogio');
  if(!el) return;
  function p(n){return String(n).padStart(2,'0');}
  setInterval(()=>{
    const d=new Date();
    el.textContent=`◉ ${p(d.getDate())}/${p(d.getMonth()+1)}/${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
  },1000);
})();

// Canvas de partículas
(function(){
  const cv=document.getElementById('bg');
  if(!cv) return;
  const ctx=cv.getContext('2d');
  let W,H;
  function resize(){W=cv.width=window.innerWidth;H=cv.height=window.innerHeight;}
  window.addEventListener('resize',resize); resize();

  class P{
    constructor(){this.r();}
    r(){this.x=Math.random()*W;this.y=Math.random()*H;this.rad=Math.random()*2+.8;
      this.vx=(Math.random()-.5)*.35;this.vy=(Math.random()-.5)*.35;
      this.a=Math.random()*.5+.2;this.t=Math.random()*Math.PI*2;}
    u(){this.x+=this.vx;this.y+=this.vy;this.t+=.022;
      if(this.x<-8||this.x>W+8||this.y<-8||this.y>H+8)this.r();}
    d(){const a=this.a*(.6+.4*Math.sin(this.t));
      ctx.beginPath();ctx.arc(this.x,this.y,this.rad,0,Math.PI*2);
      ctx.fillStyle=`rgba(0,212,255,${a})`;ctx.fill();}
  }

  class FL{
    constructor(){this.r();}
    r(){this.x1=Math.random()*W;this.y1=Math.random()*H;
      const a=Math.random()*Math.PI*2,l=Math.random()*200+80;
      this.x2=this.x1+Math.cos(a)*l;this.y2=this.y1+Math.sin(a)*l;
      this.lf=0;this.mx=Math.random()*110+90;this.sp=Math.random()*.3+.25;this.dt=0;}
    u(){this.lf+=this.sp;this.dt+=.018;if(this.lf>this.mx)this.r();}
    d(){const p=this.lf/this.mx;
      const a=p<.2?p/.2:p>.8?(1-p)/.2:1;
      const g=ctx.createLinearGradient(this.x1,this.y1,this.x2,this.y2);
      g.addColorStop(0,'rgba(0,212,255,0)');
      g.addColorStop(.5,`rgba(0,212,255,${a*.14})`);
      g.addColorStop(1,'rgba(0,212,255,0)');
      ctx.beginPath();ctx.moveTo(this.x1,this.y1);ctx.lineTo(this.x2,this.y2);
      ctx.strokeStyle=g;ctx.lineWidth=.7;ctx.stroke();
      const f=(.5+.5*Math.sin(this.dt))%1;
      const px=this.x1+(this.x2-this.x1)*f,py=this.y1+(this.y2-this.y1)*f;
      ctx.beginPath();ctx.arc(px,py,1.5,0,Math.PI*2);
      ctx.fillStyle=`rgba(0,212,255,${a*.65})`;ctx.fill();}
  }

  const pts=Array.from({length:60},()=>new P());
  const fls=Array.from({length:20},()=>new FL());

  function conn(){
    for(let i=0;i<pts.length;i++)
      for(let j=i+1;j<pts.length;j++){
        const dx=pts[i].x-pts[j].x,dy=pts[i].y-pts[j].y;
        const d=Math.hypot(dx,dy);
        if(d<110){ctx.beginPath();ctx.moveTo(pts[i].x,pts[i].y);ctx.lineTo(pts[j].x,pts[j].y);
          ctx.strokeStyle=`rgba(0,212,255,${.07*(1-d/110)})`;ctx.lineWidth=.5;ctx.stroke();}
      }
  }

  (function loop(){
    ctx.clearRect(0,0,W,H);
    const r=ctx.createRadialGradient(W*.3,H*.4,0,W*.3,H*.4,W*.75);
    r.addColorStop(0,'rgba(0,90,180,.07)');r.addColorStop(.5,'rgba(0,212,255,.025)');r.addColorStop(1,'rgba(0,0,0,0)');
    ctx.fillStyle=r;ctx.fillRect(0,0,W,H);
    fls.forEach(f=>{f.u();f.d();});
    conn();
    pts.forEach(p=>{p.u();p.d();});
    requestAnimationFrame(loop);
  })();
})();
</script>
</body>
</html>
