<?php
// Start session and include necessary files
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/email.php';
require_once __DIR__ . '/../app/Database.php';
require_once __DIR__ . '/../app/Mail.php';
require_once __DIR__ . '/../app/Auth.php';
require_once __DIR__ . '/../app/Subscription.php';
require_once __DIR__ . '/../app/Transaction.php';
require_once __DIR__ . '/../app/Product.php';
require_once __DIR__ . '/../app/Helper.php';

// Initialize classes
$database = new Database($pdo);
$auth = new Auth($database);
$subscription = new Subscription($database);
$transaction = new Transaction($database);
$product = new Product($database);

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    Helper::redirect(APP_URL . '/auth/login.php');
}

// Check subscription status (admin bypass, subscription pages bypass)
$_currentPage = $_SERVER['PHP_SELF'] ?? '';
$_isSubscriptionPage = strpos($_currentPage, '/subscription/') !== false;

if ($_SESSION['role'] !== 'admin' && !$_isSubscriptionPage) {
    $subsStats = $subscription->getSubscriptionStats($_SESSION['user_id']);
    if (!$subsStats['is_active']) {
        // Send expired notification email (only once per session)
        if (!isset($_SESSION['expired_email_sent']) && isset($subsStats['subscription']['end_date'])) {
            $user = $auth->getCurrentUser();
            $expiredDate = date('d M Y', strtotime($subsStats['subscription']['end_date']));
            $subscription->sendExpiredEmail($user['email'], $user['name'], $expiredDate);
            $_SESSION['expired_email_sent'] = true;
        }

        Helper::redirect(APP_URL . '/subscription/expired.php');
    }
}
