<?php
$pageTitle = 'Log Masuk';
require_once __DIR__.'/../../config/functions.php';
if(isLoggedIn()) redirect(BASE_URL);

$error = '';
if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!verifyCsrfToken($_POST['csrf_token']??''))die('CSRF Error');
  $username = sanitize($_POST['username']??'');
  $password = $_POST['password']??'';
  if($username && $password){
    $stmt=$pdo->prepare("SELECT u.*,p.nama as nama_pegawai FROM users u LEFT JOIN pegawai p ON u.pegawai_id=p.id WHERE (u.username=? OR u.email=?) AND u.status=1");
    $stmt->execute([$username,$username]);
    $user=$stmt->fetch();
    if($user && password_verify($password,$user['password'])){
      $_SESSION['user_id']=$user['id'];
      $_SESSION['user_nama']=$user['nama_pegawai']??$user['username'];
      $_SESSION['user_role']=$user['role'];
      $_SESSION['unit_id']=$user['unit_id'];
      $_SESSION['pegawai_id']=$user['pegawai_id'];
      $_SESSION['just_logged_in']=true;
      $pdo->prepare("UPDATE users SET last_login=NOW() WHERE id=?")->execute([$user['id']]);
      logActivity('Login','auth',$user['id'],'Login berjaya');
      if(!empty($_POST['remember'])){
        $token=bin2hex(random_bytes(32));
        setcookie('remember_token',$token,time()+2592000,'/',false,true);
        $pdo->prepare("UPDATE users SET remember_token=? WHERE id=?")->execute([$token,$user['id']]);
      }
      redirect(BASE_URL);
    }else{$error='Nama pengguna atau kata laluan tidak sah.';}
  }else{$error='Sila isi semua medan.';}
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Log Masuk | S.P.M Dashboard</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="<?=BASE_URL?>assets/css/style.css">
<style>
body{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:1rem}
.login-card{width:100%;max-width:420px;background:rgba(26,26,46,0.9);border:1px solid rgba(204,0,1,0.2);border-radius:28px;padding:2.5rem;backdrop-filter:blur(20px);box-shadow:0 40px 100px rgba(0,0,0,0.5)}
.login-logo{text-align:center;margin-bottom:2rem}
.login-logo .logo-text{font-size:3rem;font-weight:900;color:#fff;letter-spacing:2px}
.login-logo .logo-text span{color:#cc0001}
.login-logo .logo-sub{font-size:.7rem;color:#555;letter-spacing:3px;text-transform:uppercase;margin-top:.25rem}
.divider{border-color:rgba(255,255,255,0.06)!important}
</style>
</head>
<body>
<div class="login-card">
  <div class="login-logo">
    <div style="display:flex;justify-content:center;margin-bottom:.5rem"><?=getSektorLogo('large')?></div>
    <div class="logo-sub"><?=htmlspecialchars(getSektorData()['nama_sektor']??'SEKTOR PEMBANGUNAN MURID')?></div>
    <div style="width:60px;height:2px;background:linear-gradient(90deg,transparent,#cc0001,transparent);margin:1rem auto 0"></div>
  </div>
  <?php if($error): ?>
  <div class="alert" style="background:rgba(204,0,1,0.1);border:1px solid rgba(204,0,1,0.3);color:#ff8888;border-radius:12px;font-size:.9rem;padding:.75rem 1rem">
    <i class="fas fa-exclamation-circle me-2"></i><?=htmlspecialchars($error)?>
  </div>
  <?php endif; ?>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?=generateCsrfToken()?>">
    <div class="mb-3">
      <label class="form-label">Nama Pengguna / Emel</label>
      <div style="position:relative">
        <span style="position:absolute;left:1rem;top:50%;transform:translateY(-50%);color:#555"><i class="fas fa-user"></i></span>
        <input type="text" name="username" class="form-control" style="padding-left:2.5rem" placeholder="username / emel" required value="<?=htmlspecialchars($_POST['username']??'')?>">
      </div>
    </div>
    <div class="mb-3">
      <label class="form-label">Kata Laluan</label>
      <div style="position:relative">
        <span style="position:absolute;left:1rem;top:50%;transform:translateY(-50%);color:#555"><i class="fas fa-lock"></i></span>
        <input type="password" name="password" id="pwdInput" class="form-control" style="padding-left:2.5rem;padding-right:2.5rem" placeholder="••••••••" required>
        <span style="position:absolute;right:1rem;top:50%;transform:translateY(-50%);color:#555;cursor:pointer" onclick="togglePwd()"><i class="fas fa-eye" id="eyeIcon"></i></span>
      </div>
    </div>
    <div class="d-flex justify-content-between align-items-center mb-4">
      <label style="display:flex;align-items:center;gap:.5rem;cursor:pointer;font-size:.85rem;color:#888">
        <input type="checkbox" name="remember" style="accent-color:#cc0001"> Ingat Saya
      </label>
      <a href="forgot.php" style="font-size:.85rem;color:rgba(204,0,1,0.8);text-decoration:none">Lupa Kata Laluan?</a>
    </div>
    <button type="submit" class="btn btn-primary w-100" style="padding:.85rem;font-size:1rem;font-weight:700;border-radius:14px;letter-spacing:.5px">
      <i class="fas fa-sign-in-alt me-2"></i>Log Masuk
    </button>
  </form>
  <hr class="divider my-4">
  <div style="text-align:center">
    <a href="../../" class="btn btn-outline-light btn-sm" style="border-radius:12px;padding:.5rem 1.25rem;font-size:.85rem;color:#aaa;border-color:rgba(255,255,255,0.1)">
      <i class="fas fa-home me-2"></i>Kembali ke Paparan Awam
    </a>
  </div>
</div>
<script>
function togglePwd(){
  const p=document.getElementById('pwdInput');
  const e=document.getElementById('eyeIcon');
  p.type=p.type==='password'?'text':'password';
  e.className=p.type==='password'?'fas fa-eye':'fas fa-eye-slash';
}
setTimeout(()=>{const ls=document.getElementById('loadingScreen');if(ls)ls.remove();},100);
</script>
</body></html>
