<?php require_once __DIR__.'/layout/header.php'; ?>

<style>

body{
  font-family:Arial,sans-serif;
  background:#f4f6f8;
  display:flex;
  justify-content:center;
  align-items:center;
  height:100vh;
}

.login-card{
  background:#fff;
  padding:30px;
  width:320px;
  box-shadow:0 1px 4px rgba(0,0,0,0.1);
}

h2{
  margin-top:0;
}

input{
  width:100%;
  padding:8px;
  margin-top:4px;
  margin-bottom:12px;
  box-sizing:border-box;
}

button{
  padding:10px;
  width:100%;
  background:#2563eb;
  border:none;
  color:white;
  cursor:pointer;
}

pre{
  margin-top:12px;
  font-size:12px;
  background:#f9fafb;
  padding:8px;
}

</style>


<div class="login-card">

<h2>Admin Login</h2>

<form id="loginForm">

<label>Email</label><br>
<input type="email" id="email" required><br>

<label>Password</label><br>
<input type="password" id="password" required><br>

<button type="submit">Login</button>

</form>

<pre id="output"></pre>

</div>


<script>

/* ================= CSRF ================= */

let CSRF_TOKEN=null

fetch('/auth/csrf_token.php',{credentials:'include'})
.then(r=>r.json())
.then(d=>CSRF_TOKEN=d.csrf_token)

function csrfFetch(url,options={}){

return fetch(url,{

...options,

credentials:'include',

headers:{
...(options.headers||{}),
'X-CSRF-Token':CSRF_TOKEN
}

})

}


/* ================= LOGIN ================= */

document.getElementById("loginForm")
.addEventListener("submit",async function(e){

e.preventDefault()

const email=document.getElementById("email").value
const password=document.getElementById("password").value

const res=await csrfFetch("/auth/login.php",{

method:"POST",

headers:{ "Content-Type":"application/json" },

body:JSON.stringify({email,password})

})

const data=await res.json()

if(data.status==="success"){

localStorage.setItem("auth_token",data.token)
localStorage.setItem("auth_user",JSON.stringify(data.user))

window.location.href="/admin/dashboard.php"

}

})

</script>


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