<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';
require_once __DIR__ . '/../src/Permissions/PermissionManager.php';
require_once __DIR__ . '/navigation.php';

AuthManager::requireAuth();

$user = AuthManager::getCurrentUser();

// Get workspace
$workspaceParam = $_GET['workspace'] ?? null;
$pdo = getPDO();
$company = null;

if ($workspaceParam) {
    $stmt = $pdo->prepare('
        SELECT c.* FROM companies c
        JOIN user_company_access uca ON c.id = uca.company_id
        WHERE uca.user_id = ? AND c.subdomain = ?
    ');
    $stmt->execute([$user['id'], $workspaceParam]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$company && isset($_SESSION['current_company_id'])) {
    $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ?');
    $stmt->execute([$_SESSION['current_company_id']]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$company) {
    header('Location: /workspace-plans.php');
    exit;
}

$_SESSION['current_company_id'] = $company['id'];
$_SESSION['current_company'] = $company;

$companyId = (int)$company['id'];
$userId = (int)$user['id'];
$projectId = (int)($_GET['id'] ?? 0);

if (!$projectId) {
    header('Location: /projects.php?workspace=' . urlencode($company['subdomain']));
    exit;
}

// Get project
$project = ProjectManager::getProject($projectId, $companyId);
if (!$project) {
    header('Location: /projects.php?workspace=' . urlencode($company['subdomain']));
    exit;
}

// Permission helper
$hasPermission = function(string $permission) use ($userId, $companyId): bool {
    if (PermissionManager::isOwner($userId, $companyId)) {
        return true;
    }
    return PermissionManager::hasPermission($userId, $companyId, $permission);
};

$canEdit = $hasPermission('projects_edit');
$canCreateTask = $hasPermission('tasks_create');
$canEditTask = $hasPermission('tasks_edit');

// Get tasks and statuses
$tasks = TaskManager::getTasks($projectId, $companyId);
$statuses = TaskManager::getStatuses($companyId);

// Get workspace members
$memberStmt = $pdo->prepare('
    SELECT u.id, u.name, u.email 
    FROM users u
    JOIN user_company_access uca ON u.id = uca.user_id
    WHERE uca.company_id = ?
    ORDER BY u.name ASC
');
$memberStmt->execute([$companyId]);
$members = $memberStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

// Group tasks by status
$tasksByStatus = [];
foreach ($statuses as $status) {
    $tasksByStatus[$status['id']] = [
        'status' => $status,
        'tasks' => []
    ];
}

foreach ($tasks as $task) {
    $statusId = $task['status_id'] ?? 0;
    if (isset($tasksByStatus[$statusId])) {
        $tasksByStatus[$statusId]['tasks'][] = $task;
    }
}

$priorityColors = [
    'low' => 'text-slate-400',
    'medium' => 'text-blue-500',
    'high' => 'text-amber-500',
    'urgent' => 'text-rose-500'
];

$pageTitle = htmlspecialchars($project['name']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - <?= htmlspecialchars($company['name']) ?></title>
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <style>
        @keyframes slideInRight {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }
        .slide-panel { animation: slideInRight 0.3s ease-out; }
        .task-card {
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .task-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
        }
        .task-card.sortable-ghost {
            opacity: 0.4;
            background: #e2e8f0;
        }
        .task-card.sortable-drag {
            box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.2);
            transform: rotate(2deg);
        }
        .status-column {
            min-height: 200px;
        }
        .add-task-btn {
            opacity: 0;
            transform: translateY(-10px);
            transition: all 0.2s;
        }
        .status-column:hover .add-task-btn {
            opacity: 1;
            transform: translateY(0);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 via-blue-50/30 to-slate-50 min-h-screen">
    <?php renderNavigationNew('Projects', 'dark'); ?>
    
    <main class="max-w-[1800px] mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <!-- Project Header -->
        <div class="bg-white rounded-2xl p-6 border border-slate-200/60 shadow-sm mb-6">
            <div class="flex items-start justify-between mb-4">
                <div class="flex-1">
                    <div class="flex items-center gap-3 mb-3">
                        <a href="/projects.php?workspace=<?= urlencode($company['subdomain']) ?>" 
                           class="text-slate-400 hover:text-slate-600 transition-colors">
                            <i class="fas fa-arrow-left"></i>
                        </a>
                        <?php if ($project['category_name']): ?>
                            <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-semibold" 
                                  style="background-color: <?= htmlspecialchars($project['category_color']) ?>15; color: <?= htmlspecialchars($project['category_color']) ?>">
                                <i class="fas fa-<?= htmlspecialchars($project['category_icon'] ?? 'folder') ?>"></i>
                                <?= htmlspecialchars($project['category_name']) ?>
                            </span>
                        <?php endif; ?>
                    </div>
                    <h1 class="text-3xl font-bold text-slate-900 mb-2"><?= htmlspecialchars($project['name']) ?></h1>
                    <?php if ($project['description']): ?>
                        <p class="text-slate-600 max-w-3xl"><?= nl2br(htmlspecialchars($project['description'])) ?></p>
                    <?php endif; ?>
                </div>
                
                <div class="flex items-center gap-3">
                    <?php if ($canEdit): ?>
                        <button onclick="editProject()" 
                                class="px-4 py-2.5 bg-slate-50 hover:bg-slate-100 text-slate-700 rounded-xl font-medium transition-all border border-slate-200">
                            <i class="fas fa-edit mr-2"></i>Edit Project
                        </button>
                    <?php endif; ?>
                    <button onclick="shareProject()" 
                            class="px-4 py-2.5 bg-blue-50 hover:bg-blue-100 text-blue-700 rounded-xl font-medium transition-all border border-blue-200">
                        <i class="fas fa-share-alt mr-2"></i>Share
                    </button>
                </div>
            </div>
            
            <!-- Project Stats -->
            <div class="grid grid-cols-4 gap-4 pt-4 border-t border-slate-200">
                <div class="text-center">
                    <p class="text-sm text-slate-500 mb-1">Total Tasks</p>
                    <p class="text-2xl font-bold text-slate-900"><?= $project['task_count'] ?></p>
                </div>
                <div class="text-center">
                    <p class="text-sm text-slate-500 mb-1">Completed</p>
                    <p class="text-2xl font-bold text-emerald-600"><?= $project['completed_task_count'] ?></p>
                </div>
                <div class="text-center">
                    <p class="text-sm text-slate-500 mb-1">Progress</p>
                    <p class="text-2xl font-bold text-blue-600">
                        <?= $project['task_count'] > 0 ? round(($project['completed_task_count'] / $project['task_count']) * 100) : 0 ?>%
                    </p>
                </div>
                <div class="text-center">
                    <p class="text-sm text-slate-500 mb-1">Due Date</p>
                    <p class="text-lg font-bold text-slate-900">
                        <?= $project['due_date'] ? date('M j, Y', strtotime($project['due_date'])) : 'Not set' ?>
                    </p>
                </div>
            </div>
        </div>
        
        <!-- Task Board -->
        <div class="flex gap-5 overflow-x-auto pb-6">
            <?php foreach ($tasksByStatus as $statusGroup): 
                $status = $statusGroup['status'];
                $statusTasks = $statusGroup['tasks'];
            ?>
                <div class="flex-shrink-0 w-80">
                    <div class="bg-white rounded-2xl border border-slate-200/60 shadow-sm overflow-hidden">
                        <!-- Column Header -->
                        <div class="p-4 border-b border-slate-200" style="background: linear-gradient(135deg, <?= htmlspecialchars($status['color']) ?>15 0%, <?= htmlspecialchars($status['color']) ?>05 100%)">
                            <div class="flex items-center justify-between mb-2">
                                <div class="flex items-center gap-2">
                                    <div class="w-3 h-3 rounded-full" style="background-color: <?= htmlspecialchars($status['color']) ?>"></div>
                                    <h3 class="font-bold text-slate-900"><?= htmlspecialchars($status['name']) ?></h3>
                                    <span class="px-2 py-0.5 bg-slate-100 text-slate-600 rounded-full text-xs font-semibold">
                                        <?= count($statusTasks) ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Tasks List -->
                        <div class="status-column p-3 space-y-3 max-h-[calc(100vh-400px)] overflow-y-auto" 
                             data-status-id="<?= $status['id'] ?>">
                            <?php foreach ($statusTasks as $task): ?>
                                <div class="task-card bg-white rounded-xl p-4 border border-slate-200 cursor-pointer hover:border-blue-300 transition-all"
                                     data-task-id="<?= $task['id'] ?>"
                                     onclick="openTaskPanel(<?= $task['id'] ?>)">
                                    <div class="flex items-start justify-between mb-2">
                                        <h4 class="font-semibold text-slate-900 flex-1 pr-2"><?= htmlspecialchars($task['title']) ?></h4>
                                        <i class="fas fa-flag <?= $priorityColors[$task['priority']] ?? '' ?> text-sm"></i>
                                    </div>
                                    
                                    <?php if ($task['description']): ?>
                                        <p class="text-sm text-slate-600 mb-3 line-clamp-2"><?= htmlspecialchars($task['description']) ?></p>
                                    <?php endif; ?>
                                    
                                    <div class="flex items-center justify-between text-xs">
                                        <div class="flex items-center gap-2 text-slate-500">
                                            <?php if ($task['comment_count'] > 0): ?>
                                                <span class="flex items-center gap-1">
                                                    <i class="fas fa-comment"></i><?= $task['comment_count'] ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($task['attachment_count'] > 0): ?>
                                                <span class="flex items-center gap-1">
                                                    <i class="fas fa-paperclip"></i><?= $task['attachment_count'] ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($task['due_date']): ?>
                                                <span class="flex items-center gap-1 <?= strtotime($task['due_date']) < time() ? 'text-rose-600 font-semibold' : '' ?>">
                                                    <i class="fas fa-clock"></i><?= date('M j', strtotime($task['due_date'])) ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <?php if (!empty($task['assignees'])): ?>
                                            <div class="flex -space-x-2">
                                                <?php foreach (array_slice($task['assignees'], 0, 3) as $assignee): ?>
                                                    <div class="w-6 h-6 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 text-white flex items-center justify-center text-xs font-semibold border-2 border-white"
                                                         title="<?= htmlspecialchars($assignee['name']) ?>">
                                                        <?= strtoupper(substr($assignee['name'], 0, 1)) ?>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            
                            <!-- Add Task Button -->
                            <?php if ($canCreateTask): ?>
                                <button onclick="event.stopPropagation(); openQuickAddTask(<?= $status['id'] ?>)" 
                                        class="add-task-btn w-full px-4 py-3 bg-slate-50 hover:bg-slate-100 text-slate-600 rounded-xl font-medium transition-all border-2 border-dashed border-slate-200 hover:border-blue-300 hover:text-blue-600">
                                    <i class="fas fa-plus mr-2"></i>Add Task
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </main>
    
    <!-- Task Detail Slide Panel -->
    <div id="taskPanel" class="hidden fixed inset-y-0 right-0 w-full md:w-2/3 lg:w-1/2 xl:w-2/5 bg-white shadow-2xl z-50 overflow-y-auto slide-panel">
        <div class="sticky top-0 bg-gradient-to-r from-blue-600 to-purple-600 px-6 py-5 flex items-center justify-between z-10">
            <h2 class="text-2xl font-bold text-white">Task Details</h2>
            <button onclick="closeTaskPanel()" class="text-white/80 hover:text-white transition-colors">
                <i class="fas fa-times text-2xl"></i>
            </button>
        </div>
        
        <div id="taskPanelContent" class="p-6">
            <!-- Content loaded via AJAX -->
        </div>
    </div>
    
    <!-- Quick Add Task Modal -->
    <div id="quickAddModal" class="hidden fixed inset-0 z-40 overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen px-4 bg-slate-900/50 backdrop-blur-sm">
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full transform transition-all">
                <div class="bg-gradient-to-r from-emerald-600 to-teal-600 px-6 py-4 rounded-t-2xl">
                    <h3 class="text-xl font-bold text-white">Quick Add Task</h3>
                </div>
                
                <form id="quickAddForm" class="p-6 space-y-4">
                    <input type="hidden" name="status_id" id="quickAddStatusId">
                    <input type="hidden" name="project_id" value="<?= $projectId ?>">
                    
                    <div>
                        <input type="text" name="title" required placeholder="Task title..."
                               class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500 text-lg font-medium">
                    </div>
                    
                    <div>
                        <textarea name="description" rows="2" placeholder="Description (optional)"
                                  class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500"></textarea>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-3">
                        <select name="priority" class="px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            <option value="medium">Medium Priority</option>
                            <option value="low">Low Priority</option>
                            <option value="high">High Priority</option>
                            <option value="urgent">Urgent</option>
                        </select>
                        
                        <input type="date" name="due_date"
                               class="px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500">
                    </div>
                    
                    <div class="flex gap-3 pt-2">
                        <button type="submit"
                                class="flex-1 px-6 py-3 bg-gradient-to-r from-emerald-600 to-teal-600 text-white rounded-xl font-semibold hover:shadow-lg transition-all">
                            Create Task
                        </button>
                        <button type="button" onclick="closeQuickAddTask()"
                                class="px-6 py-3 bg-slate-100 text-slate-700 rounded-xl font-semibold hover:bg-slate-200 transition-all">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        // Initialize drag and drop
        document.querySelectorAll('.status-column').forEach(column => {
            new Sortable(column, {
                group: 'tasks',
                animation: 150,
                ghostClass: 'sortable-ghost',
                dragClass: 'sortable-drag',
                onEnd: async function(evt) {
                    const taskId = evt.item.dataset.taskId;
                    const newStatusId = evt.to.dataset.statusId;
                    
                    // Update task status via API
                    try {
                        const response = await fetch('/api/tasks.php', {
                            method: 'PUT',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({
                                id: taskId,
                                status_id: newStatusId
                            })
                        });
                        
                        if (!response.ok) {
                            // Revert if failed
                            evt.from.insertBefore(evt.item, evt.from.children[evt.oldIndex]);
                            alert('Failed to update task');
                        }
                    } catch (error) {
                        evt.from.insertBefore(evt.item, evt.from.children[evt.oldIndex]);
                        alert('Error updating task');
                    }
                }
            });
        });
        
        // Quick add task
        function openQuickAddTask(statusId) {
            document.getElementById('quickAddStatusId').value = statusId;
            document.getElementById('quickAddModal').classList.remove('hidden');
            document.querySelector('#quickAddForm input[name="title"]').focus();
        }
        
        function closeQuickAddTask() {
            document.getElementById('quickAddModal').classList.add('hidden');
            document.getElementById('quickAddForm').reset();
        }
        
        document.getElementById('quickAddForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch('/api/tasks.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                if (result.success) {
                    window.location.reload();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                alert('Error creating task');
            }
        });
        
        // Task panel
        async function openTaskPanel(taskId) {
            document.getElementById('taskPanel').classList.remove('hidden');
            document.getElementById('taskPanelContent').innerHTML = '<div class="text-center py-12"><i class="fas fa-spinner fa-spin text-4xl text-blue-600"></i></div>';
            
            try {
                const response = await fetch(`/api/tasks.php?id=${taskId}`);
                const result = await response.json();
                
                if (result.success) {
                    renderTaskPanel(result.task);
                } else {
                    document.getElementById('taskPanelContent').innerHTML = '<p class="text-rose-600">Error loading task</p>';
                }
            } catch (error) {
                document.getElementById('taskPanelContent').innerHTML = '<p class="text-rose-600">Error loading task</p>';
            }
        }
        
        function closeTaskPanel() {
            document.getElementById('taskPanel').classList.add('hidden');
        }
        
        function renderTaskPanel(task) {
            // This would render the full task details - simplified for now
            document.getElementById('taskPanelContent').innerHTML = `
                <div class="space-y-6">
                    <div>
                        <h3 class="text-2xl font-bold text-slate-900 mb-2">${task.title}</h3>
                        <p class="text-slate-600">${task.description || 'No description'}</p>
                    </div>
                    <div class="flex gap-4">
                        <a href="/task.php?id=${task.id}&project_id=<?= $projectId ?>&workspace=<?= urlencode($company['subdomain']) ?>"
                           class="px-6 py-3 bg-blue-600 text-white rounded-xl font-semibold hover:bg-blue-700 transition-all">
                            Open Full Details
                        </a>
                    </div>
                </div>
            `;
        }
        
        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                closeTaskPanel();
                closeQuickAddTask();
            }
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                if (<?= $canCreateTask ? 'true' : 'false' ?>) {
                    openQuickAddTask(<?= $statuses[0]['id'] ?? 0 ?>);
                }
            }
        });
    </script>
</body>
</html>
