<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];

// Get totals
$total_views = 0;
$total_revenue = 0;
$total_payments_count = 0;
$total_videos_count = 0;
$site_settings = get_site_settings($pdo);
$system_comm = $site_settings['system_commission'] ?? 0;

try {
    // Total videos count
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM videos WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $total_videos_count = $stmt->fetchColumn() ?: 0;
    // Total views for user's videos
    $stmt = $pdo->prepare("SELECT SUM(views) as tv FROM videos WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $total_views = $stmt->fetchColumn() ?: 0;

    // Total transactions matching user's videos
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as tc, SUM(t.amount) as tr
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed'
    ");
    $stmt->execute([$user_id]);
    $trans_data = $stmt->fetch();
    if ($trans_data) {
        $total_payments_count = $trans_data['tc'] ?: 0;
        $gross_revenue = $trans_data['tr'] ?: 0;
        $total_revenue = $gross_revenue * (1 - ($system_comm / 100));
    }
    
    $stmt = $pdo->prepare("
        SELECT v.*, (SELECT COALESCE(SUM(amount),0) FROM transactions WHERE video_id = v.id AND status='completed') as gross_revenue 
        FROM videos v 
        WHERE user_id = ? 
        ORDER BY gross_revenue DESC LIMIT 5
    ");
    $stmt->execute([$user_id]);
    $top_videos = $stmt->fetchAll();
    
    $stmt = $pdo->prepare("SELECT message, type FROM system_notifications WHERE is_active = 1 ORDER BY created_at DESC LIMIT 1");
    $stmt->execute();
    $latest_notification = $stmt->fetch() ?: null;
    
} catch (PDOException $e) {}

$pageTitle = "Dashboard - Kindamba Pay";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Dashboard</h6>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium">
                        <a href="dashboard.php" class="d-flex align-items-center gap-1 hover-text-primary">
                            <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon>
                            Dashboard
                        </a>
                    </li>
                </ul>
            </div>

            <style>
                .sophisticated-card {
                    background: white;
                    border: 1px solid rgba(0,0,0,0.05);
                    box-shadow: 0 4px 15px rgba(0,0,0,0.03);
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                }
                .sophisticated-card:hover { 
                    transform: translateY(-4px); 
                    box-shadow: 0 12px 25px rgba(0,0,0,0.06); 
                }
                .icon-overlay {
                    position: absolute;
                    right: 8px;
                    bottom: 8px;
                    font-size: 60px;
                    opacity: 0.03;
                    pointer-events: none;
                }
            </style>

            <?php if (!empty($latest_notification)): 
                $notifType = $latest_notification['type'] ?? 'primary';
                $alertStyles = [
                    'primary' => ['alert' => 'alert-primary',  'bg' => '#eef2ff', 'border' => '#6366f1', 'icon_bg' => '#6366f1', 'title' => 'System Announcement'],
                    'info'    => ['alert' => 'alert-info',     'bg' => '#e0f7fa', 'border' => '#0288d1', 'icon_bg' => '#0288d1', 'title' => 'Info'],
                    'success' => ['alert' => 'alert-success',  'bg' => '#f0fdf4', 'border' => '#16a34a', 'icon_bg' => '#16a34a', 'title' => 'Success'],
                    'warning' => ['alert' => 'alert-warning',  'bg' => '#fffbeb', 'border' => '#d97706', 'icon_bg' => '#d97706', 'title' => 'Warning'],
                    'danger'  => ['alert' => 'alert-danger',   'bg' => '#fef2f2', 'border' => '#dc2626', 'icon_bg' => '#dc2626', 'title' => 'Important Notice'],
                ];
                $as = $alertStyles[$notifType] ?? $alertStyles['primary'];
            ?>
            <div class="alert border-0 radius-16 mb-24 p-20 d-flex align-items-center gap-16 shadow-sm <?= $as['alert'] ?>" 
                 style="background:<?= $as['bg'] ?>; border-left: 4px solid <?= $as['border'] ?> !important;">
                <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center text-white text-2xl flex-shrink-0"
                     style="background: <?= $as['icon_bg'] ?>">
                    <iconify-icon icon="solar:bell-bing-bold-duotone"></iconify-icon>
                </div>
                <div class="flex-grow-1">
                    <h6 class="fw-bold mb-4" style="color:<?= $as['border'] ?>"><?= $as['title'] ?></h6>
                    <div class="text-sm fw-medium">
                        <?= $latest_notification['message'] ?>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php endif; ?>

            <!-- Metrics Row -->
            <div class="row gy-4 mb-24">
                <?php
                $metrics = [
                    ['title' => 'Total Views', 'value' => number_format($total_views), 'icon' => 'solar:eye-broken', 'color' => '#6366f1'],
                    ['title' => 'Success Payments', 'value' => number_format($total_payments_count), 'icon' => 'solar:check-read-broken', 'color' => '#10b981'],
                    ['title' => 'Revenue Generated', 'value' => 'TSH ' . number_format($total_revenue), 'icon' => 'solar:dollar-broken', 'color' => '#f59e0b'],
                    ['title' => 'Total Videos', 'value' => number_format($total_videos_count), 'icon' => 'solar:video-library-broken', 'color' => '#ec4899']
                ];

                foreach($metrics as $m):
                ?>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-24 sophisticated-card radius-16 position-relative h-100 border-0">
                        <iconify-icon icon="<?= $m['icon'] ?>" class="icon-overlay"></iconify-icon>
                        <div class="d-flex align-items-center gap-16 mb-16">
                            <div class="w-48-px h-48-px radius-12 d-flex justify-content-center align-items-center bg-base text-2xl" style="color: <?= $m['color'] ?>; background-color: <?= $m['color'] ?>15">
                                <iconify-icon icon="<?= $m['icon'] ?>"></iconify-icon>
                            </div>
                            <span class="fw-bold text-secondary-light text-xs text-uppercase tracking-wider"><?= $m['title'] ?></span>
                        </div>
                        <h4 class="fw-bold mb-0"><?= $m['value'] ?></h4>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="row gy-4">
                <div class="col-xxl-12 col-md-12">
                    <div class="card radius-12 border-0 shadow-sm">
                        <div class="card-header border-bottom bg-base">
                            <div class="d-flex align-items-center flex-wrap gap-2 justify-content-between">
                                <h6 class="mb-0 fw-bold">Top Performing Videos</h6>
                                <a href="videos.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 text-sm fw-medium">
                                    View All Library
                                    <iconify-icon icon="solar:alt-arrow-right-linear" class="icon"></iconify-icon>
                                </a>
                            </div>
                        </div>
                        <div class="card-body p-24">
                            <div class="row gy-4">
                                <?php if(!empty($top_videos)): ?>
                                    <?php foreach($top_videos as $vid): ?>
                                    <div class="col-xl-4 col-md-6">
                                        <div class="d-flex align-items-center p-16 radius-12 border border-black-10 hover-border-primary transition-all">
                                            <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'assets/images/placeholder.jpg') ?>" alt="" class="w-60-px h-60-px rounded-3 flex-shrink-0 me-16 object-fit-cover shadow-sm">
                                            <div class="flex-grow-1 overflow-hidden">
                                                <h6 class="text-sm mb-4 text-truncate"><?= htmlspecialchars($vid['title']) ?></h6>
                                                <div class="d-flex align-items-center gap-12">
                                                    <span class="text-xs text-secondary-light"><i class="ri-eye-line"></i> <?= number_format($vid['views']) ?></span>
                                                    <?php $net_vid_rev = $vid['gross_revenue'] * (1 - ($system_comm / 100)); ?>
                                                    <span class="text-xs text-success-main fw-bold"><i class="ri-money-dollar-circle-line"></i> TSH <?= number_format($net_vid_rev) ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="col-12 text-center py-24">
                                        <img src="assets/images/no-data.png" alt="" class="mb-16 opacity-50" style="width: 80px;">
                                        <p class="text-secondary-light">No video statistics available yet.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/footer.php'; ?>
    </main>
</body>
</html>


