<?php
// Enable error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

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

// ✅ FIXED: Get role from session (matches login_proc.php format: lowercase)
$userRole = isset($_SESSION['role']) ? strtolower(trim($_SESSION['role'])) : '';
$userId = (int) $_SESSION['user_id'];

// ✅ Direct role checking - matches login_proc.php allowed roles
$allowedRoles = ['admin', 'director', 'dept_head', 'staff'];

// Define role capabilities
$canViewAll = in_array($userRole, ['admin', 'director', 'dept_head']);
$isStaff = ($userRole === 'staff');
$isDirector = ($userRole === 'director');
$isAdmin = ($userRole === 'admin');
$isDeptHead = ($userRole === 'dept_head');

// If not in allowed roles, redirect
if (!in_array($userRole, $allowedRoles)) {
    $_SESSION['error_message'] = "Anda tidak memiliki akses ke halaman ini. Role: " . $userRole;
    header("Location: ../../dashboard.php");
    exit;
}

// Get task ID
$taskId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// ✅ CORRECT: Path untuk kembali (tanpa dashboard.php prefix)
$backUrl = match($userRole) {
    'admin' => "pages/admin/rencana_kerja.php",
    'dept_head' => "pages/manager/rencana_kerja.php",
    'director' => "pages/director/rencana_kerja.php",
    'staff' => "pages/staff/rencana_kerja.php",
    default => "pages/staff/rencana_kerja.php"
};

if ($taskId <= 0) {
    $_SESSION['error_message'] = "ID tugas tidak valid";
    header("Location: ../../dashboard.php?load=" . urlencode($backUrl));
    exit;
}

// Helper function untuk escape HTML dengan aman
function e($value, $default = '-') {
    return htmlspecialchars($value ?? $default, ENT_QUOTES, 'UTF-8');
}

// Get task data with all details - DENGAN COALESCE UNTUK PRIORITY
$sql = "SELECT rk.*, 
        COALESCE(rk.priority, 'penting_tidak_genting') AS priority,
        creator.full_name AS creator_name,
        creator.email AS creator_email,
        assignee.full_name AS assignee_name,
        assignee.email AS assignee_email,
        assignee.department AS assignee_department,
        approver.full_name AS approver_name
        FROM rencana_kerja rk
        JOIN users creator ON rk.created_by = creator.id
        JOIN users assignee ON rk.assigned_to = assignee.id
        LEFT JOIN users approver ON rk.approval_by = approver.id
        WHERE rk.id = ? AND rk.is_deleted = 0";

// If user can't view all, add filter to only show their assigned tasks or created by them
if (!$canViewAll) {
    $sql .= " AND (rk.assigned_to = ? OR rk.created_by = ?)";
}

$stmt = $conn->prepare($sql);

if (!$stmt) {
    $_SESSION['error_message'] = "Database error: " . $conn->error;
    header("Location: ../../dashboard.php?load=" . urlencode($backUrl));
    exit;
}

if (!$canViewAll) {
    $stmt->bind_param("iii", $taskId, $userId, $userId);
} else {
    $stmt->bind_param("i", $taskId);
}

$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = !$canViewAll ? "Data tidak ditemukan atau Anda tidak memiliki akses" : "Data tidak ditemukan";
    header("Location: ../../dashboard.php?load=" . urlencode($backUrl));
    exit;
}

$task = $result->fetch_assoc();

// ✅ FIX: Normalize department
if (empty($task['department']) || $task['department'] === 'N/A') {
    $task['department'] = $task['assignee_department'] ?? 'Tidak Ada Department';
}

if (empty($task['department'])) {
    $task['department'] = 'Tidak Ada Department';
}

// Helper function untuk status
function getStatusConfig($status) {
    $configs = [
        'done' => [
            'class' => 'bg-green-100 text-green-700 border-green-200',
            'icon' => 'bi-check-circle-fill',
            'text' => 'Selesai'
        ],
        'progress' => [
            'class' => 'bg-blue-100 text-blue-700 border-blue-200',
            'icon' => 'bi-arrow-repeat',
            'text' => 'Progress'
        ],
        'stuck' => [
            'class' => 'bg-red-100 text-red-700 border-red-200',
            'icon' => 'bi-exclamation-triangle-fill',
            'text' => 'Terhambat'
        ],
        'pending' => [
            'class' => 'bg-gray-100 text-gray-700 border-gray-200',
            'icon' => 'bi-clock-fill',
            'text' => 'Pending'
        ]
    ];
    return $configs[$status] ?? $configs['pending'];
}

// Helper function untuk priority
function getPriorityConfig($priority) {
    $configs = [
        'penting_genting' => [
            'class' => 'bg-red-100 text-red-700 border-red-200',
            'text' => 'Penting & Genting'
        ],
        'penting_tidak_genting' => [
            'class' => 'bg-yellow-100 text-yellow-700 border-yellow-200',
            'text' => 'Penting Tidak Genting'
        ],
        'penting' => [
            'class' => 'bg-orange-100 text-orange-700 border-orange-200',
            'text' => 'Penting'
        ],
        'tidak_penting' => [
            'class' => 'bg-green-100 text-green-700 border-green-200',
            'text' => 'Tidak Penting'
        ],
        // Legacy support
        'high' => [
            'class' => 'bg-red-100 text-red-700 border-red-200',
            'text' => 'Tinggi'
        ],
        'medium' => [
            'class' => 'bg-yellow-100 text-yellow-700 border-yellow-200',
            'text' => 'Sedang'
        ],
        'low' => [
            'class' => 'bg-green-100 text-green-700 border-green-200',
            'text' => 'Rendah'
        ]
    ];
    return $configs[$priority] ?? $configs['penting_tidak_genting'];
}

// Ambil status dan priority dengan aman
$taskStatus = $task['status'] ?? 'pending';
$taskPriority = $task['priority'] ?? 'penting_tidak_genting';

$statusConfig = getStatusConfig($taskStatus);
$priorityConfig = getPriorityConfig($taskPriority);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Rencana Kerja - <?= e($task['judul_tugas'], 'Tugas') ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#14b8a6',
                        'primary-dark': '#0f766e',
                        'primary-light': '#5eead4',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        .alert-slide-in {
            animation: slideIn 0.3s ease-out;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #14b8a6;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #0f766e;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-blue-50 to-slate-100">
    <!-- Success/Error Messages -->
    <?php if (isset($_SESSION['success_message'])): ?>
    <div id="successAlert" class="fixed top-3 right-3 bg-green-50 border-l-4 border-green-500 rounded-lg p-3 shadow-lg z-50 max-w-sm alert-slide-in">
        <div class="flex items-start gap-2">
            <div class="w-8 h-8 bg-green-500 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="bi bi-check-circle-fill text-white text-sm"></i>
            </div>
            <div class="flex-1">
                <p class="font-bold text-green-900 text-sm">Berhasil!</p>
                <p class="text-xs text-green-700"><?= htmlspecialchars($_SESSION['success_message']) ?></p>
            </div>
            <button onclick="this.parentElement.parentElement.remove()" class="text-green-600 hover:text-green-800 transition text-sm">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
    </div>
    <?php unset($_SESSION['success_message']); endif; ?>

    <?php if (isset($_SESSION['error_message'])): ?>
    <div id="errorAlert" class="fixed top-3 right-3 bg-red-50 border-l-4 border-red-500 rounded-lg p-3 shadow-lg z-50 max-w-sm alert-slide-in">
        <div class="flex items-start gap-2">
            <div class="w-8 h-8 bg-red-500 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="bi bi-exclamation-triangle-fill text-white text-sm"></i>
            </div>
            <div class="flex-1">
                <p class="font-bold text-red-900 text-sm">Error!</p>
                <p class="text-xs text-red-700"><?= htmlspecialchars($_SESSION['error_message']) ?></p>
            </div>
            <button onclick="this.parentElement.parentElement.remove()" class="text-red-600 hover:text-red-800 transition text-sm">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
    </div>
    <?php unset($_SESSION['error_message']); endif; ?>

    <div class="min-h-screen py-4">
        <div class="max-w-5xl mx-auto px-3">
            <!-- Header -->
            <div class="mb-3">
                <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
                    <div class="flex items-center gap-2">
                        <button 
                            type="button"
                            onclick="goBack('<?= $backUrl ?>')"
                            class="w-8 h-8 flex items-center justify-center rounded-lg bg-white hover:bg-slate-50 border border-slate-200 transition cursor-pointer">
                            <i class="bi bi-arrow-left text-slate-700"></i>
                        </button>
                        <div>
                            <h1 class="text-lg font-black text-slate-900">Detail Rencana Kerja</h1>
                            <p class="text-xs text-slate-600">Informasi lengkap tugas</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-3">
                <!-- Left Column - Main Info -->
                <div class="lg:col-span-2 space-y-3">
                    <!-- Task Info Card -->
                    <div class="bg-white rounded-lg shadow-md border border-slate-200 overflow-hidden">
                        <div class="bg-gradient-to-r from-primary to-primary-dark p-3">
                            <h2 class="text-base font-black text-white mb-1"><?= e($task['judul_tugas'], 'Tanpa Judul') ?></h2>
                            <div class="flex items-center gap-2 text-white/80 text-xs flex-wrap">
                                <?php if (!empty($task['department'])): ?>
                                <div class="flex items-center gap-1">
                                    <i class="bi bi-building"></i>
                                    <span><?= e($task['department']) ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="flex items-center gap-1">
                                    <i class="bi bi-calendar-event"></i>
                                    <span><?= !empty($task['tenggat_waktu']) ? date('d M Y', strtotime($task['tenggat_waktu'])) : 'Tidak ada tenggat' ?></span>
                                </div>
                            </div>
                        </div>

                        <div class="p-3 space-y-3">
                            <!-- Description -->
                            <div>
                                <h3 class="text-xs font-bold text-slate-700 mb-1 flex items-center gap-1">
                                    <i class="bi bi-align-left text-primary text-sm"></i>
                                    Deskripsi
                                </h3>
                                <p class="text-xs text-slate-700 leading-relaxed">
                                    <?= !empty($task['deskripsi']) ? nl2br(e($task['deskripsi'])) : '<span class="text-slate-400 italic">Tidak ada deskripsi</span>' ?>
                                </p>
                            </div>

                            <!-- Progress -->
                            <div>
                                <div class="flex items-center justify-between mb-1">
                                    <h3 class="text-xs font-bold text-slate-700 flex items-center gap-1">
                                        <i class="bi bi-graph-up text-primary text-sm"></i>
                                        Progress
                                    </h3>
                                    <span class="text-lg font-black text-primary"><?= (int)($task['progress'] ?? 0) ?>%</span>
                                </div>
                                <div class="h-3 bg-slate-200 rounded-full overflow-hidden">
                                    <div class="h-full bg-gradient-to-r from-primary to-primary-dark transition-all duration-500" 
                                         style="width: <?= (int)($task['progress'] ?? 0) ?>%"></div>
                                </div>
                            </div>

                            <!-- Status & Priority -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div>
                                    <h3 class="text-xs font-bold text-slate-700 mb-1 flex items-center gap-1">
                                        <i class="bi bi-clipboard-check text-primary text-sm"></i>
                                        Status
                                    </h3>
                                    <span class="inline-flex items-center px-3 py-1 rounded-lg font-bold <?= $statusConfig['class'] ?> border text-xs">
                                        <i class="bi <?= $statusConfig['icon'] ?> mr-1 text-xs"></i>
                                        <?= $statusConfig['text'] ?>
                                    </span>
                                </div>

                                <div>
                                    <h3 class="text-xs font-bold text-slate-700 mb-1 flex items-center gap-1">
                                        <i class="bi bi-flag text-primary text-sm"></i>
                                        Prioritas
                                    </h3>
                                    <span class="inline-flex items-center px-3 py-1 rounded-lg font-bold <?= $priorityConfig['class'] ?> border text-xs">
                                        <?= $priorityConfig['text'] ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right Column - Metadata -->
                <div class="space-y-3">
                    <!-- Assignee Card -->
                    <div class="bg-white rounded-lg shadow-md border border-slate-200 p-3">
                        <h3 class="text-xs font-bold text-slate-700 mb-2 flex items-center gap-1">
                            <i class="bi bi-person-check text-primary text-sm"></i>
                            Ditugaskan Kepada
                        </h3>
                        <div class="flex items-center gap-2 mb-2">
                            <div class="w-10 h-10 bg-gradient-to-br from-primary to-primary-dark rounded-full flex items-center justify-center text-white text-sm font-black shadow-lg">
                                <?= strtoupper(substr($task['assignee_name'] ?? 'U', 0, 1)) ?>
                            </div>
                            <div>
                                <p class="font-bold text-slate-900 text-sm"><?= e($task['assignee_name'], 'Unknown') ?></p>
                                <?php if (!empty($task['assignee_department'])): ?>
                                <p class="text-xs text-slate-600"><?= e($task['assignee_department']) ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php if (!empty($task['assignee_email'])): ?>
                        <p class="text-xs text-slate-600">
                            <i class="bi bi-envelope mr-1"></i>
                            <?= e($task['assignee_email']) ?>
                        </p>
                        <?php endif; ?>
                    </div>

                    <!-- Creator Card -->
                    <div class="bg-white rounded-lg shadow-md border border-slate-200 p-3">
                        <h3 class="text-xs font-bold text-slate-700 mb-2 flex items-center gap-1">
                            <i class="bi bi-person-badge text-primary text-sm"></i>
                            Dibuat Oleh
                        </h3>
                        <div class="space-y-2">
                            <div>
                                <p class="text-xs text-slate-600">Nama</p>
                                <p class="font-bold text-slate-900 text-sm"><?= e($task['creator_name'], 'Unknown') ?></p>
                            </div>
                            <?php if (!empty($task['creator_email'])): ?>
                            <div>
                                <p class="text-xs text-slate-600">Email</p>
                                <p class="font-medium text-slate-900 text-xs"><?= e($task['creator_email']) ?></p>
                            </div>
                            <?php endif; ?>
                            <div>
                                <p class="text-xs text-slate-600">Tanggal</p>
                                <p class="font-medium text-slate-900 text-xs">
                                    <?= !empty($task['created_at']) && $task['created_at'] != '0000-00-00 00:00:00' 
                                        ? date('d M Y, H:i', strtotime($task['created_at'])) 
                                        : '-' ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Timeline Card -->
                    <div class="bg-white rounded-lg shadow-md border border-slate-200 p-3">
                        <h3 class="text-xs font-bold text-slate-700 mb-2 flex items-center gap-1">
                            <i class="bi bi-clock-history text-primary text-sm"></i>
                            Timeline
                        </h3>
                        <div class="space-y-2">
                            <div class="flex items-center justify-between">
                                <span class="text-xs text-slate-600">Dibuat</span>
                                <span class="text-xs font-bold text-slate-900">
                                    <?= !empty($task['created_at']) && $task['created_at'] != '0000-00-00 00:00:00' 
                                        ? date('d M Y', strtotime($task['created_at'])) 
                                        : '-' ?>
                                </span>
                            </div>
                            <?php if (!empty($task['updated_at']) && $task['updated_at'] != '0000-00-00 00:00:00'): ?>
                            <div class="flex items-center justify-between">
                                <span class="text-xs text-slate-600">Terakhir Update</span>
                                <span class="text-xs font-bold text-slate-900"><?= date('d M Y', strtotime($task['updated_at'])) ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="flex items-center justify-between">
                                <span class="text-xs text-slate-600">Deadline</span>
                                <span class="text-xs font-bold text-red-600">
                                    <?= !empty($task['tenggat_waktu']) && $task['tenggat_waktu'] != '0000-00-00' 
                                        ? date('d M Y', strtotime($task['tenggat_waktu'])) 
                                        : '-' ?>
                                </span>
                            </div>
                            <?php
                            $daysLeft = 0;
                            if (!empty($task['tenggat_waktu']) && $task['tenggat_waktu'] != '0000-00-00') {
                                try {
                                    $deadline = new DateTime($task['tenggat_waktu']);
                                    $now = new DateTime();
                                    $diff = $now->diff($deadline);
                                    $daysLeft = $deadline > $now ? $diff->days : -$diff->days;
                                } catch (Exception $e) {
                                    $daysLeft = 0;
                                }
                            }
                            ?>
                            <div class="pt-2 border-t border-slate-200">
                                <div class="text-center">
                                    <?php if ($daysLeft > 0): ?>
                                        <p class="text-xl font-black text-primary"><?= $daysLeft ?></p>
                                        <p class="text-xs text-slate-600">Hari tersisa</p>
                                    <?php elseif ($daysLeft == 0): ?>
                                        <p class="text-base font-black text-amber-600">Hari ini!</p>
                                    <?php elseif ($daysLeft < 0): ?>
                                        <p class="text-xl font-black text-red-600"><?= abs($daysLeft) ?></p>
                                        <p class="text-xs text-red-600">Hari terlambat</p>
                                    <?php else: ?>
                                        <p class="text-xs text-slate-500">Tidak ada deadline</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // ✅ FINAL FIX: goBack function yang BENAR
        function goBack(url) {
            console.log('🔍 Debug Info:');
            console.log('Target URL:', url);
            console.log('Has parent:', !!parent);
            console.log('Has iframe:', !!(parent && parent.document.getElementById('contentFrame')));
            
            // Cek apakah ada iframe di parent
            if (parent && parent.document.getElementById('contentFrame')) {
                // ✅ BENAR: Load pages langsung tanpa dashboard.php wrapper
                console.log('✅ Loading via iframe:', url);
                parent.document.getElementById('contentFrame').src = url;
                return;
            }

            // Kalau tidak ada iframe, redirect normal
            console.log('🔄 Redirecting normally with dashboard wrapper');
            window.location.href = '/inventoryACF/dashboard.php?load=' + encodeURIComponent(url);
        }
        
        // Auto hide alerts after 5 seconds
        setTimeout(() => {
            document.getElementById('successAlert')?.remove();
            document.getElementById('errorAlert')?.remove();
        }, 5000);
    </script>
</body>
</html>