<?php
// Include buffer controller (handles output buffering)
require_once 'includes/buffer_controller.php';

// Include header (which includes all dependencies)
include 'includes/header.php';

// $page_title is now set after language files are loaded by header.php
// Ensure $lang_frontend, $lang_alerts, and $lang_navigation are available from header.php's centralized loader
$page_title = $lang_frontend['PAGE_TITLE_ACCOUNT'] ?? 'My Account';

if (!isLoggedIn()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_PERMISSION_DENIED'] ?? 'You do not have permission to access this page', 'danger');
    redirectTo('index');
}

// Compute statistics using the same method as tickets.php (skip guest check)
$open_tickets = 0;
$closed_tickets = 0;
$total_projects = 0;

if (!isset($pdo)) {
    echo "<!-- ERROR: PDO connection not available -->";
} else {
    try {
        // Use the exact same method as tickets.php for logged in users
        if (isLoggedIn() && !isAdminOrStaff()) {
            // Get the user's email from database (same as tickets.php)
            $user_email = '';
            $stmt_user = $pdo->prepare("SELECT email FROM users WHERE id = ?");
            $stmt_user->execute([$_SESSION['user_id']]);
            $user = $stmt_user->fetch();
            if ($user) {
                $user_email = $user['email'];
            }

            // Use exact same query structure as tickets.php
            $stmt = $pdo->prepare("SELECT * FROM tickets WHERE user_id = ? OR email = ?");
            $stmt->execute([$_SESSION['user_id'], $user_email]);
            $tickets = $stmt->fetchAll();

            // Count exactly like tickets.php does - separate them after fetching
            $open_tickets = 0;
            $closed_tickets = 0;

            foreach ($tickets as $ticket) {
                if ($ticket['status'] === 'open') {
                    $open_tickets++;
                } else {
                    // Any non-open ticket should be considered closed (same as tickets.php)
                    $closed_tickets++;
                }
            }

        } else if (isLoggedIn() && isAdminOrStaff()) {
            // Admin/Staff see all tickets
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM tickets WHERE status = 'open'");
            $stmt->execute();
            $result = $stmt->fetch();
            $open_tickets = $result['count'] ?? 0;

            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM tickets WHERE status = 'closed'");
            $stmt->execute();
            $result = $stmt->fetch();
            $closed_tickets = $result['count'] ?? 0;
        }

    } catch (PDOException $e) {
        // Log error and set defaults for tickets only
        error_log("Error computing ticket stats: " . $e->getMessage());
        $open_tickets = 0;
        $closed_tickets = 0;
    }
}

// Handle projects separately so errors don't affect ticket counts
if (isset($pdo) && defined('ENABLE_PROJECTS') && ENABLE_PROJECTS) {
    try {
        if (isAdminOrStaff()) {
            // Admins and staff can see all projects
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM projects");
            $stmt->execute();
        } else {
            // Regular users see projects assigned to them (same logic as projects.php)
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM projects WHERE user_id = ?");
            $stmt->execute([$_SESSION['user_id']]);
        }
        $result = $stmt->fetch();
        $total_projects = $result['count'] ?? 0;
    } catch (PDOException $e) {
        // Log error and set default for projects only
        error_log("Error computing project stats: " . $e->getMessage());
        $total_projects = 0;
    }
}

?>
<h4><?php echo sprintf($lang_frontend['ACCOUNT_WELCOME_TO_SITE'] ?? 'Welcome to %s', SITE_NAME); ?></h4><br>
<div class="row mb-4">

    <div class="col-md-4">
        <div class="card bg-light-success text-dark h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase">
                            <?php echo $lang_frontend['ACCOUNT_CARD_OPEN_TICKETS_TITLE'] ?? 'Open Tickets'; ?></h6>
                        <h2 class="mb-0"><?php echo $open_tickets; ?></h2>
                    </div>
                    <i class="bi bi-ticket-detailed" style="font-size: 3rem;"></i>
                </div>
            </div>

        </div>
    </div>

    <div class="col-md-4">
        <div class="card bg-light-warning text-dark h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase">
                            <?php echo $lang_frontend['ACCOUNT_CARD_CLOSED_TICKETS_TITLE'] ?? 'Closed Tickets'; ?></h6>
                        <h2 class="mb-0"><?php echo $closed_tickets; ?></h2>
                    </div>
                    <i class="bi bi-journal-text" style="font-size: 3rem;"></i>
                </div>
            </div>

        </div>
    </div>
    <?php if (isLoggedIn() && defined('ENABLE_PROJECTS') && ENABLE_PROJECTS): ?>
        <div class="col-md-4">
            <div class="card bg-light-info text-dark h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-uppercase">
                                <?php echo $lang_frontend['ACCOUNT_CARD_TOTAL_PROJECTS_TITLE'] ?? 'Total Projects'; ?></h6>
                            <h2 class="mb-0"><?php echo $total_projects; ?></h2>
                        </div>
                        <i class="bi bi-kanban" style="font-size: 3rem;"></i>
                    </div>
                </div>

            </div>
        </div>
    <?php endif; ?>

</div>

<!-- Recent Tickets Section -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-clock-history me-2"></i>
                    <?php echo isAdminOrStaff() ? ($lang_frontend['ACCOUNT_SECTION_RECENT_TICKETS_ADMIN'] ?? 'Recent Tickets') : ($lang_frontend['ACCOUNT_SECTION_RECENT_OPEN_TICKETS_USER'] ?? 'Recent Open Tickets'); ?>
                </h5>
            </div>
            <div class="card-body p-0">
                <?php
                // Fetch recent tickets based on user role
                $recent_tickets = [];

                if (isset($pdo)) {
                    try {
                        if (isAdminOrStaff()) {
                            // Staff/Admin: Show last 10 newest tickets (any status)
                            $stmt = $pdo->prepare("
                                SELECT t.*, u.name as user_name, tc.name as category_name,
                                       (SELECT COUNT(*) FROM ticket_replies c WHERE c.ticket_id = t.id) AS comment_count
                                FROM tickets t 
                                LEFT JOIN users u ON t.user_id = u.id 
                                LEFT JOIN ticket_categories tc ON t.category_id = tc.id
                                ORDER BY t.created_at DESC 
                                LIMIT 10
                            ");
                            $stmt->execute();
                        } else {
                            // Regular users: Show last 10 open tickets for this user
                            $user_email = '';
                            $stmt_user = $pdo->prepare("SELECT email FROM users WHERE id = ?");
                            $stmt_user->execute([$_SESSION['user_id']]);
                            $user = $stmt_user->fetch();
                            if ($user) {
                                $user_email = $user['email'];
                            }

                            $stmt = $pdo->prepare("
                                SELECT t.*, u.name as user_name, tc.name as category_name,
                                       (SELECT COUNT(*) FROM ticket_replies c WHERE c.ticket_id = t.id) AS comment_count
                                FROM tickets t 
                                LEFT JOIN users u ON t.user_id = u.id 
                                LEFT JOIN ticket_categories tc ON t.category_id = tc.id
                                WHERE (t.user_id = ? OR t.email = ?) AND t.status = 'open'
                                ORDER BY t.created_at DESC 
                                LIMIT 10
                            ");
                            $stmt->execute([$_SESSION['user_id'], $user_email]);
                        }

                        $recent_tickets = $stmt->fetchAll();

                    } catch (PDOException $e) {
                        error_log("Error fetching recent tickets: " . $e->getMessage());
                        $recent_tickets = [];
                    }
                }

                if (empty($recent_tickets)): ?>
                    <div class="p-4 text-center text-muted">
                        <i class="bi bi-inbox display-4 d-block mb-3"></i>
                        <p class="mb-0">
                            <?php echo isAdminOrStaff() ? ($lang_frontend['ACCOUNT_TEXT_NO_TICKETS_ADMIN'] ?? 'No tickets found.') : ($lang_frontend['ACCOUNT_TEXT_NO_OPEN_TICKETS_USER'] ?? 'No open tickets found.'); ?>
                        </p>
                        <a href="<?php echo getCleanUrl('ticket_create'); ?>" class="btn btn-primary mt-2">
                            <i class="bi bi-plus"></i>
                            <?php echo $lang_frontend['ACCOUNT_BUTTON_CREATE_NEW_TICKET'] ?? 'Create New Ticket'; ?>
                        </a>
                    </div>
                <?php else: ?>
                    <div class="list-group list-group-flush">
                        <?php foreach ($recent_tickets as $ticket): ?>
                            <a href="<?php echo getCleanUrl('ticket_view/' . $ticket['id']); ?>"
                                class="list-group-item list-group-item-action">
                                <div class="d-flex w-100 justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="d-flex align-items-center mb-1">
                                            <span class="badge bg-secondary me-2">#<?php echo $ticket['id']; ?></span>
                                            <h6 class="mb-0 me-2"><?php echo htmlspecialchars($ticket['subject']); ?></h6>

                                            <!-- Status badge -->
                                            <span
                                                class="badge <?php echo $ticket['status'] === 'open' ? 'bg-success' : 'bg-secondary'; ?> me-2">
                                                <?php echo ucfirst($ticket['status']); ?>
                                            </span>

                                            <!-- Comment count -->
                                            <?php if ($ticket['comment_count'] > 0): ?>
                                                <span class="badge bg-primary me-2">
                                                    <i class="bi bi-chat-dots"></i> <?php echo $ticket['comment_count']; ?>
                                                </span>
                                            <?php endif; ?>

                                            <!-- Attachment indicator -->
                                            <?php if (!empty($ticket['attachment'])): ?>
                                                <i class="bi bi-paperclip text-muted"
                                                    title="<?php echo $lang_frontend['TOOLTIP_HAS_ATTACHMENT'] ?? 'Has attachment'; ?>"></i>
                                            <?php endif; ?>
                                        </div>

                                        <div class="d-flex align-items-center text-muted small">
                                            <!-- Category -->
                                            <?php if (!empty($ticket['category_name'])): ?>
                                                <span class="me-3">
                                                    <i class="bi bi-tag"></i>
                                                    <?php echo htmlspecialchars($ticket['category_name']); ?>
                                                </span>
                                            <?php endif; ?>

                                            <!-- User info (for staff/admin) -->
                                            <?php if (isAdminOrStaff()): ?>
                                                <span class="me-3">
                                                    <i class="bi bi-person"></i>
                                                    <?php
                                                    if (!empty($ticket['user_name'])) {
                                                        echo htmlspecialchars($ticket['user_name']);
                                                    } elseif (!empty($ticket['email'])) {
                                                        echo htmlspecialchars($ticket['email']) . ' ' . ($lang_frontend['TEXT_GUEST_SUFFIX'] ?? '(Guest)');
                                                    } else {
                                                        echo $lang_frontend['TEXT_GUEST_USER'] ?? 'Guest';
                                                    }
                                                    ?>
                                                </span>
                                            <?php endif; ?>

                                            <!-- Created date -->
                                            <span>
                                                <i class="bi bi-calendar"></i>
                                                <span
                                                    title="<?php echo htmlspecialchars(getFormattedDate($ticket['created_at'])); ?>">
                                                    <?php echo timeAgo($ticket['created_at'], [
                                                        'just_now' => $lang_frontend['TIMEAGO_JUST_NOW'],
                                                        'minute_ago' => $lang_frontend['TIMEAGO_MINUTE_AGO'],
                                                        'minutes_ago' => $lang_frontend['TIMEAGO_MINUTES_AGO'],
                                                        'hour_ago' => $lang_frontend['TIMEAGO_HOUR_AGO'],
                                                        'hours_ago' => $lang_frontend['TIMEAGO_HOURS_AGO'],
                                                        'day_ago' => $lang_frontend['TIMEAGO_DAY_AGO'],
                                                        'days_ago' => $lang_frontend['TIMEAGO_DAYS_AGO'],
                                                        'week_ago' => $lang_frontend['TIMEAGO_WEEK_AGO'],
                                                        'weeks_ago' => $lang_frontend['TIMEAGO_WEEKS_AGO'],
                                                        'month_ago' => $lang_frontend['TIMEAGO_MONTH_AGO'],
                                                        'months_ago' => $lang_frontend['TIMEAGO_MONTHS_AGO'],
                                                        'year_ago' => $lang_frontend['TIMEAGO_YEAR_AGO'],
                                                        'years_ago' => $lang_frontend['TIMEAGO_YEARS_AGO'],
                                                    ]); ?>
                                                </span>
                                            </span>
                                        </div>
                                    </div>

                                    <div class="text-end">
                                        <i class="bi bi-chevron-right text-muted"></i>
                                    </div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>

                    <?php if (count($recent_tickets) === 10): ?>
                        <div class="card-footer text-center">
                            <a href="<?php echo getCleanUrl('tickets'); ?>" class="btn btn-outline-primary btn-sm">
                                <i class="bi bi-arrow-right"></i>
                                <?php echo $lang_frontend['ACCOUNT_BUTTON_VIEW_ALL_TICKETS'] ?? 'View All Tickets'; ?>
                            </a>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
// Check if any Pro features are enabled and get user's quotes/invoices counts
$quotes_count = 0;
$invoices_count = 0;
$pending_invoices = 0;
$subscriptions_count = 0;
$active_subscriptions = 0;

if (isset($pdo) && !isAdminOrStaff()) {
    try {
        // Get user's email for quotes/invoices lookup
        $user_email = '';
        $stmt_user = $pdo->prepare("SELECT email FROM users WHERE id = ?");
        $stmt_user->execute([$_SESSION['user_id']]);
        $user = $stmt_user->fetch();
        if ($user) {
            $user_email = $user['email'];
        }

        // Count quotes
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM quotes WHERE user_id = ? OR client_email = ?");
        $stmt->execute([$_SESSION['user_id'], $user_email]);
        $result = $stmt->fetch();
        $quotes_count = $result['count'] ?? 0;

        // Count invoices
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM invoices WHERE user_id = ? OR client_email = ?");
        $stmt->execute([$_SESSION['user_id'], $user_email]);
        $result = $stmt->fetch();
        $invoices_count = $result['count'] ?? 0;

        // Count pending/unpaid invoices
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM invoices WHERE (user_id = ? OR client_email = ?) AND status IN ('sent', 'overdue')");
        $stmt->execute([$_SESSION['user_id'], $user_email]);
        $result = $stmt->fetch();
        $pending_invoices = $result['count'] ?? 0;

        // Count subscriptions (including guest subscriptions by email)
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as count 
            FROM subscriptions s
            LEFT JOIN orders o ON s.order_id = o.id
            WHERE s.user_id = ? OR (s.user_id IS NULL AND o.client_email = ?)
        ");
        $stmt->execute([$_SESSION['user_id'], $user_email]);
        $result = $stmt->fetch();
        $subscriptions_count = $result['count'] ?? 0;

        // Count active subscriptions (including guest subscriptions by email)
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as count 
            FROM subscriptions s
            LEFT JOIN orders o ON s.order_id = o.id
            WHERE (s.user_id = ? OR (s.user_id IS NULL AND o.client_email = ?)) 
              AND s.status IN ('active', 'trial')
        ");
        $stmt->execute([$_SESSION['user_id'], $user_email]);
        $result = $stmt->fetch();
        $active_subscriptions = $result['count'] ?? 0;

        // Auto-link guest subscriptions to this user account
        if (!empty($user_email)) {
            $stmt_update = $pdo->prepare("
                UPDATE subscriptions s
                JOIN orders o ON s.order_id = o.id
                SET s.user_id = ?
                WHERE s.user_id IS NULL AND o.client_email = ?
            ");
            $stmt_update->execute([$_SESSION['user_id'], $user_email]);
        }

        // Also check for and fix any incomplete subscriptions for this user
        if (function_exists('fixIncompleteSubscriptions')) {
            $fix_result = fixIncompleteSubscriptions($pdo);
            if ($fix_result['fixed'] > 0) {
                error_log("account.php: Fixed {$fix_result['fixed']} incomplete subscriptions for user {$_SESSION['user_id']}");
                // Re-count subscriptions after fixing
                $stmt->execute([$_SESSION['user_id'], $user_email]);
                $result = $stmt->fetch();
                $subscriptions_count = $result['count'] ?? 0;

                $stmt = $pdo->prepare("
                    SELECT COUNT(*) as count 
                    FROM subscriptions s
                    LEFT JOIN orders o ON s.order_id = o.id
                    WHERE (s.user_id = ? OR (s.user_id IS NULL AND o.client_email = ?)) 
                      AND s.status IN ('active', 'trial')
                ");
                $stmt->execute([$_SESSION['user_id'], $user_email]);
                $result = $stmt->fetch();
                $active_subscriptions = $result['count'] ?? 0;
            }
        }

    } catch (PDOException $e) {
        error_log("Error fetching pro features stats: " . $e->getMessage());
    }
}

// Always show Pro features section to display quotes and invoices
?>

<div class="row">
    <div class="col-12">
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><?php echo $lang_frontend['ACCOUNT_SECTION_MAIN_FEATURES'] ?? 'Main features'; ?></h5>
            </div>
            <div class="card-body">

                <div class="row mt-4">
                    <div class="col-md-4 mb-3">
                        <a href="profile" class="btn btn-outline-primary btn-lg w-100">
                            <i class="bi bi-person me-2"></i>
                            <?php echo $lang_frontend['ACCOUNT_BUTTON_PROFILE'] ?? ($lang_navigation['NAV_DROPDOWN_PROFILE'] ?? 'Profile'); ?>
                        </a>
                    </div>
                    <div class="col-md-4 mb-3">
                        <a href="tickets" class="btn btn-outline-primary btn-lg w-100">
                            <i class="bi bi-ticket-detailed me-2"></i>
                            <?php echo $lang_frontend['ACCOUNT_BUTTON_TICKETS'] ?? ($lang_navigation['NAV_TICKETS'] ?? 'Tickets'); ?>
                        </a>
                    </div>
                    <?php if (isLoggedIn() && defined('ENABLE_PROJECTS') && ENABLE_PROJECTS): ?>
                        <div class="col-md-4 mb-3">
                            <a href="projects" class="btn btn-outline-primary btn-lg w-100">
                                <i class="bi bi-kanban me-2"></i>
                                <?php echo $lang_frontend['ACCOUNT_BUTTON_PROJECTS'] ?? ($lang_navigation['NAV_PROJECTS'] ?? 'Projects'); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                    <?php if (isLoggedIn() && defined('QUOTES_MANAGEMENT') && QUOTES_MANAGEMENT): ?>
                        <div class="col-md-4 mb-3">
                            <div class="card bg-light-info h-100">
                                <div class="card-body text-center">
                                    <i class="bi bi-file-earmark-text display-4 text-info mb-2"></i>
                                    <h6 class="card-title">
                                        <?php echo $lang_frontend['ACCOUNT_CARD_QUOTES_TITLE'] ?? 'Quotes'; ?></h6>
                                    <h3 class="text-info"><?php echo $quotes_count; ?></h3>
                                    <a href="<?php echo getCleanUrl('user_quotes'); ?>"
                                        class="btn btn-outline-primary btn-sm"><?php echo $lang_frontend['ACCOUNT_BUTTON_VIEW_ALL_QUOTES'] ?? 'View All'; ?></a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (isLoggedIn() && defined('INVOICE_MANAGEMENT') && INVOICE_MANAGEMENT): ?>
                        <div class="col-md-4 mb-3">
                            <div class="card bg-light-warning h-100">
                                <div class="card-body text-center">
                                    <i class="bi bi-receipt display-4 text-warning mb-2"></i>
                                    <h6 class="card-title">
                                        <?php echo $lang_frontend['ACCOUNT_CARD_INVOICES_TITLE'] ?? 'Invoices'; ?></h6>
                                    <h3 class="text-warning">
                                        <?php echo $invoices_count; ?>    <?php if ($pending_invoices > 0): ?>
                                            <font color="red">
                                                (<?php echo sprintf($lang_frontend['ACCOUNT_TEXT_PENDING_INVOICES'] ?? '%s pending', $pending_invoices); ?>)
                                            </font><?php endif; ?>
                                    </h3>

                                    <a href="<?php echo getCleanUrl('user_invoices'); ?>"
                                        class="btn btn-outline-primary btn-sm"><?php echo $lang_frontend['ACCOUNT_BUTTON_VIEW_ALL_INVOICES'] ?? 'View All'; ?></a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (isLoggedIn() && defined('SUBSCRIPTIONS_MANAGEMENT') && SUBSCRIPTIONS_MANAGEMENT): ?>
                        <div class="col-md-4 mb-3">
                            <div class="card bg-light-success h-100">
                                <div class="card-body text-center">
                                    <i class="bi bi-arrow-repeat display-4 text-success mb-2"></i>
                                    <h6 class="card-title">
                                        <?php echo $lang_frontend['ACCOUNT_CARD_SUBSCRIPTIONS_TITLE'] ?? 'Subscriptions'; ?>
                                    </h6>
                                    <h3 class="text-success">
                                        <?php if ($active_subscriptions > 0): ?>        <?php echo sprintf($lang_frontend['ACCOUNT_TEXT_ACTIVE_SUBSCRIPTIONS'] ?? '%s active', $active_subscriptions); ?>
                                        <?php else: ?>        <?php echo $active_subscriptions; ?>    <?php endif; ?></h3>


                                    <a href="<?php echo getCleanUrl('user_subscriptions'); ?>"
                                        class="btn btn-outline-primary btn-sm"><?php echo $lang_frontend['ACCOUNT_BUTTON_MANAGE_SUBSCRIPTIONS'] ?? 'Manage'; ?></a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                </div>
            </div>
        </div>
    </div>
</div>



<?php
// Include footer
include 'includes/footer.php';
?>