<?php
// Note: This file assumes 'config.php', 'layouts.php', 'require_login()', 'is_admin()', and $pdo are correctly defined elsewhere.

require_once 'config.php';
// require_login(); // Uncomment these lines for actual application use
// 
// if (is_admin()) {
//     header('Location: dashboard.php'); // Redirect admins
//     exit();
// }

// --- HELPER FUNCTION FOR TIME CALCULATION ---
/**
 * Returns a human-readable string for the elapsed time since $datetime.
 * This is needed to replicate the 'age' field from the mock data.
 */
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}


// --- Data Fetching (Updated to match the new design/image) ---
$studentId = $_SESSION['user_id'] ?? '2660092'; 
$userName = htmlspecialchars($_SESSION['user_name'] ?? 'Popantha Winchester'); 

// 2. Dynamic Time-based Greeting for Sri Jayawardenepura (Asia/Colombo, UTC+5:30)
date_default_timezone_set('Asia/Colombo');
$currentHour = (int)date('H'); 
$currentDateDisplay = date('F d, Y'); 

if ($currentHour >= 5 && $currentHour < 12) {
    $greeting = 'Good Morning';
} elseif ($currentHour >= 12 && $currentHour < 17) {
    // 12:00 PM to 4:59 PM
    $greeting = 'Good Afternoon';
} elseif ($currentHour >= 17 && $currentHour < 22) {
    // 5:00 PM to 9:59 PM
    $greeting = 'Good Evening';
} else {
    // 10:00 PM to 4:59 AM
    $greeting = 'Good Night';
}

// Mock data for key metrics
$avgWorkTime = 15; // Hours
$slipEntry = 'Slip is Not'; // Mock status

// --- Notices Database Fetching (Replaces Mock Array) ---
$notices = [];
$importantNoticeCount = 0;

// IMPORTANT: Assuming $pdo (PDO connection object) is available from 'config.php'
if (isset($pdo)) {
    try {
        // Fetch notices ordered by creation time descending (newest first)
        $stmt = $pdo->query("SELECT title, description, created_at FROM notices ORDER BY created_at DESC");
        $db_notices = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($db_notices as $notice) {
            // Combine title and description to form the main text, similar to the original single-text mock
            $text_content = htmlspecialchars($notice['title']) . ': ' . htmlspecialchars($notice['description']);
            
            // Simplified logic to determine importance, since 'is_important' is not in the SQL schema
            // We'll mark notices with 'NA' (Sinhala for 'no') or 'Paper Class' in the title/description as important.
            $is_important = (strpos(strtolower($text_content), 'na') !== false || strpos(strtolower($text_content), 'paper class') !== false);
            
            // Simplified logic to add a link text
            $link_text = null;
            if (strpos(strtolower($text_content), 'gmmk') !== false) {
                $link_text = 'Click here to more details.';
            }

            $notices[] = [
                'text' => $text_content,
                'age' => time_elapsed_string($notice['created_at']), 
                'is_important' => $is_important,
                'link_text' => $link_text
            ];
            
            if ($is_important) {
                $importantNoticeCount++;
            }
        }
    } catch (\PDOException $e) {
        // In a real application, you would log this error. 
        // For this demo, we'll let $notices remain empty and log a message.
        // echo "Error fetching notices: " . $e->getMessage();
    }
} else {
    // If $pdo is not set, we can add a fallback notice for display.
    $notices[] = [
        'text' => 'Database connection not established. No notices loaded.',
        'age' => 'just now',
        'is_important' => true,
        'link_text' => null
    ];
    $importantNoticeCount = 1;
}

// --- Layout Rendering (Assumed from layouts.php) ---
require_once 'layouts.php';
render_header('CK Dashboard');
render_sidebar($_SESSION['user_role'] ?? 'student', basename(__FILE__));

$topbar_nav = [
    ['label' => 'Dashboard', 'url' => 'dashboard.php'],
    ['label' => 'My Classes', 'url' => 'classes.php'],
    ['label' => 'Notices', 'url' => 'notices.php'],
    ['label' => 'Buy Classes', 'url' => 'buy.php'],
    ['label' => 'Profile', 'url' => 'profile.php'],
];
render_topbar($topbar_nav); 
?>

<style>
/* Base Styling */
body, .main-content-wrapper {
    background-color: #f7f9fc !important;
}
.dashboard-card {
    background-color: white;
    border-radius: 16px;
    box-shadow: 0 4px 10px -1px rgba(0, 0, 0, 0.08), 0 2px 4px -2px rgba(0, 0, 0, 0.04);
}

/* Custom Gradient for AP LearnIX Card (Vibrant Purple/Pink) */
.ap-learnix-gradient {
    /* Using a gradient close to the image's vibrant colors */
    background-image: linear-gradient(to right top, #9d4edd, #c77dff, #e0aaff); 
    color: white; 
    position: relative;
    overflow: hidden;
}

/* Simulate GIF/Animation 1: Pulsating gradient shift (for AP LearnIX card) */
@keyframes gradient-shift {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}
.animated-gradient {
    background-size: 200% 200%;
    animation: gradient-shift 6s ease infinite;
}

/* Simulate GIF/Animation 2: Bar pulse (for AVG WORK TIME bar) */
@keyframes pulse-bar {
    0%, 100% { opacity: 0.9; }
    50% { opacity: 1; box-shadow: 0 0 8px rgba(126, 34, 206, 0.6); }
}
.progress-bar-pulse {
    animation: pulse-bar 3s ease-in-out infinite;
}
/* Ensure Sinhala text displays correctly */
.dashboard-card p, .dashboard-card h2 {
    font-family: 'Noto Sans', sans-serif; /* Fallback to a suitable font */
}
</style>

<div class="p-4 sm:p-6 lg:p-8 bg-gray-50 min-h-screen">

    <!-- Time-based Greeting -->
    <h1 class="text-3xl font-extrabold text-gray-900 mb-6 flex items-center">
        <!-- Sun/Moon Icon -->
        <svg class="w-8 h-8 mr-3 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path></svg>
        <?php echo $greeting; ?> <?php echo $userName; ?> !
    </h1>

    <!-- Info Row: AP LearnIX, Work Time, Slip Entry (4 columns) -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-6 mb-8">
        
        <!-- 1. Student ID -->
        <div class="dashboard-card p-4 flex flex-col justify-center border-l-4 border-yellow-400">
            <h3 class="text-sm font-semibold uppercase text-gray-500 mb-1">STUDENT ID</h3>
            <p class="text-xl font-extrabold text-gray-800"><?php echo $studentId; ?></p>
        </div>

        <!-- 2. AP LearnIX Card (Vibrant Gradient/Animation) -->
        <!-- MODIFICATION: Added onclick to redirect to ai.php -->
        <div class="ap-learnix-gradient animated-gradient p-4 rounded-xl shadow-2xl flex flex-col justify-center transform hover:scale-[1.02] transition duration-300 cursor-pointer" onclick="window.location.href='ai.php'">
            <p class="text-sm font-medium uppercase opacity-80">ASK ME ANYTHING</p>
            <div class="flex justify-between items-center">
                <p class="text-xl font-black mt-1">CkassKeeper</p>
                 <div class="w-6 h-6 rounded-full bg-white bg-opacity-30 flex items-center justify-center">
                    <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17.93c-3.13-.88-5.4-3.86-5.4-7.38 0-4.96 4.04-9 9-9 3.52 0 6.5.69 7.38 3.4L13 19.93zm-1-6.93h-2v2h2v-2zm0-4h-2v2h2v-2zm4 0h-2v2h2v-2zm0 4h-2v2h2v-2zm-4-8h-2v2h2v-2zm0 4h-2v2h2v-2z"></path></svg>
                </div>
            </div>
        </div>
        
        <!-- 3. AVG WORK TIME -->
        <div class="dashboard-card p-4 flex flex-col justify-center border-r-4 border-indigo-400">
            <h3 class="text-sm font-semibold uppercase text-gray-500 mb-1">AVG WORK TIME</h3>
            <p class="text-xl font-extrabold text-indigo-600 mb-2"><?php echo $avgWorkTime; ?> <span class="text-sm font-normal">Hours</span></p>
            <!-- Progress Bar with pulse animation -->
            <div class="relative pt-1">
                <div class="overflow-hidden h-2 text-xs flex rounded bg-gray-200">
                    <div style="width: 60%" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-indigo-500 progress-bar-pulse"></div>
                </div>
            </div>
        </div>

        <!-- 4. SLIP ENTRY Status -->
        <div class="dashboard-card p-4 flex flex-col justify-center border-r-4 border-pink-500">
            <h3 class="text-sm font-semibold uppercase text-gray-500 mb-1">SLIP ENTRY</h3>
            <p class="text-xl font-extrabold text-red-500 mb-2"><?php echo $slipEntry; ?></p>
        </div>
    </div>

    <!-- Main 2x2 Grid (3 columns layout: 2 wide + 1 narrow) -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        
        <!-- Left Column (Paper Marks Analyze & Papers) - 2/3 width -->
        <div class="lg:col-span-2 space-y-8">
            
            <!-- Paper Marks Analyze Card -->
            <div class="dashboard-card p-6 min-h-[350px]">
                <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center justify-between border-b pb-2">
                    Paper Marks Analyze
                    <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0h6"></path></svg>
                </h2>
                <div class="text-center py-10">
                    <!-- Placeholder graphic mimicking the image -->
                    <div class="w-32 h-32 mx-auto mb-4 flex flex-col justify-center items-center">
                        <svg class="w-20 h-20 text-green-500 opacity-60" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m-6-8h6m-7 8l-4 4V7a2 2 0 012-2h10a2 2 0 012 2v10a2 2 0 01-2 2H9z"></path></svg>
                    </div>
                    <p class="text-gray-500 text-lg font-medium">No Papers to Analyze...</p>
                </div>
            </div>

            <!-- Papers Card (Bottom Left) -->
            <div class="dashboard-card p-6 min-h-[250px]">
                <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center justify-between border-b pb-2">
                    Papers
                    <svg class="w-5 h-5 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 001-2 0V7a2 2 0 00-2-2H7a2 2 0 00-2 2v4m14 0V9a2 2 0 00-2-2H7a2 2 0 00-2 2v2m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2h14z"></path></svg>
                </h2>
                <div class="text-center py-10">
                    <p class="text-gray-500 text-lg font-medium">No new papers.</p>
                </div>
            </div>

        </div>
        
        <!-- Right Column (Notices and Work Times) - 1/3 width -->
        <div class="lg:col-span-1 space-y-8">

            <!-- Notices Card -->
            <div class="dashboard-card p-6 min-h-[350px]">
                <h2 class="text-xl font-bold text-gray-900 mb-4 flex items-center justify-between border-b pb-2">
                    Notices
                    <!-- Display dynamic count of important notices -->
                    <div class="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold"><?php echo $importantNoticeCount; ?></div>
                </h2>
                <div class="space-y-4">
                    <?php if (empty($notices)): ?>
                        <div class="text-center py-4">
                            <p class="text-gray-500 italic">No recent notices available.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($notices as $notice): ?>
                            <div class="p-3 rounded-lg <?php echo $notice['is_important'] ? 'bg-red-50 border-l-4 border-red-600' : 'bg-gray-50'; ?> shadow-sm">
                                <p class="text-sm text-gray-800 font-medium"><?php echo htmlspecialchars($notice['text']); ?></p>
                                <div class="flex justify-between items-center mt-1">
                                    <span class="text-xs text-gray-400 italic"><?php echo htmlspecialchars($notice['age']); ?></span>
                                    <?php if (isset($notice['link_text'])): ?>
                                        <a href="#" class="text-xs font-semibold text-blue-600 hover:text-blue-800 transition duration-150"><?php echo htmlspecialchars($notice['link_text']); ?></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            

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

<?php render_main_content_end(); ?>