<?php
// File: member/member_dashboard.php

// 1. Matikan Cache
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

include 'auth_check.php';
require_role(['member']); 
require_once('../db.php'); 

$member_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Member'; 
$tasks = [];
$counts = ['pending' => 0, 'in_progress' => 0, 'completed' => 0]; 

// --- 1. HITUNG STATISTIK ---
$sql_count_stats = "
    SELECT 
        SUM(CASE WHEN (status IS NULL OR status = '' OR status = 'pending') THEN 1 ELSE 0 END) as count_pending,
        SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as count_in_progress,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as count_completed
    FROM tasks 
    WHERE assigned_to = ?
";
$stmt = $conn->prepare($sql_count_stats);
$stmt->bind_param("i", $member_id);
$stmt->execute();
$res = $stmt->get_result();
if ($row = $res->fetch_assoc()) { $counts = $row; }
$stmt->close();

// --- 2. CONFIG FILTER & PAGINATION ---
$filter_status = isset($_GET['filter']) ? strtolower($_GET['filter']) : '';
$limit = 5; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// --- 3. HITUNG TOTAL DATA ---
$sql_total = "SELECT COUNT(*) as total FROM tasks WHERE assigned_to = ?";
if ($filter_status === 'pending') {
    $sql_total .= " AND (status = 'pending' OR status IS NULL OR status = '')";
} elseif ($filter_status !== '') {
    $sql_total .= " AND status = '$filter_status'";
}

$stmt = $conn->prepare($sql_total);
$stmt->bind_param("i", $member_id);
$stmt->execute();
$res_total = $stmt->get_result();
$row_total = $res_total->fetch_assoc();
$total_records = $row_total['total'];
$total_pages = ceil($total_records / $limit);
$stmt->close();

// --- 4. AMBIL DATA TUGAS ---
$sql = "
    SELECT 
        id, title, due_date, status, 
        (SELECT project_name FROM projects WHERE projects.project_id = tasks.project_id) as p_name
    FROM tasks 
    WHERE assigned_to = ? 
";

if ($filter_status === 'pending') {
    $sql .= " AND (status = 'pending' OR status IS NULL OR status = '')";
} elseif ($filter_status !== '') {
    $sql .= " AND status = '$filter_status'";
}

$sql .= " ORDER BY 
          CASE WHEN status = 'completed' THEN 2 ELSE 1 END ASC, 
          id DESC 
          LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("iii", $member_id, $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) { $tasks[] = $row; }
$stmt->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <title>Member - Tugas Saya</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* GLOBAL STYLE */
        :root { --bg: #f3f4f6; --text: #1f2937; }
        body { background-color: var(--bg); margin: 0; padding: 0; color: var(--text); font-family: 'Poppins', sans-serif; }
        
        /* STICKY TOP SECTION */
        .sticky-top-section {
            position: sticky; top: 0; z-index: 1000; 
            background-color: #dcfce7; padding: 20px 30px; 
            box-shadow: 0 4px 20px rgba(0,0,0,0.08); border-bottom: 1px solid #bbf7d0;
        }

        .header-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .header-left { display: flex; align-items: center; gap: 15px; }
        
        /* --- LOGO STYLE (DESKTOP DEFAULT) --- */
        .logo-text { 
            font-size: 22px; font-weight: 800; color: #166534; text-transform: uppercase; 
            border-right: 2px solid #86efac; padding-right: 15px; display: block; 
        }
        .logo-desktop { display: inline; } /* Tampil di Desktop */
        .logo-mobile { display: none; }    /* Sembunyi di Desktop */

        .header-title h1 { font-size: 20px; font-weight: 700; color: #111; margin: 0; }
        .header-title p { margin: 0; color: #4a5568; font-size: 12px; }
        
        .header-actions { display: flex; gap: 8px; }
        .btn-refresh, .btn-logout { padding: 8px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; }
        .btn-refresh { background: white; color: #374151; border: 1px solid #d1d5db; }
        .btn-logout { background: #ef4444; color: white; border: 1px solid #ef4444; }

        /* STATS CARDS */
        .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; }
        .stat-card { background: white; padding: 15px; border-radius: 10px; display: flex; flex-direction: column; align-items: center; text-align: center; text-decoration: none; color: inherit; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
        .stat-card.active { transform: scale(1.02); border: 2px solid #10b981; }
        .c-pending { border-top: 4px solid #f59e0b; } .c-progress { border-top: 4px solid #3b82f6; } .c-completed { border-top: 4px solid #10b981; }
        .stat-info h2 { font-size: 24px; margin: 0; font-weight: 700; }
        .stat-info p { margin: 0; font-size: 10px; text-transform: uppercase; font-weight: 600; color: #6b7280; }
        .stat-icon { font-size: 20px; margin-top: 2px; }

        /* CONTENT */
        .main-content { padding: 20px; padding-bottom: 80px; }
        .table-section-title { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; font-weight: 700; font-size: 16px; }
        .reset-link { font-size: 12px; color: #ef4444; text-decoration: none; }

        /* TABLE DESKTOP */
        .table-wrap { background: white; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.02); border: 1px solid #e5e7eb; overflow: hidden; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #f9fafb; padding: 15px; text-align: left; font-size: 13px; }
        td { padding: 15px; border-bottom: 1px solid #e5e7eb; font-size: 14px; }
        .badge { padding: 5px 10px; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; display: inline-block; }
        .bg-pending { background-color: #fffbeb; color: #b45309; } .bg-in_progress { background-color: #eff6ff; color: #1d4ed8; } .bg-completed { background-color: #ecfdf5; color: #047857; }
        .btn-upd { background: #1f2937; color: white; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 12px; font-weight: 600; display: inline-block; }
        .pagination { padding: 20px; text-align: center; }
        .page-link { display: inline-block; padding: 8px 12px; margin: 0 3px; border: 1px solid #e0e0e0; color: #555; text-decoration: none; border-radius: 6px; font-size: 12px; }
        .page-link.active { background-color: #111; color: white; }

        /* --- MOBILE RESPONSIVE (HANYA DI HP) --- */
        @media screen and (max-width: 768px) {
            .sticky-top-section { padding: 15px; }
            
            /* 1. LOGO SWITCH (TM) */
            .logo-desktop { display: none; } 
            .logo-mobile { display: inline; }
            .logo-text { font-size: 20px; padding-right: 10px; }
            
            .header-title h1 { font-size: 16px; }
            .header-title p { font-size: 11px; }
            
            /* 2. TABLE TO CARD VIEW */
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            
            tr { 
                margin-bottom: 15px; background: white; border-radius: 10px; 
                box-shadow: 0 2px 5px rgba(0,0,0,0.05); border: 1px solid #e5e7eb; padding: 15px; 
            }
            
            td { 
                border: none; position: relative; padding: 5px 0; padding-left: 40%; 
                display: flex; justify-content: space-between; align-items: center; text-align: right;
            }
            
            td:before { 
                content: attr(data-label); position: absolute; left: 0; width: 35%; 
                font-weight: 700; font-size: 11px; color: #6b7280; text-align: left; 
            }
            
            /* Khusus Judul */
            td[data-label="JUDUL"] { font-size: 16px; font-weight: 700; color: #111; display: block; text-align: left; padding-left: 0; margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px dashed #eee; }
            td[data-label="JUDUL"]:before { display: none; }

            /* Khusus Tombol Update (Full Width & Presisi) */
            td[data-label="AKSI"] { 
                margin-top: 15px; 
                padding-top: 0;
                padding-left: 0; 
                display: block; 
                text-align: center;
            }
            td[data-label="AKSI"]:before { display: none; }
            
            .btn-upd { 
                width: 100%; 
                box-sizing: border-box; 
                text-align: center; 
                padding: 12px; 
                border-radius: 8px;
                display: block;
            }
        }
    </style>
</head>
<body>

    <div class="sticky-top-section">
        <div class="header-container">
            <div class="header-left">
                <div class="logo-text">
                    <span class="logo-desktop">TASK MANAGEMENT</span>
                    <span class="logo-mobile">TM</span>
                </div>
                <div class="header-title">
                    <h1>Hi, <?php echo htmlspecialchars($username); ?></h1>
                    <p>Dashboard</p>
                </div>
            </div>
            <div class="header-actions">
                <a href="member_dashboard.php" class="btn-refresh">🔄</a>
                <a href="../logout.php" class="btn-logout">🚪</a>
            </div>
        </div>

        <div class="stats-grid">
            <a href="member_dashboard.php?filter=pending" class="stat-card c-pending <?php echo ($filter_status == 'pending') ? 'active' : ''; ?>">
                <div class="stat-info"><h2><?php echo $counts['count_pending'] ?? 0; ?></h2><p>Pending</p></div>
            </a>
            <a href="member_dashboard.php?filter=in_progress" class="stat-card c-progress <?php echo ($filter_status == 'in_progress') ? 'active' : ''; ?>">
                <div class="stat-info"><h2><?php echo $counts['count_in_progress'] ?? 0; ?></h2><p>Process</p></div>
            </a>
            <a href="member_dashboard.php?filter=completed" class="stat-card c-completed <?php echo ($filter_status == 'completed') ? 'active' : ''; ?>">
                <div class="stat-info"><h2><?php echo $counts['count_completed'] ?? 0; ?></h2><p>Done</p></div>
            </a>
        </div>
    </div> 

    <div class="main-content">
        <div class="table-section-title">
            <span>📋 Tugas Saya</span>
            <?php if ($filter_status): ?><a href="member_dashboard.php" class="reset-link">❌ Reset</a><?php endif; ?>
        </div>

        <div class="table-wrap">
            <?php if (empty($tasks)): ?>
                <div style="padding:60px; text-align:center; color:#9ca3af;"><p style="font-size:16px;">Tidak ada tugas.</p></div>
            <?php else: ?>
                <table>
                    <thead><tr><th>Judul</th><th>Project</th><th>Deadline</th><th>Status</th><th>Aksi</th></tr></thead>
                    <tbody>
                        <?php foreach ($tasks as $t): 
                            $clean = strtolower(trim($t['status'] ?? '')); 
                            if (empty($clean)) $clean = 'pending'; 
                        ?>
                        <tr>
                            <td data-label="JUDUL"><?php echo htmlspecialchars($t['title']); ?></td>
                            <td data-label="PROJECT"><span style="background:#f3f4f6; padding:2px 6px; border-radius:4px; font-size:11px; border:1px solid #e5e7eb;"><?php echo htmlspecialchars($t['p_name']); ?></span></td>
                            <td data-label="DEADLINE" style="color:#ef4444; font-weight:600;"><?php echo $t['due_date']; ?></td>
                            <td data-label="STATUS"><span class="badge bg-<?php echo $clean; ?>"><?php echo strtoupper(str_replace('_',' ',$clean)); ?></span></td>
                            <td data-label="AKSI"><a href="member_view_task.php?task_id=<?php echo $t['id']; ?>" class="btn-upd">Update Status</a></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="pagination">
                    <?php for ($i=1; $i<=$total_pages; $i++): ?>
                        <a href="?page=<?php echo $i; ?><?php echo $filter_status ? '&filter='.$filter_status : ''; ?>" class="page-link <?php echo ($i==$page)?'active':''; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

</body>
</html>