<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';
require_once __DIR__ . '/../../config/RencanaKerjaPermission.php';

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html");
    exit;
}

// Initialize permission checker
$permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $_SESSION['role']);
$permSummary = $permission->getPermissionSummary();

// AUTO-DETECT column names from database
$detectResult = $conn->query("SHOW COLUMNS FROM rencana_kerja");
$dateColumn = 'tenggat_waktu'; // default
$taskNameColumn = 'judul_tugas'; // default

while ($col = $detectResult->fetch_assoc()) {
    $fieldName = $col['Field'];
    
    // Detect date column
    if (stripos($fieldName, 'deadline') !== false) {
        $dateColumn = $fieldName;
    } elseif (stripos($fieldName, 'tenggat') !== false && $dateColumn === 'tenggat_waktu') {
        $dateColumn = $fieldName;
    }
    
    // Detect task name column
    if (stripos($fieldName, 'task_name') !== false) {
        $taskNameColumn = $fieldName;
    } elseif (stripos($fieldName, 'judul') !== false && $taskNameColumn === 'judul_tugas') {
        $taskNameColumn = $fieldName;
    }
}

// Get filters
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$filterDepartment = isset($_GET['department']) ? $_GET['department'] : '';

// Build date filter
$dateFilter = '';
if ($dateFrom && $dateTo) {
    $dateFilter = " AND rk.$dateColumn BETWEEN '" . $conn->real_escape_string($dateFrom) . "' AND '" . $conn->real_escape_string($dateTo) . "'";
} elseif ($dateFrom) {
    $dateFilter = " AND rk.$dateColumn >= '" . $conn->real_escape_string($dateFrom) . "'";
} elseif ($dateTo) {
    $dateFilter = " AND rk.$dateColumn <= '" . $conn->real_escape_string($dateTo) . "'";
}

// Build department filter
$deptFilter = '';
if ($filterDepartment && $permSummary['can_view_all']) {
    $deptFilter = " AND (rk.department = '" . $conn->real_escape_string($filterDepartment) . "' OR assignee.department = '" . $conn->real_escape_string($filterDepartment) . "')";
}

// Get permission-based filter
$permissionFilter = $permission->getViewFilter();

// Query untuk get tasks dengan permission filter
$query = "
    SELECT 
        rk.*,
        creator.full_name AS creator_name,
        creator.department AS creator_department,
        assignee.full_name AS assignee_name,
        assignee.department AS assignee_department,
        approver.full_name AS approver_name
    FROM rencana_kerja rk
    LEFT JOIN users creator ON rk.created_by = creator.id
    LEFT JOIN users assignee ON rk.assigned_to = assignee.id
    LEFT JOIN users approver ON rk.approval_by = approver.id
    WHERE rk.is_deleted = 0 
    $permissionFilter
    $dateFilter
    $deptFilter
    ORDER BY rk.$dateColumn ASC
";

$result = $conn->query($query);

// Get assignable users based on permission
$users = $permission->getAssignableUsers();

// Get accessible departments
$departments = $permission->getAccessibleDepartments();

$allTasks = [];
if ($result && $result->num_rows > 0) {
    while ($task = $result->fetch_assoc()) {
        $allTasks[] = $task;
    }
}

// Statistics dengan permission filter
$statsQuery = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'progress' THEN 1 ELSE 0 END) as in_progress,
        SUM(CASE WHEN status = 'stuck' THEN 1 ELSE 0 END) as stuck,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending
    FROM rencana_kerja rk
    LEFT JOIN users assignee ON rk.assigned_to = assignee.id
    WHERE rk.is_deleted = 0 
    $permissionFilter
    $dateFilter
    $deptFilter
";
$statsResult = $conn->query($statsQuery);
$stats = $statsResult->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rencana Kerja - <?= ucfirst($permSummary['role']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #7AB2B2;
            --primary-dark: #4D869C;
            --primary-light: #CDE8E5;
            --primary-lighter: #EEF7FF;
            
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-400: #9ca3af;
            --gray-500: #6b7280;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-800: #1f2937;
            --gray-900: #111827;
            
            --blue: #3b82f6;
            --red: #ef4444;
            --yellow: #f59e0b;
            --green: #10b981;
            --purple: #8b5cf6;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--gray-50);
            color: var(--gray-900);
            line-height: 1.5;
        }

        /* Header */
        .header {
            background: white;
            border-bottom: 1px solid var(--gray-200);
            padding: 1rem 2rem;
        }

        .header-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            max-width: 1400px;
            margin: 0 auto;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .header-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }

        .header-title h1 {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--gray-900);
        }

        .header-subtitle {
            font-size: 0.875rem;
            color: var(--gray-500);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.5rem 1rem;
            background: var(--gray-50);
            border-radius: 8px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: var(--primary);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .user-details {
            display: flex;
            flex-direction: column;
        }

        .user-name {
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--gray-900);
        }

        .user-role {
            font-size: 0.75rem;
            color: var(--gray-500);
        }

        /* Stats */
        .stats {
            background: white;
            border-bottom: 1px solid var(--gray-200);
            padding: 1rem 2rem;
        }

        .stats-container {
            max-width: 1400px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
        }

        .stat-card {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem 1rem;
            background: var(--gray-50);
            border-radius: 8px;
            border: 1px solid var(--gray-200);
        }

        .stat-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
        }

        .stat-card.total .stat-icon { background: #dbeafe; color: var(--blue); }
        .stat-card.done .stat-icon { background: #d1fae5; color: var(--green); }
        .stat-card.progress .stat-icon { background: #fef3c7; color: var(--yellow); }
        .stat-card.stuck .stat-icon { background: #fee2e2; color: var(--red); }

        .stat-info {
            flex: 1;
        }

        .stat-label {
            font-size: 0.75rem;
            color: var(--gray-500);
            text-transform: uppercase;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Toolbar */
        .toolbar {
            background: white;
            padding: 0.75rem 2rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .toolbar-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 1rem;
        }

        .toolbar-left {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .toolbar-center {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            flex: 1;
            max-width: 800px;
        }

        .toolbar-right {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .view-tabs {
            display: flex;
            gap: 0;
            background: var(--gray-100);
            border-radius: 6px;
            padding: 2px;
        }

        .view-tab {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0.5rem 0.75rem;
            border: none;
            background: transparent;
            border-radius: 4px;
            font-size: 1rem;
            color: var(--gray-500);
            cursor: pointer;
            transition: all 0.2s;
            min-width: 36px;
        }

        .view-tab:hover {
            color: var(--gray-900);
        }

        .view-tab.active {
            background: white;
            color: var(--primary-dark);
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
        }

        .search-box {
            position: relative;
            flex: 1;
            max-width: 280px;
        }

        .search-box input {
            width: 100%;
            padding: 0.5rem 0.75rem 0.5rem 2.5rem;
            border: 1px solid var(--gray-300);
            border-radius: 6px;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .search-box input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .search-box i {
            position: absolute;
            left: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-400);
        }

        .date-filter {
            display: flex;
            align-items: center;
            gap: 0.35rem;
            background: var(--gray-50);
            padding: 0.25rem;
            border-radius: 6px;
            border: 1px solid var(--gray-200);
        }

        .date-filter input,
        .date-filter select {
            padding: 0.35rem 0.5rem;
            border: none;
            background: transparent;
            border-radius: 4px;
            font-size: 0.8rem;
            color: var(--gray-700);
        }

        .date-filter input {
            width: 115px;
        }

        .date-filter select {
            width: 150px;
        }

        .date-filter input:focus,
        .date-filter select:focus {
            outline: none;
            background: white;
        }

        .date-filter .separator {
            color: var(--gray-400);
            font-size: 0.75rem;
            padding: 0 0.25rem;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border: 1px solid var(--gray-300);
            background: white;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--gray-700);
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn:hover {
            background: var(--gray-50);
            border-color: var(--gray-400);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            border: none;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(122, 178, 178, 0.25);
        }

        /* Content */
        .content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 1.5rem 2rem;
        }

        .view-container {
            display: none;
        }

        .view-container.active {
            display: block;
        }

        /* Table */
        .table-wrapper {
            background: white;
            border-radius: 8px;
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table thead {
            background: var(--gray-50);
        }

        .table th {
            padding: 0.75rem 1rem;
            text-align: left;
            font-size: 0.75rem;
            font-weight: 600;
            color: var(--gray-500);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid var(--gray-200);
        }

        .table td {
            padding: 1rem;
            font-size: 0.875rem;
            border-bottom: 1px solid var(--gray-200);
        }

        .table tbody tr:last-child td {
            border-bottom: none;
        }

        .table tbody tr:hover {
            background: var(--gray-50);
        }

        .task-name {
            font-weight: 500;
            color: var(--gray-900);
        }

        .task-department {
            font-size: 0.75rem;
            color: var(--gray-500);
            margin-top: 0.25rem;
        }

        .user-cell {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .avatar {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
            font-weight: 600;
            color: white;
            flex-shrink: 0;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge.status-pending { background: #f3f4f6; color: #6b7280; }
        .badge.status-progress { background: #fef3c7; color: #d97706; }
        .badge.status-stuck { background: #fee2e2; color: #dc2626; }
        .badge.status-done { background: #d1fae5; color: #059669; }

        .badge.priority-penting { background: #fee2e2; color: #dc2626; }
        .badge.priority-penting-tidak-genting { background: #fef3c7; color: #d97706; }
        .badge.priority-penting-genting { background: #dc2626; color: white; }

        /* Board */
        .board {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
        }

        .board-column {
            background: var(--gray-100);
            border-radius: 8px;
            padding: 1rem;
        }

        .board-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 1rem;
        }

        .board-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
            font-weight: 600;
            color: var(--gray-700);
        }

        .board-count {
            background: white;
            padding: 0.125rem 0.5rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .board-cards {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }

        .board-card {
            background: white;
            border-radius: 6px;
            padding: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid var(--gray-200);
        }

        .board-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transform: translateY(-1px);
        }

        .board-card-title {
            font-size: 0.875rem;
            font-weight: 500;
            margin-bottom: 0.5rem;
            color: var(--gray-900);
        }

        .board-card-meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 0.75rem;
            color: var(--gray-500);
            padding-top: 0.5rem;
            border-top: 1px solid var(--gray-200);
        }

        /* Calendar */
        .calendar {
            background: white;
            border-radius: 8px;
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        .calendar-header {
            padding: 1rem;
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .calendar-nav {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .calendar-title {
            font-size: 1rem;
            font-weight: 600;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
        }

        .calendar-day-header {
            padding: 0.75rem;
            text-align: center;
            font-size: 0.75rem;
            font-weight: 600;
            color: var(--gray-500);
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
        }

        .calendar-day {
            min-height: 100px;
            padding: 0.5rem;
            border: 1px solid var(--gray-200);
            border-top: none;
            border-left: none;
        }

        .calendar-day:nth-child(7n+8) {
            border-left: 1px solid var(--gray-200);
        }

        .calendar-day.other-month {
            background: var(--gray-50);
            opacity: 0.5;
        }

        .calendar-day.today {
            background: var(--primary-lighter);
        }

        .calendar-day-number {
            font-size: 0.875rem;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }

        .calendar-task {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            margin-bottom: 0.25rem;
            border-radius: 3px;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            font-size: 1.125rem;
            font-weight: 600;
        }

        .modal-close {
            width: 32px;
            height: 32px;
            border: none;
            background: none;
            border-radius: 4px;
            cursor: pointer;
            color: var(--gray-400);
        }

        .modal-close:hover {
            background: var(--gray-100);
            color: var(--gray-600);
        }

        .modal-body {
            padding: 1.5rem;
        }

        .form-group {
            margin-bottom: 1.25rem;
        }

        .form-label {
            display: block;
            font-size: 0.875rem;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
        }

        .form-input,
        .form-select,
        .form-textarea {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid var(--gray-300);
            border-radius: 6px;
            font-size: 0.875rem;
            font-family: inherit;
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .modal-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: flex-end;
            gap: 0.5rem;
        }

        /* Toast */
        .toast {
            position: fixed;
            bottom: 1.5rem;
            right: 1.5rem;
            background: var(--gray-900);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            display: none;
            align-items: center;
            gap: 0.75rem;
            z-index: 2000;
        }

        .toast.active {
            display: flex;
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from {
                transform: translateY(100px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        /* Empty State */
        .empty-state {
            padding: 4rem 2rem;
            text-align: center;
        }

        .empty-state i {
            font-size: 3rem;
            color: var(--gray-300);
            margin-bottom: 1rem;
        }

        .empty-state h3 {
            font-size: 1.125rem;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: var(--gray-500);
        }

        /* Responsive */
        @media (max-width: 1024px) {
            .board {
                grid-template-columns: repeat(2, 1fr);
            }

            .toolbar-content {
                flex-wrap: wrap;
            }

            .toolbar-center {
                order: 2;
                width: 100%;
                max-width: 100%;
            }

            .search-box {
                max-width: 100%;
            }

            .date-filter {
                width: auto;
            }
        }

        @media (max-width: 768px) {
            .header,
            .stats,
            .toolbar {
                padding-left: 1rem;
                padding-right: 1rem;
            }

            .content {
                padding: 1rem;
            }

            .stats-container {
                grid-template-columns: repeat(2, 1fr);
            }

            .board {
                grid-template-columns: 1fr;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .toolbar-content {
                flex-direction: column;
                align-items: stretch;
                gap: 0.75rem;
            }

            .toolbar-left,
            .toolbar-right {
                justify-content: center;
            }

            .toolbar-center {
                flex-direction: column;
                gap: 0.75rem;
            }

            .search-box,
            .date-filter {
                width: 100%;
            }

            .date-filter input,
            .date-filter select {
                width: 100%;
            }
        }

        .help-text {
            font-size: 0.75rem;
            color: var(--gray-500);
            margin-top: 0.25rem;
        }

        .action-buttons {
            display: flex;
            gap: 0.25rem;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <div class="header-content">
            <div class="header-left">
                <div class="header-icon">
                    <i class="fas fa-tasks"></i>
                </div>
                <div class="header-title">
                    <h1>Rencana Kerja</h1>
                    <div class="header-subtitle">
                        <?php if ($permSummary['can_view_all']): ?>
                            Kelola semua tugas organisasi
                        <?php elseif ($permSummary['role'] === 'dept_head'): ?>
                            Kelola tugas <?= htmlspecialchars($permSummary['department']) ?>
                        <?php else: ?>
                            Tugas Saya
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <?= getInitials($permSummary['user_name']) ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?= htmlspecialchars($permSummary['user_name']) ?></div>
                    <div class="user-role">
                        <?= ucfirst($permSummary['role']) ?>
                        <?php if ($permSummary['department']): ?>
                            • <?= htmlspecialchars($permSummary['department']) ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics -->
    <div class="stats">
        <div class="stats-container">
            <div class="stat-card total">
                <div class="stat-icon">
                    <i class="fas fa-clipboard-list"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">Total</div>
                    <div class="stat-value"><?= $stats['total'] ?? 0 ?></div>
                </div>
            </div>
            <div class="stat-card done">
                <div class="stat-icon">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">Selesai</div>
                    <div class="stat-value"><?= $stats['completed'] ?? 0 ?></div>
                </div>
            </div>
            <div class="stat-card progress">
                <div class="stat-icon">
                    <i class="fas fa-spinner"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">Progress</div>
                    <div class="stat-value"><?= $stats['in_progress'] ?? 0 ?></div>
                </div>
            </div>
            <div class="stat-card stuck">
                <div class="stat-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">Terhambat</div>
                    <div class="stat-value"><?= $stats['stuck'] ?? 0 ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toolbar -->
    <div class="toolbar">
        <div class="toolbar-content">
            <!-- Left: View Tabs -->
            <div class="toolbar-left">
                <div class="view-tabs">
                    <button class="view-tab active" onclick="switchView(this, 'table')" title="Tabel">
                        <i class="fas fa-list"></i>
                    </button>
                    <button class="view-tab" onclick="switchView(this, 'board')" title="Board">
                        <i class="fas fa-columns"></i>
                    </button>
                    <button class="view-tab" onclick="switchView(this, 'calendar')" title="Kalender">
                        <i class="fas fa-calendar"></i>
                    </button>
                </div>
            </div>

            <!-- Center: Search & Filter -->
            <div class="toolbar-center">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Cari tugas..." id="searchInput" onkeyup="filterTasks()">
                </div>

                <div class="date-filter">
                    <?php if ($permSummary['can_view_all'] && count($departments) > 1): ?>
                    <select id="departmentFilter" onchange="applyFilters()">
                        <option value="">Semua Dept</option>
                        <?php foreach ($departments as $dept): ?>
                            <option value="<?= htmlspecialchars($dept) ?>" <?= $filterDepartment === $dept ? 'selected' : '' ?>>
                                <?= htmlspecialchars($dept) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="separator">•</span>
                    <?php endif; ?>
                    
                    <input type="date" id="dateFrom" value="<?= $dateFrom ?>" onchange="applyFilters()" placeholder="Dari">
                    <span class="separator">—</span>
                    <input type="date" id="dateTo" value="<?= $dateTo ?>" onchange="applyFilters()" placeholder="Sampai">
                    <?php if ($dateFrom || $dateTo || $filterDepartment): ?>
                    <button class="btn" onclick="clearFilters()" title="Hapus Filter" style="padding: 0.35rem 0.5rem; font-size: 0.75rem; border: none; background: transparent; color: var(--gray-500);">
                        <i class="fas fa-times"></i>
                    </button>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Right: Action Button -->
            <div class="toolbar-right">
                <?php if ($permSummary['can_create']): ?>
                <button class="btn btn-primary" onclick="openAddModal()">
                    <i class="fas fa-plus"></i>
                    Tambah Tugas
                </button>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Content -->
    <div class="content">
        <!-- Table View -->
        <div class="view-container active" id="tableView">
            <?php if (!empty($allTasks)): ?>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Nama Tugas</th>
                            <th>Ditugaskan</th>
                            <th>Tenggat</th>
                            <th>Prioritas</th>
                            <th>Progress</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($allTasks as $task): ?>
                        <tr data-task-id="<?= $task['id'] ?>" 
                            data-status="<?= $task['status'] ?>" 
                            data-title="<?= strtolower($task[$taskNameColumn] ?? '') ?>">
                            <td>
                                <div class="task-name"><?= htmlspecialchars($task[$taskNameColumn] ?? '') ?></div>
                                <?php if ($permSummary['can_view_all'] && $task['assignee_department']): ?>
                                <div class="task-department">
                                    <i class="fas fa-building" style="font-size: 0.65rem;"></i>
                                    <?= htmlspecialchars($task['assignee_department']) ?>
                                </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="user-cell">
                                    <div class="avatar" style="background: <?= getAvatarColor($task['assignee_name'] ?? '') ?>;">
                                        <?= getInitials($task['assignee_name'] ?? 'N/A') ?>
                                    </div>
                                    <span><?= htmlspecialchars($task['assignee_name'] ?? 'Unassigned') ?></span>
                                </div>
                            </td>
                            <td><?= date('d M Y', strtotime($task[$dateColumn])) ?></td>
                            <td>
                                <span class="badge priority-<?= str_replace('_', '-', $task['prioritas'] ?? '') ?>">
                                    <?= getPriorityLabel($task['prioritas'] ?? '') ?>
                                </span>
                            </td>
                            <td>
                                <span style="font-weight: 600; color: var(--primary);">
                                    <?= $task['progress_percentage'] ?? 0 ?>%
                                </span>
                            </td>
                            <td>
                                <span class="badge status-<?= $task['status'] ?>">
                                    <?= getStatusLabel($task['status']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <?php if ($permSummary['can_update']): ?>
                                    <button class="btn" onclick="editTask(<?= $task['id'] ?>)" style="padding: 0.25rem 0.5rem;" title="Edit">
                                        <i class="fas fa-pencil-alt"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php if ($permission->canDelete($task['id'])): ?>
                                    <button class="btn" onclick="deleteTask(<?= $task['id'] ?>)" style="padding: 0.25rem 0.5rem; color: var(--red);" title="Hapus">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-clipboard-list"></i>
                <h3>Belum Ada Tugas</h3>
                <p>
                    <?php if ($permSummary['can_create']): ?>
                        Klik "Tambah Tugas" untuk membuat tugas baru
                    <?php else: ?>
                        Belum ada tugas yang ditugaskan kepada Anda
                    <?php endif; ?>
                </p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Board View -->
        <div class="view-container" id="boardView">
            <div class="board">
                <?php 
                $statuses = [
                    'pending' => ['icon' => 'clock', 'label' => 'Pending'],
                    'progress' => ['icon' => 'spinner', 'label' => 'Progress'],
                    'stuck' => ['icon' => 'exclamation-triangle', 'label' => 'Terhambat'],
                    'done' => ['icon' => 'check-circle', 'label' => 'Selesai']
                ];
                
                foreach ($statuses as $statusKey => $statusInfo):
                    $statusTasks = array_filter($allTasks, fn($t) => $t['status'] === $statusKey);
                ?>
                <div class="board-column">
                    <div class="board-header">
                        <div class="board-title">
                            <i class="fas fa-<?= $statusInfo['icon'] ?>"></i>
                            <?= $statusInfo['label'] ?>
                        </div>
                        <div class="board-count"><?= count($statusTasks) ?></div>
                    </div>
                    <div class="board-cards">
                        <?php foreach ($statusTasks as $task): ?>
                        <div class="board-card" onclick="editTask(<?= $task['id'] ?>)">
                            <div class="board-card-title"><?= htmlspecialchars($task[$taskNameColumn] ?? '') ?></div>
                            <?php if ($permSummary['can_view_all'] && $task['assignee_department']): ?>
                            <div style="font-size: 0.7rem; color: var(--gray-500); margin-bottom: 0.5rem;">
                                <i class="fas fa-building" style="font-size: 0.6rem;"></i>
                                <?= htmlspecialchars($task['assignee_department']) ?>
                            </div>
                            <?php endif; ?>
                            <div style="margin: 0.5rem 0;">
                                <span class="badge priority-<?= str_replace('_', '-', $task['prioritas'] ?? '') ?>">
                                    <?= getPriorityLabel($task['prioritas'] ?? '') ?>
                                </span>
                            </div>
                            <div class="board-card-meta">
                                <div class="user-cell">
                                    <div class="avatar" style="background: <?= getAvatarColor($task['assignee_name'] ?? '') ?>; width: 20px; height: 20px; font-size: 0.65rem;">
                                        <?= getInitials($task['assignee_name'] ?? 'N/A') ?>
                                    </div>
                                    <span><?= htmlspecialchars(explode(' ', $task['assignee_name'] ?? 'N/A')[0]) ?></span>
                                </div>
                                <span><?= date('M d', strtotime($task[$dateColumn])) ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Calendar View -->
        <div class="view-container" id="calendarView">
            <div class="calendar">
                <div class="calendar-header">
                    <div class="calendar-nav">
                        <button class="btn" onclick="previousMonth()">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <div class="calendar-title" id="calendarTitle">February 2026</div>
                        <button class="btn" onclick="nextMonth()">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                    <button class="btn" onclick="goToToday()">
                        <i class="fas fa-calendar-day"></i>
                        Hari Ini
                    </button>
                </div>
                <div class="calendar-grid" id="calendarGrid"></div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal" id="taskModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Tugas Baru</h2>
                <button class="modal-close" onclick="closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="taskForm" onsubmit="submitTask(event)">
                <div class="modal-body">
                    <input type="hidden" id="taskId" name="task_id">

                    <div class="form-group">
                        <label class="form-label">Nama Tugas *</label>
                        <input type="text" class="form-input" id="judulTugas" name="judul_tugas" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Deskripsi</label>
                        <textarea class="form-textarea" id="deskripsi" name="deskripsi"></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Prioritas *</label>
                            <select class="form-select" id="prioritas" name="prioritas" required>
                                <option value="">Pilih Prioritas</option>
                                <option value="penting">Penting</option>
                                <option value="penting_tidak_genting">Penting Tidak Genting</option>
                                <option value="penting_genting">Penting & Genting</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Status *</label>
                            <select class="form-select" id="status" name="status" required>
                                <option value="pending">Pending</option>
                                <option value="progress">Progress</option>
                                <option value="stuck">Terhambat</option>
                                <option value="done">Selesai</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Ditugaskan Kepada *</label>
                            <select class="form-select" id="assignedTo" name="assigned_to" required>
                                <option value="">Pilih User</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?= $user['id'] ?>" data-department="<?= $user['department'] ?>">
                                        <?= htmlspecialchars($user['full_name']) ?> 
                                        (<?= $user['role'] ?>)
                                        <?php if ($user['department']): ?>
                                            - <?= $user['department'] ?>
                                        <?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($permSummary['role'] === 'staff'): ?>
                            <div class="help-text">
                                <i class="fas fa-info-circle"></i>
                                Anda hanya dapat menugaskan ke diri sendiri
                            </div>
                            <?php elseif ($permSummary['role'] === 'dept_head'): ?>
                            <div class="help-text">
                                <i class="fas fa-info-circle"></i>
                                Anda hanya dapat menugaskan ke anggota departemen Anda
                            </div>
                            <?php endif; ?>
                        </div>

                        <div class="form-group">
                            <label class="form-label">Tenggat Waktu *</label>
                            <input type="date" class="form-input" id="tenggatWaktu" name="tenggat_waktu" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Progress (%)</label>
                        <input type="number" class="form-input" id="progressPercentage" name="progress_percentage" min="0" max="100" value="0">
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn" onclick="closeModal()">Batal</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Toast -->
    <div class="toast" id="toast">
        <i class="fas fa-check-circle" id="toastIcon"></i>
        <span id="toastMessage">Success!</span>
    </div>

    <script>
        const allTasksData = <?= json_encode($allTasks) ?>;
        const dateColumn = '<?= $dateColumn ?>';
        const taskNameColumn = '<?= $taskNameColumn ?>';
        const userPermissions = <?= json_encode($permSummary) ?>;
        let currentMonth = new Date(2026, 1);

        function applyFilters() {
            const dateFrom = document.getElementById('dateFrom').value;
            const dateTo = document.getElementById('dateTo').value;
            const department = document.getElementById('departmentFilter')?.value || '';
            
            let url = window.location.pathname;
            const params = new URLSearchParams();
            
            if (dateFrom) params.append('date_from', dateFrom);
            if (dateTo) params.append('date_to', dateTo);
            if (department) params.append('department', department);
            
            if (params.toString()) url += '?' + params.toString();
            window.location.href = url;
        }

        function clearFilters() {
            window.location.href = window.location.pathname;
        }

        function switchView(btn, view) {
            document.querySelectorAll('.view-tab').forEach(tab => tab.classList.remove('active'));
            btn.classList.add('active');
            
            document.querySelectorAll('.view-container').forEach(container => {
                container.classList.remove('active');
            });
            
            document.getElementById(view + 'View').classList.add('active');
            
            if (view === 'calendar') renderCalendar();
        }

        function filterTasks() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const rows = document.querySelectorAll('.table tbody tr');
            
            rows.forEach(row => {
                const title = row.getAttribute('data-title') || '';
                row.style.display = title.includes(searchTerm) ? '' : 'none';
            });
        }

        function renderCalendar() {
            const grid = document.getElementById('calendarGrid');
            grid.innerHTML = '';
            
            const days = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'];
            days.forEach(day => {
                const header = document.createElement('div');
                header.className = 'calendar-day-header';
                header.textContent = day;
                grid.appendChild(header);
            });
            
            const firstDay = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), 1);
            const lastDay = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0);
            const daysInMonth = lastDay.getDate();
            const startingDayOfWeek = firstDay.getDay();
            
            const prevMonthLastDay = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), 0).getDate();
            for (let i = startingDayOfWeek - 1; i >= 0; i--) {
                const dayCell = document.createElement('div');
                dayCell.className = 'calendar-day other-month';
                dayCell.innerHTML = `<div class="calendar-day-number">${prevMonthLastDay - i}</div>`;
                grid.appendChild(dayCell);
            }
            
            const today = new Date();
            for (let day = 1; day <= daysInMonth; day++) {
                const dayCell = document.createElement('div');
                const currentDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), day);
                const isToday = currentDate.toDateString() === today.toDateString();
                
                dayCell.className = 'calendar-day' + (isToday ? ' today' : '');
                dayCell.innerHTML = `<div class="calendar-day-number">${day}</div>`;
                
                const dayTasks = allTasksData.filter(task => {
                    if (!task[dateColumn]) return false;
                    const taskDate = new Date(task[dateColumn]);
                    return taskDate.getDate() === day && 
                           taskDate.getMonth() === currentMonth.getMonth() && 
                           taskDate.getFullYear() === currentMonth.getFullYear();
                });
                
                dayTasks.forEach(task => {
                    const taskEl = document.createElement('div');
                    taskEl.className = `calendar-task badge status-${task.status}`;
                    taskEl.textContent = task[taskNameColumn];
                    taskEl.onclick = (e) => {
                        e.stopPropagation();
                        editTask(task.id);
                    };
                    dayCell.appendChild(taskEl);
                });
                
                grid.appendChild(dayCell);
            }
            
            const remainingCells = 42 - (startingDayOfWeek + daysInMonth);
            for (let day = 1; day <= remainingCells; day++) {
                const dayCell = document.createElement('div');
                dayCell.className = 'calendar-day other-month';
                dayCell.innerHTML = `<div class="calendar-day-number">${day}</div>`;
                grid.appendChild(dayCell);
            }
            
            const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 
                          'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
            document.getElementById('calendarTitle').textContent = 
                `${months[currentMonth.getMonth()]} ${currentMonth.getFullYear()}`;
        }

        function previousMonth() {
            currentMonth.setMonth(currentMonth.getMonth() - 1);
            renderCalendar();
        }

        function nextMonth() {
            currentMonth.setMonth(currentMonth.getMonth() + 1);
            renderCalendar();
        }

        function goToToday() {
            currentMonth = new Date();
            renderCalendar();
        }

        function openAddModal() {
            document.getElementById('modalTitle').textContent = 'Tugas Baru';
            document.getElementById('taskForm').reset();
            document.getElementById('taskId').value = '';
            
            // Auto-select user for staff
            if (userPermissions.role === 'staff') {
                document.getElementById('assignedTo').value = userPermissions.user_id;
            }
            
            document.getElementById('taskModal').classList.add('active');
        }

        function closeModal() {
            document.getElementById('taskModal').classList.remove('active');
        }

        function editTask(taskId) {
            fetch(`ajax/get_task.php?id=${taskId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('modalTitle').textContent = 'Edit Tugas';
                        document.getElementById('taskId').value = data.task.id;
                        document.getElementById('judulTugas').value = data.task.judul_tugas || data.task.task_name;
                        document.getElementById('deskripsi').value = data.task.deskripsi || data.task.description || '';
                        document.getElementById('prioritas').value = data.task.prioritas || data.task.priority;
                        document.getElementById('status').value = data.task.status;
                        document.getElementById('assignedTo').value = data.task.assigned_to;
                        document.getElementById('tenggatWaktu').value = data.task.tenggat_waktu || data.task.deadline;
                        document.getElementById('progressPercentage').value = data.task.progress_percentage;
                        document.getElementById('taskModal').classList.add('active');
                    } else {
                        showToast(data.message || 'Error memuat data tugas', 'error');
                    }
                })
                .catch(error => {
                    showToast('Error: ' + error.message, 'error');
                });
        }

        function deleteTask(taskId) {
            if (!confirm('Apakah Anda yakin ingin menghapus tugas ini?')) return;
            
            fetch('ajax/delete_task.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ task_id: taskId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(data.message || 'Gagal menghapus tugas', 'error');
                }
            })
            .catch(error => {
                showToast('Error: ' + error.message, 'error');
            });
        }

        function submitTask(event) {
            event.preventDefault();
            
            const formData = new FormData(document.getElementById('taskForm'));
            const taskId = document.getElementById('taskId').value;
            const url = taskId ? 'ajax/update_task.php' : 'ajax/create_task.php';
            
            fetch(url, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    closeModal();
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast(data.message || 'Terjadi kesalahan', 'error');
                }
            })
            .catch(error => {
                showToast('Error: ' + error.message, 'error');
            });
        }

        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const toastMessage = document.getElementById('toastMessage');
            const toastIcon = document.getElementById('toastIcon');
            
            toastMessage.textContent = message;
            toast.className = `toast active`;
            
            toastIcon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
            
            setTimeout(() => {
                toast.classList.remove('active');
            }, 3000);
        }

        document.getElementById('taskModal').addEventListener('click', function(e) {
            if (e.target === this) closeModal();
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') closeModal();
        });
    </script>
</body>
</html>

<?php
function getPriorityLabel($priority) {
    $labels = [
        'penting' => 'Penting',
        'penting_tidak_genting' => 'Tidak Genting',
        'penting_genting' => 'Genting!'
    ];
    return $labels[$priority] ?? ucfirst($priority);
}

function getStatusLabel($status) {
    $labels = [
        'pending' => 'Pending',
        'progress' => 'Progress',
        'stuck' => 'Terhambat',
        'done' => 'Selesai'
    ];
    return $labels[$status] ?? ucfirst($status);
}

function getAvatarColor($name) {
    $colors = ['#667eea', '#764ba2', '#f093fb', '#4facfe', '#43e97b', '#fa709a'];
    $index = strlen($name ?? '') % count($colors);
    return $colors[$index];
}

function getInitials($name) {
    if (empty($name) || $name === 'N/A') return 'N/A';
    $words = explode(' ', $name);
    $initials = '';
    foreach ($words as $word) {
        if (!empty($word)) {
            $initials .= strtoupper(substr($word, 0, 1));
        }
        if (strlen($initials) >= 2) break;
    }
    return $initials ?: 'N/A';
}
?>