<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include 'db_connect.php';

// Set default constants to avoid errors
define('AGENCY_NAME', 'Travel SaaS');
define('AGENCY_LOGO', 'assets/default_logo.png');
define('AGENCY_STATUS', 'Unknown');
define('EXPIRY_DATE', '0000-00-00');

if (isset($_SESSION['agency_id'])) {
    $aid = $_SESSION['agency_id'];
    $stmt = $conn->prepare("SELECT * FROM agencies WHERE id = ?");
    $stmt->bind_param("i", $aid);
    $stmt->execute();
    $res = $stmt->get_result();
    
    if ($res->num_rows > 0) {
        $agency = $res->fetch_assoc();
        
        // --- AUTOMATIC MONTHLY RESET LOGIC ---
        $currentMonth = date('Y-m'); // e.g., 2026-01
        if ($agency['last_reset_month'] !== $currentMonth) {
            $aid = $agency['id'];
            $conn->query("UPDATE agencies SET tickets_used = 0, umrah_used = 0, posters_generated = 0, last_reset_month = '$currentMonth' WHERE id = $aid");
            // Refresh data after reset
            $agency['tickets_used'] = 0;
            $agency['umrah_used'] = 0;
            $agency['posters_generated'] = 0;
        }

        // Define your constants
        define('AGENCY_NAME_LIVE', $agency['agency_name']);
        define('AGENCY_LOGO_LIVE', $agency['logo_path']);
        define('AGENCY_PHONE_LIVE', $agency['phone']);
        define('AGENCY_ADDRESS_LIVE', $agency['address']);
        define('AGENCY_STATUS_LIVE', $agency['status']);
        define('EXPIRY_DATE_LIVE', $agency['expiry_date']);
        
        // Usage Data for current session
        $GLOBALS['agency_usage'] = $agency; 

        // Security Kill-Switch
        if ($agency['status'] == 'Suspended' && $_SESSION['user_role'] != 'SuperAdmin') {
            session_destroy();
            header("Location: login.php?error=Your account is suspended.");
            exit();
        }
    }
    }
// ...

?>