<?php
/**
 * includes/functions.php
 *
 * Core bootstrap file: starts the session, connects to the database,
 * and provides the auth helper functions used across the dashboards.
 *
 * IMPORTANT: Fill in your real database credentials below before use.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ================================
// DATABASE CONNECTION
// ================================
// config.php lives in the project root, one level above includes/
require_once __DIR__ . '/../config.php';

try {
    $pdo = new PDO(
        "mysql:host="";dbname=" mybelief_spica";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]
    );
} catch (PDOException $e) {
    // TEMPORARY DEBUG MODE: shows the real error so you can fix the credentials.
    // IMPORTANT: remove this and restore the generic message once it's working,
    // so real users never see raw DB error details.
    die("Database connection failed: " . $e->getMessage());
}

// ================================
// AUTH HELPERS
// ================================

/**
 * Returns true if a user is currently logged in.
 */
function is_logged_in(): bool {
    return isset($_SESSION['user']) && !empty($_SESSION['user']['id']);
}

/**
 * Returns the currently logged-in user's session data as an array,
 * or null if nobody is logged in.
 */
function current_user(): ?array {
    return $_SESSION['user'] ?? null;
}

/**
 * Logs a user in: looks them up by email, verifies the password,
 * and stores their info in $_SESSION['user'].
 * Returns true on success, false on failure (wrong email/password).
 */
function attempt_login(PDO $pdo, string $email, string $password): bool {
    $stmt = $pdo->prepare("SELECT id, name, email, password, role, reporting_manager_id FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $row = $stmt->fetch();

    if (!$row) {
        return false;
    }

    // Assumes passwords are stored hashed with password_hash().
    if (!password_verify($password, $row['password'])) {
        return false;
    }

    unset($row['password']); // never keep the hash in session
    $_SESSION['user'] = $row;
    return true;
}

/**
 * Logs the current user out and destroys the session.
 */
function logout_user(): void {
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    session_destroy();
}