<?php
session_start();
require_once '../db/config.php';

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

if (empty($email) || empty($password)) {
    $_SESSION['login_error'] = 'Email and password are required.';
    header('Location: login.php');
    exit;
}

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password']) && $user['is_admin']) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user_id'] = $user['id'];
        $_SESSION['admin_email'] = $user['email'];
        header('Location: index.php');
        exit;
    } else {
        $_SESSION['login_error'] = 'Invalid credentials or not an admin.';
        header('Location: login.php');
        exit;
    }
} catch (PDOException $e) {
    $_SESSION['login_error'] = 'Database error: ' . $e->getMessage();
    header('Location: login.php');
    exit;
}
?>