<?php
require_once __DIR__ . '/../../config/session_check.php';
require_once __DIR__ . '/../../DataBase/koneksi.php';
require_once __DIR__ . '/../../config/RencanaKerjaPermission.php';

// Cek role access
$allowedRoles = ['admin', 'director', 'dept_head', 'staff'];
if (!checkRole($allowedRoles)) {
    echo '<div style="padding: 40px; text-align: center;">
            <h2>Access Denied</h2>
            <p>Anda tidak memiliki akses ke halaman ini.</p>
          </div>';
    exit;
}

// Normalize role
$userRole = strtolower(trim($_SESSION['role']));
$userId = (int) $_SESSION['user_id'];

$permission = new RencanaKerjaPermission($conn, $_SESSION['user_id'], $userRole);

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

// ✅ FIXED: Determine back URL based on role (dept_head → manager folder)
$backUrl = match($userRole) {
    'admin' => '../admin/rencana_kerja.php',
    'dept_head' => '../manager/rencana_kerja.php', // ← PERBAIKAN UTAMA
    'director' => '../director/rencana_kerja.php',
    'staff' => '../staff/rencana_kerja.php',
    default => '../staff/rencana_kerja.php'
};

if ($taskId <= 0) {
    $_SESSION['error_message'] = "ID tugas tidak valid";
    header("Location: $backUrl");
    exit;
}

// Handle form submission
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $judulTugas = trim($_POST['judul_tugas'] ?? '');
    $deskripsi = trim($_POST['deskripsi'] ?? '');
    $assignedTo = (int)($_POST['assigned_to'] ?? 0);
    $tenggatWaktu = trim($_POST['tenggat_waktu'] ?? '');
    $priority = trim($_POST['priority'] ?? 'penting');
    $status = trim($_POST['status'] ?? 'pending');
    $progress = (int)($_POST['progress'] ?? 0);

    // Validation
    if (empty($judulTugas)) $errors[] = "Judul tugas harus diisi";
    if (empty($assignedTo)) $errors[] = "Harus menentukan penerima tugas";
    if (empty($tenggatWaktu)) $errors[] = "Tenggat waktu harus diisi";
    if ($progress < 0 || $progress > 100) $errors[] = "Progress harus antara 0-100";

    if (empty($errors)) {
        // Get current task
        $checkSql = "SELECT id FROM rencana_kerja WHERE id = ? AND is_deleted = 0";
        $checkStmt = $conn->prepare($checkSql);
        $checkStmt->bind_param("i", $taskId);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        
        if ($checkResult->num_rows > 0) {
            // Update query
            $sql = "UPDATE rencana_kerja 
                    SET judul_tugas = ?, 
                        deskripsi = ?, 
                        assigned_to = ?, 
                        tenggat_waktu = ?, 
                        priority = ?, 
                        status = ?, 
                        progress = ?, 
                        updated_at = NOW() 
                    WHERE id = ? AND is_deleted = 0";
            
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                $errors[] = "Database error: " . $conn->error;
            } else {
                $stmt->bind_param("ssisssii", 
                    $judulTugas, 
                    $deskripsi, 
                    $assignedTo, 
                    $tenggatWaktu, 
                    $priority, 
                    $status, 
                    $progress, 
                    $taskId
                );
                
                if ($stmt->execute()) {
                    $_SESSION['success_message'] = "✅ Rencana kerja berhasil diperbarui";
                    $stmt->close();
                    header("Location: $backUrl");
                    exit;
                } else {
                    $errors[] = "Gagal memperbarui data: " . $stmt->error;
                }
                
                if (isset($stmt)) {
                    $stmt->close();
                }
            }
        } else {
            $errors[] = "Task tidak ditemukan";
        }
        
        $checkStmt->close();
    }
}

// Get task data with department from assignee
$sql = "SELECT rk.*, 
        creator.full_name AS creator_name,
        assignee.full_name AS assignee_name,
        assignee.department AS assignee_department,
        assignee.status AS assignee_status,
        assignee.is_active AS assignee_is_active
        FROM rencana_kerja rk
        JOIN users creator ON rk.created_by = creator.id
        JOIN users assignee ON rk.assigned_to = assignee.id
        WHERE rk.id = ? AND rk.is_deleted = 0";

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

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

$stmt->bind_param("i", $taskId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Data tidak ditemukan";
    $stmt->close();
    header("Location: $backUrl");
    exit;
}

$task = $result->fetch_assoc();
$stmt->close();

// Fix progress value
$task['progress'] = isset($task['progress']) && $task['progress'] !== null
    ? (int)$task['progress']
    : 0;

// Use assignee's department as the task department
$task['department'] = $task['assignee_department'] ?? '';

// ✅ Get assignable users from permission
$users = $permission->getAssignableUsers();

// ✅ CRITICAL FIX: Pastikan assignee lama SELALU masuk list
// Untuk EDIT mode, assignee lama harus tetap muncul walaupun inactive
$assignedUserExists = false;
foreach ($users as $u) {
    if ($u['id'] == $task['assigned_to']) {
        $assignedUserExists = true;
        break;
    }
}

// Jika assignee lama tidak ada di list, tambahkan secara manual
if (!$assignedUserExists) {
    // ✅ FIXED: Tanpa is_deleted karena tabel users tidak punya kolom itu
    // Query ini ambil user apapun statusnya (untuk edit mode)
    $extraUserSql = "SELECT id, full_name, department, status, is_active 
                     FROM users 
                     WHERE id = ?";
    $extraStmt = $conn->prepare($extraUserSql);
    
    if ($extraStmt) {
        $extraStmt->bind_param("i", $task['assigned_to']);
        $extraStmt->execute();
        $extraResult = $extraStmt->get_result();
        
        if ($extraResult->num_rows > 0) {
            $assignedUser = $extraResult->fetch_assoc();
            // Tambahkan di awal array agar mudah terlihat
            array_unshift($users, $assignedUser);
        }
        
        $extraStmt->close();
    }
}

$departments = $permission->getAccessibleDepartments();

// Prepare progress value for form
$progressValue = (int)($_POST['progress'] ?? $task['progress'] ?? 0);

// Check if current assignee is inactive
$isAssigneeInactive = ($task['assignee_status'] === 'inactive' || $task['assignee_is_active'] == 0);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Rencana Kerja</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-blue-50 to-slate-100">
    <div class="min-h-screen py-4">
        <div class="max-w-4xl mx-auto px-3">
            <!-- Header -->
            <div class="mb-3">
                <div class="flex items-center gap-2 mb-2">
                    <a href="<?= $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 no-underline text-slate-700">
                        ←
                    </a>
                    <div>
                        <h1 class="text-lg font-black text-slate-900">Edit Rencana Kerja</h1>
                        <p class="text-xs text-slate-600">Perbarui informasi tugas</p>
                    </div>
                </div>
            </div>

            <!-- Warning if assignee is inactive -->
            <?php if ($isAssigneeInactive): ?>
            <div class="bg-amber-50 border-l-4 border-amber-500 rounded-lg p-3 mb-4 shadow-md">
                <div class="flex items-start gap-2">
                    <div class="w-8 h-8 bg-amber-500 rounded-lg flex items-center justify-center flex-shrink-0 text-white text-sm font-bold">
                        ⚠
                    </div>
                    <div class="flex-1">
                        <h3 class="font-bold text-amber-900 text-sm mb-1">Perhatian</h3>
                        <p class="text-amber-700 text-xs">
                            User yang saat ini ditugaskan (<strong><?= htmlspecialchars($task['assignee_name']) ?></strong>) 
                            berstatus <span class="font-bold">INACTIVE</span>. 
                            Pertimbangkan untuk menugaskan ke user lain yang aktif.
                        </p>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Error Messages -->
            <?php if (!empty($errors)): ?>
            <div class="bg-red-50 border-l-4 border-red-500 rounded-lg p-3 mb-4 shadow-md">
                <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 text-white text-sm font-bold">
                        !
                    </div>
                    <div class="flex-1">
                        <h3 class="font-bold text-red-900 text-sm mb-1">Terdapat kesalahan:</h3>
                        <ul class="list-disc list-inside text-red-700 space-y-0.5 text-xs">
                            <?php foreach ($errors as $error): ?>
                                <li><?= htmlspecialchars($error) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Form -->
            <form method="POST" class="bg-white rounded-lg shadow-md border border-slate-200">
                <div class="p-4 space-y-4">
                    <!-- Judul Tugas -->
                    <div>
                        <label for="judul_tugas" class="block text-xs font-bold text-slate-700 mb-1">
                            Judul Tugas <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="judul_tugas" name="judul_tugas" required
                               value="<?= htmlspecialchars($_POST['judul_tugas'] ?? $task['judul_tugas']) ?>"
                               class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium text-sm"
                               placeholder="Masukkan judul tugas...">
                    </div>

                    <!-- Deskripsi -->
                    <div>
                        <label for="deskripsi" class="block text-xs font-bold text-slate-700 mb-1">
                            Deskripsi
                        </label>
                        <textarea id="deskripsi" name="deskripsi" rows="3"
                                  class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium text-sm"
                                  placeholder="Tambahkan deskripsi detail tugas..."><?= htmlspecialchars($_POST['deskripsi'] ?? $task['deskripsi']) ?></textarea>
                    </div>

                    <!-- Assigned To & Department -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label for="assigned_to" class="block text-xs font-bold text-slate-700 mb-1">
                                Ditugaskan Kepada <span class="text-red-500">*</span>
                            </label>
                            <select id="assigned_to" name="assigned_to" required
                                    class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium bg-white text-sm">
                                <option value="">Pilih User</option>
                                <?php 
                                if (empty($users)) {
                                    echo '<option value="" disabled>Tidak ada user tersedia</option>';
                                } else {
                                    foreach ($users as $user): 
                                        $isCurrentAssignee = (($_POST['assigned_to'] ?? $task['assigned_to']) == $user['id']);
                                        $isInactive = ($user['status'] === 'inactive' || $user['is_active'] == 0);
                                        $statusBadge = $isInactive ? ' [INACTIVE]' : '';
                                ?>
                                    <option value="<?= $user['id'] ?>"
                                            data-department="<?= htmlspecialchars($user['department'] ?? '') ?>"
                                            data-status="<?= htmlspecialchars($user['status'] ?? 'active') ?>"
                                            <?= $isCurrentAssignee ? 'selected' : '' ?>
                                            <?= $isInactive ? 'style="color: #dc2626; font-style: italic;"' : '' ?>>
                                        <?= htmlspecialchars($user['full_name'] ?? $user['nama'] ?? 'Unknown') ?> 
                                        (<?= htmlspecialchars($user['department'] ?? 'N/A') ?>)<?= $statusBadge ?>
                                        <?= $isCurrentAssignee ? ' ✓' : '' ?>
                                    </option>
                                <?php 
                                    endforeach;
                                }
                                ?>
                            </select>
                            <?php if (!empty($users)): ?>
                            <p class="text-xs text-slate-500 mt-1">
                                <?= count($users) ?> user tersedia
                            </p>
                            <?php endif; ?>
                        </div>

                        <div>
                            <label for="department_display" class="block text-xs font-bold text-slate-700 mb-1">
                                Department <span class="text-slate-400 text-xs font-normal">(otomatis)</span>
                            </label>
                            <input type="text" id="department_display" 
                                   value="<?= htmlspecialchars($task['department']) ?>"
                                   readonly disabled
                                   class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg bg-slate-50 text-slate-600 font-medium text-sm cursor-not-allowed">
                            <p class="text-xs text-slate-500 mt-1">Mengikuti department user yang dipilih</p>
                        </div>
                    </div>

                    <!-- Tenggat Waktu & Priority -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label for="tenggat_waktu" class="block text-xs font-bold text-slate-700 mb-1">
                                Tenggat Waktu <span class="text-red-500">*</span>
                            </label>
                            <input type="date" id="tenggat_waktu" name="tenggat_waktu" required
                                   value="<?= htmlspecialchars($_POST['tenggat_waktu'] ?? $task['tenggat_waktu']) ?>"
                                   class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium text-sm">
                        </div>

                        <div>
                            <label for="priority" class="block text-xs font-bold text-slate-700 mb-1">
                                Prioritas
                            </label>
                            <select id="priority" name="priority"
                                    class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium bg-white text-sm">
                                <option value="tidak_penting" <?= (($_POST['priority'] ?? $task['priority']) === 'tidak_penting') ? 'selected' : '' ?>>Tidak Penting</option>
                                <option value="penting" <?= (($_POST['priority'] ?? $task['priority']) === 'penting') ? 'selected' : '' ?>>Penting</option>
                                <option value="penting_tidak_genting" <?= (($_POST['priority'] ?? $task['priority']) === 'penting_tidak_genting') ? 'selected' : '' ?>>Penting Tidak Genting</option>
                                <option value="penting_genting" <?= (($_POST['priority'] ?? $task['priority']) === 'penting_genting') ? 'selected' : '' ?>>Penting Genting</option>
                            </select>
                        </div>
                    </div>

                    <!-- Status & Progress -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label for="status" class="block text-xs font-bold text-slate-700 mb-1">
                                Status
                            </label>
                            <select id="status" name="status"
                                    class="w-full px-3 py-2 border-2 border-slate-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition font-medium bg-white text-sm"
                                    onchange="updateProgressByStatus(this.value)">
                                <option value="pending" <?= (($_POST['status'] ?? $task['status']) === 'pending') ? 'selected' : '' ?>>Pending</option>
                                <option value="progress" <?= (($_POST['status'] ?? $task['status']) === 'progress') ? 'selected' : '' ?>>Progress</option>
                                <option value="stuck" <?= (($_POST['status'] ?? $task['status']) === 'stuck') ? 'selected' : '' ?>>Terhambat</option>
                                <option value="done" <?= (($_POST['status'] ?? $task['status']) === 'done') ? 'selected' : '' ?>>Selesai</option>
                            </select>
                        </div>

                        <div>
                            <label for="progress" class="block text-xs font-bold text-slate-700 mb-1">
                                Progress (%)
                            </label>
                            <div class="flex items-center gap-2">
                                <input type="range" id="progress" name="progress" min="0" max="100" 
                                       value="<?= $progressValue ?>"
                                       class="flex-1 h-2 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-primary" 
                                       oninput="updateProgressDisplay(this.value)">
                                <div class="flex items-center gap-1 min-w-[50px]">
                                    <span id="progressValue" class="text-base font-black text-primary">
                                        <?= $progressValue ?>
                                    </span>
                                    <span class="text-slate-600 font-bold text-sm">%</span>
                                </div>
                            </div>
                            <div class="mt-1.5 h-1.5 bg-slate-200 rounded-full overflow-hidden">
                                <div id="progressBar" class="h-full bg-gradient-to-r from-primary to-primary-dark transition-all duration-300" 
                                     style="width: <?= $progressValue ?>%"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Info -->
                    <div class="bg-gradient-to-r from-slate-50 to-blue-50 rounded-lg p-3 border border-slate-200">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
                            <div class="flex items-center gap-2">
                                <span class="text-slate-600">Dibuat oleh:</span>
                                <span class="font-bold text-slate-900"><?= htmlspecialchars($task['creator_name']) ?></span>
                            </div>
                            <div class="flex items-center gap-2">
                                <span class="text-slate-600">Dibuat pada:</span>
                                <span class="font-bold text-slate-900"><?= date('d M Y H:i', strtotime($task['created_at'])) ?></span>
                            </div>
                            <?php if ($task['updated_at']): ?>
                            <div class="flex items-center gap-2">
                                <span class="text-slate-600">Terakhir diupdate:</span>
                                <span class="font-bold text-slate-900"><?= date('d M Y H:i', strtotime($task['updated_at'])) ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Form Footer -->
                <div class="bg-slate-50 px-4 py-3 rounded-b-lg flex items-center justify-end gap-2 border-t border-slate-200">
                    <a href="<?= $backUrl ?>"
                        class="px-4 py-2 border-2 border-slate-300 text-slate-700 rounded-lg hover:bg-white transition font-bold text-sm cursor-pointer no-underline inline-block">
                        Batal
                    </a>
                    <button type="submit" class="px-4 py-2 bg-gradient-to-r from-primary to-primary-dark hover:shadow-lg text-white rounded-lg transition font-bold text-sm">
                        Perbarui Tugas
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Update progress display when slider changes
        function updateProgressDisplay(value) {
            document.getElementById('progressValue').textContent = value;
            document.getElementById('progressBar').style.width = value + '%';
        }

        // Auto-update progress based on status
        function updateProgressByStatus(status) {
            const progressInput = document.getElementById('progress');
            
            switch(status) {
                case 'done':
                    progressInput.value = 100;
                    updateProgressDisplay(100);
                    break;
            }
        }

        // Update department display when user changes
        function updateDepartmentDisplay() {
            const userSelect = document.getElementById('assigned_to');
            const deptDisplay = document.getElementById('department_display');
            const selectedOption = userSelect.options[userSelect.selectedIndex];
            
            if (selectedOption && selectedOption.value) {
                const userDept = selectedOption.getAttribute('data-department') || 'N/A';
                deptDisplay.value = userDept;
            } else {
                deptDisplay.value = '';
            }
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            const userSelect = document.getElementById('assigned_to');
            
            // Update department display when user selection changes
            userSelect.addEventListener('change', updateDepartmentDisplay);
            
            // Set initial department display
            updateDepartmentDisplay();
        });
    </script>
</body>
</html>