<?php
session_start();
require_once 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Show login form instead of error
    header("Location: /rs_lab/index.php");
    exit;
}

$email    = trim($_POST['email'] ?? '');
$password = trim($_POST['password'] ?? '');

if ($email === '' || $password === '') {
    die("Missing credentials");
}

/* ===============================
   FETCH INSTITUTION
=============================== */
$stmt = $pdo->prepare("SELECT * FROM institutions WHERE email = ? LIMIT 1");
$stmt->execute([$email]);
$inst = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$inst) {
    die("Account not found");
}

/* ===============================
   PASSWORD CHECK (demo)
=============================== */
if (!empty($inst['password']) && $inst['password'] !== $password) {
    die("Invalid password");
}

/* ===============================
   SESSION SET
=============================== */
$_SESSION['user_role']         = 'institution';
$_SESSION['institution_id']   = $inst['id'];
$_SESSION['institution_name'] = $inst['institution_name'];
$_SESSION['institution_type'] = $inst['institution_type']; // school / college
$_SESSION['first_login']      = $inst['first_login'] ?? 0;

/* ===============================
   FORCE PASSWORD CHANGE
=============================== */
if ($_SESSION['first_login'] == 1) {
    header("Location: change_password.php");
    exit;
}

/* ===============================
   🔑 CENTRAL ROUTER
=============================== */
header("Location: router.php");
exit;