<?php
// config/admin.php
// Admin authentication and session utilities
require_once __DIR__ . '/db.php';

function admin_login($email, $password) {
    global $pdo;
    $stmt = $pdo->prepare('SELECT * FROM admins WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($admin && password_verify($password, $admin['password'])) {
        // Set session
        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_role'] = $admin['role'];
        $_SESSION['admin_name'] = $admin['name'];
        $_SESSION['admin_email'] = $admin['email'];
        $_SESSION['admin_state_id'] = $admin['state_id'];
        $_SESSION['admin_district_id'] = $admin['district_id'];
        $_SESSION['admin_block_id'] = $admin['block_id'];
        $_SESSION['admin_panchayat_id'] = $admin['panchayat_id'];
        return true;
    }
    return false;
}

function require_admin_login() {
    if (empty($_SESSION['admin_id'])) {
        header('Location: /school-crm/public/admin_login.php');
        exit;
    }
}

function require_admin_role($roles) {
    require_admin_login();
    if (!in_array($_SESSION['admin_role'], (array)$roles)) {
        http_response_code(403);
        echo "Access denied.";
        exit;
    }
}

function admin_logout() {
    session_unset();
    session_destroy();
}

function current_admin() {
    return isset($_SESSION['admin_id']) ? [
        'id' => $_SESSION['admin_id'],
        'role' => $_SESSION['admin_role'],
        'name' => $_SESSION['admin_name'],
        'email' => $_SESSION['admin_email'],
        'state_id' => $_SESSION['admin_state_id'],
        'district_id' => $_SESSION['admin_district_id'],
        'block_id' => $_SESSION['admin_block_id'],
        'panchayat_id' => $_SESSION['admin_panchayat_id'],
    ] : null;
}
