<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';
require_once __DIR__ . '/navigation.php';

requirePermission('tasks_view');

$canEdit = hasPermission('tasks_edit');
$canAssign = hasPermission('tasks_assign');

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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_task' && $canEdit) {
        $updates = [
            'title' => $_POST['title'] ?? '',
            'description' => $_POST['description'] ?? '',
            'status_id' => (int)($_POST['status_id'] ?? 0),
            'priority' => $_POST['priority'] ?? 'medium',
            'due_date' => $_POST['due_date'] ?? null,
            'estimated_hours' => !empty($_POST['estimated_hours']) ? (float)$_POST['estimated_hours'] : null
        ];
        TaskManager::updateTask($taskId, $companyId, $userId, $updates);
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'add_comment') {
        TaskManager::addComment($taskId, $companyId, $userId, $_POST['comment'] ?? '');
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'upload_attachment' && !empty($_FILES['file']['name'])) {
        $uploadDir = __DIR__ . '/../storage/companies/' . $companyId . '/project-attachments/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        $fileName = time() . '_' . basename($_FILES['file']['name']);
        $filePath = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
            TaskManager::addAttachment($taskId, $companyId, $userId, $_FILES['file']['name'], $fileName, $_FILES['file']['size']);
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'assign_user' && $canAssign) {
        $assignUserId = (int)($_POST['user_id'] ?? 0);
        if ($assignUserId) {
            TaskManager::assignUser($taskId, $assignUserId, $companyId, $userId);
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
    
    if ($action === 'unassign_user' && $canAssign) {
        $assignUserId = (int)($_POST['user_id'] ?? 0);
        if ($assignUserId) {
            TaskManager::unassignUser($taskId, $assignUserId, $companyId, $userId);
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Get task data
$task = TaskManager::getTask($taskId, $companyId);
if (!$task) {
    header('Location: /projects.php?workspace=' . urlencode($company['username'] ?? ''));
    exit;
}

$project = ProjectManager::getProject($task['project_id'], $companyId);
$statuses = TaskManager::getStatuses($companyId);
$comments = TaskManager::getComments($taskId, $companyId);
$attachments = TaskManager::getAttachments($taskId, $companyId);
$assignees = TaskManager::getAssignees($taskId, $companyId);

// Get available members
$pdo = getPDO();
$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) ?: [];

$workspace = $company['username'] ?? $company['subdomain'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($task['title']) ?> - <?= 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">
</head>
<body class="bg-slate-100 min-h-screen">
<div class="min-h-screen flex flex-col">
<?php renderNavigation(); ?>

<main class="flex-1">
    <div class="max-w-5xl mx-auto px-4 py-6 space-y-6">
        
        <!-- Breadcrumb -->
        <div class="flex items-center gap-2 text-sm text-slate-600">
            <a href="/projects.php?workspace=<?= urlencode($workspace) ?>" class="hover:text-slate-900">Projects</a>
            <i class="fas fa-chevron-right text-xs"></i>
            <a href="/projects.php?workspace=<?= urlencode($workspace) ?>&project=<?= $project['id'] ?>" class="hover:text-slate-900">
                <?= htmlspecialchars($project['name']) ?>
            </a>
            <i class="fas fa-chevron-right text-xs"></i>
            <span class="text-slate-900"><?= htmlspecialchars($task['title']) ?></span>
        </div>

        <!-- Task Header -->
        <div class="bg-white border border-slate-200 rounded-lg p-4">
            <form method="POST" class="space-y-4">
                <input type="hidden" name="action" value="update_task">
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">Task Title</label>
                    <input type="text" name="title" value="<?= htmlspecialchars($task['title']) ?>" 
                           <?= $canEdit ? '' : 'readonly' ?>
                           class="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">Description</label>
                    <textarea name="description" rows="4" 
                              <?= $canEdit ? '' : 'readonly' ?>
                              class="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>"><?= htmlspecialchars($task['description'] ?? '') ?></textarea>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Status</label>
                        <select name="status_id" <?= $canEdit ? '' : 'disabled' ?>
                                class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>">
                            <?php foreach ($statuses as $status): ?>
                                <option value="<?= $status['id'] ?>" <?= $task['status_id'] == $status['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($status['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Priority</label>
                        <select name="priority" <?= $canEdit ? '' : 'disabled' ?>
                                class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>">
                            <option value="low" <?= $task['priority'] === 'low' ? 'selected' : '' ?>>Low</option>
                            <option value="medium" <?= $task['priority'] === 'medium' ? 'selected' : '' ?>>Medium</option>
                            <option value="high" <?= $task['priority'] === 'high' ? 'selected' : '' ?>>High</option>
                            <option value="urgent" <?= $task['priority'] === 'urgent' ? 'selected' : '' ?>>Urgent</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Due Date</label>
                        <input type="date" name="due_date" value="<?= $task['due_date'] ?? '' ?>" 
                               <?= $canEdit ? '' : 'readonly' ?>
                               class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Est. Hours</label>
                        <input type="number" name="estimated_hours" step="0.5" value="<?= $task['estimated_hours'] ?? '' ?>" 
                               <?= $canEdit ? '' : 'readonly' ?>
                               class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 <?= $canEdit ? '' : 'bg-slate-50' ?>">
                    </div>
                </div>
                
                <?php if ($canEdit): ?>
                    <div class="flex items-center gap-3 pt-2 border-t border-slate-200">
                        <button type="submit" class="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-700">
                            <i class="fas fa-save mr-1"></i>Save Changes
                        </button>
                    </div>
                <?php endif; ?>
            </form>
        </div>

        <!-- Assignees -->
        <div class="bg-white border border-slate-200 rounded-lg p-4">
            <h2 class="text-base font-semibold text-slate-900 mb-3">Assigned To</h2>
            
            <?php if (empty($assignees)): ?>
                <p class="text-sm text-slate-500 mb-3">No one assigned yet</p>
            <?php else: ?>
                <div class="flex flex-wrap gap-2 mb-3">
                    <?php foreach ($assignees as $assignee): ?>
                        <div class="inline-flex items-center gap-2 px-3 py-1.5 bg-blue-50 text-blue-700 rounded-lg text-sm">
                            <span class="font-medium"><?= htmlspecialchars($assignee['name']) ?></span>
                            <?php if ($canAssign): ?>
                                <form method="POST" class="inline">
                                    <input type="hidden" name="action" value="unassign_user">
                                    <input type="hidden" name="user_id" value="<?= $assignee['id'] ?>">
                                    <button type="submit" class="text-blue-600 hover:text-blue-800">
                                        <i class="fas fa-times text-xs"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($canAssign): ?>
                <form method="POST" class="flex gap-2">
                    <input type="hidden" name="action" value="assign_user">
                    <select name="user_id" class="flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">Select member...</option>
                        <?php foreach ($members as $member): ?>
                            <?php if (!in_array($member['id'], array_column($assignees, 'id'))): ?>
                                <option value="<?= $member['id'] ?>"><?= htmlspecialchars($member['name']) ?></option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700">
                        <i class="fas fa-plus mr-1"></i>Assign
                    </button>
                </form>
            <?php endif; ?>
        </div>

        <!-- Attachments -->
        <div class="bg-white border border-slate-200 rounded-lg p-4">
            <h2 class="text-base font-semibold text-slate-900 mb-3">Attachments</h2>
            
            <?php if (empty($attachments)): ?>
                <p class="text-sm text-slate-500 mb-3">No attachments yet</p>
            <?php else: ?>
                <div class="space-y-2 mb-3">
                    <?php foreach ($attachments as $attachment): ?>
                        <div class="flex items-center justify-between p-2 border border-slate-200 rounded-lg hover:bg-slate-50">
                            <div class="flex items-center gap-3">
                                <i class="fas fa-file text-slate-400"></i>
                                <div>
                                    <p class="text-sm font-medium text-slate-900"><?= htmlspecialchars($attachment['original_filename']) ?></p>
                                    <p class="text-xs text-slate-500">
                                        <?= number_format($attachment['file_size'] / 1024, 1) ?> KB • 
                                        <?= date('M j, Y', strtotime($attachment['uploaded_at'])) ?>
                                    </p>
                                </div>
                            </div>
                            <a href="/storage/companies/<?= $companyId ?>/project-attachments/<?= htmlspecialchars($attachment['file_path']) ?>" 
                               download class="px-3 py-1.5 text-sm border border-slate-200 rounded-lg hover:bg-slate-50">
                                <i class="fas fa-download"></i>
                            </a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data" class="flex gap-2">
                <input type="hidden" name="action" value="upload_attachment">
                <input type="file" name="file" required
                       class="flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700">
                    <i class="fas fa-upload mr-1"></i>Upload
                </button>
            </form>
        </div>

        <!-- Comments -->
        <div class="bg-white border border-slate-200 rounded-lg p-4">
            <h2 class="text-base font-semibold text-slate-900 mb-3">Comments</h2>
            
            <?php if (empty($comments)): ?>
                <p class="text-sm text-slate-500 mb-4">No comments yet</p>
            <?php else: ?>
                <div class="space-y-3 mb-4">
                    <?php foreach ($comments as $comment): ?>
                        <div class="border border-slate-200 rounded-lg p-3">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-medium text-slate-900"><?= htmlspecialchars($comment['user_name']) ?></span>
                                <span class="text-xs text-slate-500"><?= date('M j, Y g:i A', strtotime($comment['created_at'])) ?></span>
                            </div>
                            <p class="text-sm text-slate-700"><?= nl2br(htmlspecialchars($comment['comment'])) ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" class="space-y-2">
                <input type="hidden" name="action" value="add_comment">
                <textarea name="comment" rows="3" required placeholder="Add a comment..."
                          class="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                <button type="submit" class="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-700">
                    <i class="fas fa-comment mr-1"></i>Add Comment
                </button>
            </form>
        </div>

    </div>
</main>

</div>
</body>
</html>
