<?php
// customer/includes/auth_check.php

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

// CRITICAL FIX: Go up TWO directories to find the config file.
// From: /customer/includes/ -> ../ is /customer/ -> ../ is /banking_system/
require_once __DIR__ . '/../../config/database.php';

// Check if the user is authenticated
if (!isset($_SESSION['user_id']) || !isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    $_SESSION['error'] = "Please log in to access this page";
    // Redirect to the root login page using the absolute BASE_URL
    header('Location: ' . BASE_URL . 'login.php');
    exit;
}

// Fetch user data for the page
if (!isset($user)) {
    $database = new Database();
    $db = $database->getConnection();

    $stmt = $db->prepare("SELECT u.*, COALESCE(ab.balance, 0.00) as balance, COALESCE(ab.currency, 'USD') as currency FROM users u LEFT JOIN account_balances ab ON u.id = ab.user_id WHERE u.id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        session_destroy();
        header('Location: ' . BASE_URL . 'login.php?error=user_not_found');
        exit;
    }
}
?>
