<?php
/**
 * Hostxolo - Enhanced User Dashboard
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'Dashboard';
$user_id = $_SESSION['user_id'];

// Get user details
$user = [];
try {
    $stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
} catch (PDOException $e) {}

// Get active subscriptions with plan details
$subscriptions = [];
try {
    $stmt = db()->prepare("SELECT us.*, sp.name as plan_name, sp.monthly_price, sp.yearly_price, sp.features
                          FROM user_subscriptions us
                          JOIN subscription_plans sp ON us.plan_id = sp.id
                          WHERE us.user_id = ?
                          ORDER BY us.created_at DESC");
    $stmt->execute([$user_id]);
    $subscriptions = $stmt->fetchAll();
} catch (PDOException $e) {}

// Get support tickets with count
$tickets = [];
$ticket_stats = ['open' => 0, 'in_progress' => 0, 'resolved' => 0, 'closed' => 0];
try {
    $stmt = db()->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
    $stmt->execute([$user_id]);
    $tickets = $stmt->fetchAll();
    
    foreach ($tickets as $ticket) {
        if (isset($ticket_stats[$ticket['status']])) {
            $ticket_stats[$ticket['status']]++;
        }
    }
} catch (PDOException $e) {}

// Get transaction history
$transactions = [];
try {
    $stmt = db()->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
    $stmt->execute([$user_id]);
    $transactions = $stmt->fetchAll();
} catch (PDOException $e) {}

// Calculate statistics
$active_subs = count(array_filter($subscriptions, fn($s) => $s['status'] === 'active'));
$expired_subs = count(array_filter($subscriptions, fn($s) => $s['status'] === 'expired'));
$open_tickets = $ticket_stats['open'] + $ticket_stats['in_progress'];
$total_spent = array_sum(array_column(array_filter($transactions, fn($t) => $t['status'] === 'success'), 'total_amount'));

// Get latest active subscription for progress bar
$latest_sub = $subscriptions[0] ?? null;
$days_remaining = 0;
$progress_percent = 0;
if ($latest_sub && $latest_sub['status'] === 'active') {
    $end = new DateTime($latest_sub['end_date']);
    $now = new DateTime();
    $start = new DateTime($latest_sub['start_date']);
    $total_days = $start->diff($end)->days;
    $days_used = $start->diff($now)->days;
    $days_remaining = max(0, $now->diff($end)->days);
    $progress_percent = $total_days > 0 ? min(100, round(($days_used / $total_days) * 100)) : 0;
}

include __DIR__ . '/includes/header.php';
?>

<style>
.dashboard-card {
    transition: all 0.3s ease;
    border: none;
    border-radius: 16px;
}
.dashboard-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.1) !important;
}
.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.welcome-banner {
    background: linear-gradient(135deg, #f97316 0%, #ea580c 50%, #c2410c 100%);
    border-radius: 16px;
    position: relative;
    overflow: hidden;
}
.welcome-banner::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -10%;
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
    border-radius: 50%;
}
.welcome-banner::after {
    content: '';
    position: absolute;
    bottom: -50%;
    left: -10%;
    width: 300px;
    height: 300px;
    background: radial-gradient(circle, rgba(255,255,255,0.08) 0%, transparent 70%);
    border-radius: 50%;
}
.subscription-card {
    background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 16px;
    border: 1px solid #e2e8f0;
}
.progress-ring {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: conic-gradient(#f97316 calc(var(--progress) * 1%), #e2e8f0 0);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}
.progress-ring::before {
    content: '';
    width: 65px;
    height: 65px;
    background: white;
    border-radius: 50%;
    position: absolute;
}
.progress-ring span {
    position: relative;
    z-index: 1;
    font-weight: 700;
    font-size: 0.875rem;
}
.activity-timeline {
    position: relative;
    padding-left: 2rem;
}
.activity-timeline::before {
    content: '';
    position: absolute;
    left: 0.5rem;
    top: 0;
    bottom: 0;
    width: 2px;
    background: linear-gradient(to bottom, #f97316, #fb923c, #fdba74);
    border-radius: 1px;
}
.timeline-item {
    position: relative;
    padding-bottom: 1.5rem;
}
.timeline-item::before {
    content: '';
    position: absolute;
    left: -1.75rem;
    top: 0.25rem;
    width: 12px;
    height: 12px;
    background: white;
    border: 3px solid #f97316;
    border-radius: 50%;
}
.timeline-item.success::before { border-color: #10b981; }
.timeline-item.warning::before { border-color: #f59e0b; }
.timeline-item.danger::before { border-color: #ef4444; }
.quick-action {
    transition: all 0.2s ease;
}
.quick-action:hover {
    background: #eff6ff;
    transform: scale(1.02);
}
.status-pulse {
    animation: pulse 2s infinite;
}
@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}
</style>

<!-- Welcome Banner -->
<div class="welcome-banner text-white p-4 mb-4">
    <div class="row align-items-center position-relative" style="z-index: 1;">
        <div class="col-lg-8">
            <h2 class="fw-bold mb-2">Welcome back, <?php echo $user['full_name']; ?>!</h2>
            <p class="mb-0 opacity-90">Here's everything you need to know about your account today.</p>
        </div>
        <div class="col-lg-4 text-lg-end mt-3 mt-lg-0">
            <a href="<?php echo BASE_URL; ?>plans.php" class="btn btn-light btn-lg">
                <i class="bi bi-plus-circle me-2"></i>Upgrade Plan
            </a>
        </div>
    </div>
</div>

<!-- Stats Cards -->
<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="card dashboard-card shadow-sm h-100">
            <div class="card-body p-4">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-primary bg-opacity-10 text-primary me-3">
                        <i class="bi bi-credit-card fs-3"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1 small">Active Subscriptions</p>
                        <h3 class="fw-bold mb-0"><?php echo $active_subs; ?></h3>
                    </div>
                </div>
                <div class="mt-3">
                    <?php if ($expired_subs > 0): ?>
                        <span class="badge bg-warning text-dark"><i class="bi bi-exclamation-circle me-1"></i><?php echo $expired_subs; ?> expired</span>
                    <?php else: ?>
                        <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>All active</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6 col-xl-3">
        <div class="card dashboard-card shadow-sm h-100">
            <div class="card-body p-4">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-warning bg-opacity-10 text-warning me-3">
                        <i class="bi bi-headset fs-3"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1 small">Support Tickets</p>
                        <h3 class="fw-bold mb-0"><?php echo $open_tickets; ?></h3>
                    </div>
                </div>
                <div class="mt-3">
                    <?php if ($ticket_stats['open'] > 0): ?>
                        <span class="badge bg-danger status-pulse"><i class="bi bi-circle-fill me-1 small"></i><?php echo $ticket_stats['open']; ?> open</span>
                    <?php elseif ($ticket_stats['in_progress'] > 0): ?>
                        <span class="badge bg-warning"><i class="bi bi-clock me-1"></i><?php echo $ticket_stats['in_progress']; ?> in progress</span>
                    <?php else: ?>
                        <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>No open tickets</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6 col-xl-3">
        <div class="card dashboard-card shadow-sm h-100">
            <div class="card-body p-4">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-success bg-opacity-10 text-success me-3">
                        <i class="bi bi-wallet2 fs-3"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1 small">Total Spent</p>
                        <h3 class="fw-bold mb-0"><?php echo format_currency($total_spent); ?></h3>
                    </div>
                </div>
                <div class="mt-3">
                    <small class="text-muted">Across <?php echo count($transactions); ?> transactions</small>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-6 col-xl-3">
        <div class="card dashboard-card shadow-sm h-100">
            <div class="card-body p-4">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-info bg-opacity-10 text-info me-3">
                        <i class="bi bi-calendar-check fs-3"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1 small">Member Since</p>
                        <h3 class="fw-bold mb-0"><?php echo format_date($user['created_at'], 'M Y'); ?></h3>
                    </div>
                </div>
                <div class="mt-3">
                    <?php
                    $member_days = (new DateTime($user['created_at']))->diff(new DateTime())->days;
                    ?>
                    <small class="text-muted"><?php echo $member_days; ?> days with us</small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Grid -->
<div class="row g-4">
    <!-- Left Column -->
    <div class="col-lg-8">
        <!-- Current Subscription Status -->
        <?php if ($latest_sub): ?>
        <div class="card dashboard-card shadow-sm mb-4">
            <div class="card-header bg-white border-0 pt-4 pb-0">
                <h5 class="fw-bold"><i class="bi bi-star-fill text-warning me-2"></i>Current Plan Status</h5>
            </div>
            <div class="card-body p-4">
                <div class="subscription-card p-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <div class="d-flex align-items-center mb-3">
                                <span class="badge bg-<?php echo $latest_sub['status'] === 'active' ? 'success' : 'danger'; ?> me-2">
                                    <?php echo ucfirst($latest_sub['status']); ?>
                                </span>
                                <h4 class="mb-0 fw-bold"><?php echo $latest_sub['plan_name']; ?></h4>
                            </div>
                            <p class="text-muted mb-3">
                                <i class="bi bi-calendar me-2"></i>
                                Valid from <?php echo format_date($latest_sub['start_date']); ?> to <?php echo format_date($latest_sub['end_date']); ?>
                            </p>
                            <div class="d-flex gap-2">
                                <span class="badge bg-light text-dark border">
                                    <i class="bi bi-clock me-1"></i><?php echo ucfirst($latest_sub['subscription_type']); ?>ly
                                </span>
                                <span class="badge bg-light text-dark border">
                                    <i class="bi bi-currency-rupee me-1"></i><?php echo format_currency($latest_sub['amount']); ?>
                                </span>
                            </div>
                        </div>
                        <div class="col-md-4 text-center mt-3 mt-md-0">
                            <div class="progress-ring mx-auto mb-2" style="--progress: <?php echo $progress_percent; ?>">
                                <span class="text-primary"><?php echo $days_remaining; ?>d</span>
                            </div>
                            <p class="text-muted small mb-0">Days Remaining</p>
                        </div>
                    </div>
                    <?php if ($latest_sub['features']): ?>
                    <hr class="my-4">
                    <div class="row">
                        <?php foreach (array_slice(json_decode($latest_sub['features'], true) ?? [], 0, 4) as $feature): ?>
                        <div class="col-6 col-md-3 mb-2">
                            <small class="text-muted"><i class="bi bi-check-circle-fill text-success me-1"></i><?php echo $feature; ?></small>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div class="card dashboard-card shadow-sm mb-4 border-warning">
            <div class="card-body p-4 text-center">
                <i class="bi bi-credit-card text-muted" style="font-size: 3rem;"></i>
                <h5 class="mt-3">No Active Subscription</h5>
                <p class="text-muted mb-3">Choose a plan to unlock all features</p>
                <a href="<?php echo BASE_URL; ?>plans.php" class="btn btn-primary">
                    <i class="bi bi-plus-circle me-2"></i>Browse Plans
                </a>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Recent Activity Timeline -->
        <div class="card dashboard-card shadow-sm">
            <div class="card-header bg-white border-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                <h5 class="fw-bold"><i class="bi bi-activity text-primary me-2"></i>Recent Activity</h5>
                <a href="transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body p-4">
                <?php if (empty($transactions) && empty($tickets)): ?>
                    <div class="text-center py-4">
                        <i class="bi bi-inbox text-muted" style="font-size: 2rem;"></i>
                        <p class="text-muted mt-2 mb-0">No recent activity</p>
                    </div>
                <?php else: ?>
                    <div class="activity-timeline">
                        <?php 
                        $activities = [];
                        foreach ($transactions as $tx) {
                            $activities[] = [
                                'type' => 'transaction',
                                'date' => $tx['created_at'],
                                'data' => $tx
                            ];
                        }
                        foreach ($tickets as $ticket) {
                            $activities[] = [
                                'type' => 'ticket',
                                'date' => $ticket['created_at'],
                                'data' => $ticket
                            ];
                        }
                        usort($activities, fn($a, $b) => strtotime($b['date']) - strtotime($a['date']));
                        
                        foreach (array_slice($activities, 0, 5) as $activity): 
                            if ($activity['type'] === 'transaction'):
                                $tx = $activity['data'];
                                $status_class = $tx['status'] === 'success' ? 'success' : ($tx['status'] === 'pending' ? 'warning' : 'danger');
                        ?>
                        <div class="timeline-item <?php echo $status_class; ?>">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <p class="fw-medium mb-1">Payment <?php echo ucfirst($tx['status']); ?></p>
                                    <p class="text-muted small mb-0">Transaction #<?php echo $tx['transaction_number']; ?></p>
                                </div>
                                <span class="badge bg-light text-dark"><?php echo format_currency($tx['total_amount']); ?></span>
                            </div>
                            <small class="text-muted"><?php echo format_date($activity['date'], 'M d, Y h:i A'); ?></small>
                        </div>
                        <?php else: 
                            $ticket = $activity['data'];
                            $status_class = $ticket['status'] === 'open' ? 'danger' : ($ticket['status'] === 'in_progress' ? 'warning' : 'success');
                        ?>
                        <div class="timeline-item <?php echo $status_class; ?>">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <p class="fw-medium mb-1">Ticket #<?php echo $ticket['ticket_number']; ?></p>
                                    <p class="text-muted small mb-0"><?php echo substr($ticket['subject'], 0, 50); ?>...</p>
                                </div>
                                <span class="badge bg-<?php echo $status_class; ?>"><?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?></span>
                            </div>
                            <small class="text-muted"><?php echo format_date($activity['date'], 'M d, Y h:i A'); ?></small>
                        </div>
                        <?php endif; endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Right Column -->
    <div class="col-lg-4">
        <!-- Quick Actions -->
        <div class="card dashboard-card shadow-sm mb-4">
            <div class="card-header bg-white border-0 pt-4 pb-0">
                <h5 class="fw-bold"><i class="bi bi-lightning-charge-fill text-warning me-2"></i>Quick Actions</h5>
            </div>
            <div class="card-body p-3">
                <a href="<?php echo BASE_URL; ?>plans.php" class="quick-action d-flex align-items-center p-3 rounded text-decoration-none text-dark">
                    <div class="stat-icon bg-primary bg-opacity-10 text-primary me-3" style="width: 45px; height: 45px;">
                        <i class="bi bi-plus-circle fs-5"></i>
                    </div>
                    <div>
                        <h6 class="mb-0">Upgrade Plan</h6>
                        <small class="text-muted">Get more features</small>
                    </div>
                    <i class="bi bi-chevron-right ms-auto text-muted"></i>
                </a>
                <a href="create-ticket.php" class="quick-action d-flex align-items-center p-3 rounded text-decoration-none text-dark">
                    <div class="stat-icon bg-warning bg-opacity-10 text-warning me-3" style="width: 45px; height: 45px;">
                        <i class="bi bi-headset fs-5"></i>
                    </div>
                    <div>
                        <h6 class="mb-0">Get Support</h6>
                        <small class="text-muted">Create a ticket</small>
                    </div>
                    <i class="bi bi-chevron-right ms-auto text-muted"></i>
                </a>
                <a href="profile.php" class="quick-action d-flex align-items-center p-3 rounded text-decoration-none text-dark">
                    <div class="stat-icon bg-success bg-opacity-10 text-success me-3" style="width: 45px; height: 45px;">
                        <i class="bi bi-person-gear fs-5"></i>
                    </div>
                    <div>
                        <h6 class="mb-0">Edit Profile</h6>
                        <small class="text-muted">Update details</small>
                    </div>
                    <i class="bi bi-chevron-right ms-auto text-muted"></i>
                </a>
                <a href="subscriptions.php" class="quick-action d-flex align-items-center p-3 rounded text-decoration-none text-dark">
                    <div class="stat-icon bg-info bg-opacity-10 text-info me-3" style="width: 45px; height: 45px;">
                        <i class="bi bi-receipt fs-5"></i>
                    </div>
                    <div>
                        <h6 class="mb-0">My Invoices</h6>
                        <small class="text-muted">Download receipts</small>
                    </div>
                    <i class="bi bi-chevron-right ms-auto text-muted"></i>
                </a>
            </div>
        </div>
        
        <!-- Need Help -->
        <div class="card dashboard-card shadow-sm bg-primary text-white">
            <div class="card-body p-4">
                <div class="d-flex align-items-center mb-3">
                    <div class="stat-icon bg-white bg-opacity-20 me-3" style="width: 50px; height: 50px;">
                        <i class="bi bi-question-circle fs-4"></i>
                    </div>
                    <h5 class="mb-0 fw-bold">Need Help?</h5>
                </div>
                <p class="opacity-90 mb-3">Our support team is available 24/7 to assist you with any questions.</p>
                <a href="<?php echo BASE_URL; ?>support.php" class="btn btn-light w-100">
                    <i class="bi bi-chat-dots me-2"></i>Contact Support
                </a>
            </div>
        </div>
    </div>
</div>

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

