<?php
session_start();
require 'dbconn.php'; // Provides $mysqli connection


// Grab & trim inputs
$email    = trim($_POST['email']    ?? '');
$password = trim($_POST['password'] ?? '');

// Basic validation
if (empty($email) || empty($password)) {
    echo "<script>alert('Email and password are required.'); window.history.back();</script>";
    exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<script>alert('Invalid email format.'); window.history.back();</script>";
    exit;
}

// Query user by email
$stmt = $mysqli->prepare("SELECT id, u_name, pass FROM admin WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows === 1) {
    $admin = $result->fetch_assoc();

    // Convert user input to MD5 and compare
    if (md5($password) !== $admin['pass']) {
        echo "<script>alert('Invalid email or password.'); window.history.back();</script>";
        exit;
    }

    // Successful login
    $_SESSION['admin_logged_in'] = true;
    $_SESSION['admin_name'] = $admin['u_name']; 
    $_SESSION['admin_id'] = $admin['id'];       

    header('Location: dashboard.php');
    exit;
}

// Default fallback
echo "<script>alert('Invalid email or password.'); window.history.back();</script>";
?>
