<?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) {
    header('Location: /workspace-plans.php');
    exit;
}

$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['subdomain']));
    exit;
}

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

$projectId = $projectId ?: (int)$task['project_id'];

// 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('tasks_edit');
$canDelete = $hasPermission('tasks_delete');

$error = '';
$success = '';

// Handle task update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        switch ($_POST['action']) {
            case 'update_task':
                if (!$canEdit) throw new Exception('Permission denied');
                
                $data = [
                    'title' => trim($_POST['title'] ?? ''),
                    'description' => trim($_POST['description'] ?? ''),
                    'status_id' => !empty($_POST['status_id']) ? (int)$_POST['status_id'] : null,
                    'priority' => $_POST['priority'] ?? 'medium',
                    'due_date' => !empty($_POST['due_date']) ? $_POST['due_date'] . ' 23:59:59' : null,
                    'estimated_hours' => !empty($_POST['estimated_hours']) ? (float)$_POST['estimated_hours'] : null,
                    'actual_hours' => !empty($_POST['actual_hours']) ? (float)$_POST['actual_hours'] : null,
                ];
                
                TaskManager::updateTask($taskId, $companyId, $userId, $data);
                $success = 'Task updated successfully';
                $task = TaskManager::getTask($taskId, $companyId);
                break;
                
            case 'add_comment':
                $comment = trim($_POST['comment'] ?? '');
                if (empty($comment)) throw new Exception('Comment cannot be empty');
                
                TaskManager::addComment($taskId, $userId, $comment);
                $success = 'Comment added';
                $task = TaskManager::getTask($taskId, $companyId);
                break;
                
            case 'upload_attachment':
                if (!isset($_FILES['attachment'])) throw new Exception('No file uploaded');
                
                $attachmentId = TaskManager::addAttachment($taskId, $companyId, $userId, $_FILES['attachment']);
                if (!$attachmentId) throw new Exception('Failed to upload file');
                
                $success = 'File uploaded successfully';
                $task = TaskManager::getTask($taskId, $companyId);
                break;
                
            case 'assign_user':
                if (!$hasPermission('tasks_assign')) throw new Exception('Permission denied');
                
                $assignUserId = (int)$_POST['user_id'];
                TaskManager::assignTask($taskId, $assignUserId, $userId);
                $success = 'User assigned';
                $task = TaskManager::getTask($taskId, $companyId);
                break;
                
            case 'unassign_user':
                if (!$hasPermission('tasks_assign')) throw new Exception('Permission denied');
                
                $unassignUserId = (int)$_POST['user_id'];
                TaskManager::unassignTask($taskId, $unassignUserId);
                $success = 'User unassigned';
                $task = TaskManager::getTask($taskId, $companyId);
                break;
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get statuses and members
$statuses = TaskManager::getStatuses($companyId);
$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) ?: [];

$assignedUserIds = array_column($task['assignees'] ?? [], 'user_id');

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

$pageTitle = htmlspecialchars($task['title']);
?>
<!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>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-slate-50">
    <?php renderNavigation($company, $user, 'Projects'); ?>
    
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div class="mb-6">
            <a href="/project.php?id=<?= $projectId ?>&workspace=<?= urlencode($company['subdomain']) ?>" class="text-blue-600 hover:text-blue-700">
                <i class="fas fa-arrow-left"></i> Back to <?= htmlspecialchars($task['project_name'] ?? 'Project') ?>
            </a>
        </div>
        
        <?php if ($error): ?>
            <div class="bg-rose-50 border border-rose-200 rounded-lg p-4 mb-6">
                <p class="text-sm text-rose-700"><?= htmlspecialchars($error) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="bg-emerald-50 border border-emerald-200 rounded-lg p-4 mb-6">
                <p class="text-sm text-emerald-700"><?= htmlspecialchars($success) ?></p>
            </div>
        <?php endif; ?>
        
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Main Content -->
            <div class="lg:col-span-2 space-y-6">
                <!-- Task Details -->
                <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <form method="POST" class="space-y-6">
                        <input type="hidden" name="action" value="update_task">
                        
                        <div class="flex items-start justify-between gap-4">
                            <div class="flex-1">
                                <input type="text" name="title" value="<?= htmlspecialchars($task['title']) ?>" <?= !$canEdit ? 'readonly' : '' ?>
                                       class="text-2xl font-bold text-slate-900 w-full border-0 border-b-2 border-transparent hover:border-slate-300 focus:border-blue-500 focus:outline-none px-0 py-2">
                            </div>
                            <i class="fas fa-flag <?= $priorityColors[$task['priority']] ?? '' ?> text-xl mt-2"></i>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-slate-700 mb-2">Description</label>
                            <textarea name="description" rows="6" <?= !$canEdit ? 'readonly' : '' ?>
                                      class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"><?= htmlspecialchars($task['description'] ?? '') ?></textarea>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Status</label>
                                <select name="status_id" <?= !$canEdit ? 'disabled' : '' ?>
                                        class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <?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-2">Priority</label>
                                <select name="priority" <?= !$canEdit ? 'disabled' : '' ?>
                                        class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <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>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Due Date</label>
                                <input type="date" name="due_date" <?= !$canEdit ? 'readonly' : '' ?>
                                       value="<?= $task['due_date'] ? date('Y-m-d', strtotime($task['due_date'])) : '' ?>"
                                       class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Estimated Hours</label>
                                <input type="number" name="estimated_hours" step="0.5" min="0" <?= !$canEdit ? 'readonly' : '' ?>
                                       value="<?= $task['estimated_hours'] ?? '' ?>"
                                       class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-slate-700 mb-2">Actual Hours</label>
                                <input type="number" name="actual_hours" step="0.5" min="0" <?= !$canEdit ? 'readonly' : '' ?>
                                       value="<?= $task['actual_hours'] ?? '' ?>"
                                       class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        
                        <?php if ($canEdit): ?>
                            <div class="flex items-center gap-4 pt-4 border-t border-slate-200">
                                <button type="submit"
                                        class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                                    Save Changes
                                </button>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
                
                <!-- Comments -->
                <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <h2 class="text-xl font-bold text-slate-900 mb-4">Comments</h2>
                    
                    <form method="POST" class="mb-6">
                        <input type="hidden" name="action" value="add_comment">
                        <textarea name="comment" rows="3" required
                                  class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2"
                                  placeholder="Add a comment..."></textarea>
                        <button type="submit"
                                class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                            Add Comment
                        </button>
                    </form>
                    
                    <div class="space-y-4">
                        <?php if (empty($task['comments'])): ?>
                            <p class="text-slate-500 text-center py-8">No comments yet</p>
                        <?php else: ?>
                            <?php foreach ($task['comments'] as $comment): ?>
                                <div class="border border-slate-200 rounded-lg p-4">
                                    <div class="flex items-start gap-3">
                                        <div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center text-sm font-medium flex-shrink-0">
                                            <?= strtoupper(substr($comment['user_name'], 0, 1)) ?>
                                        </div>
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2 mb-1">
                                                <span class="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-slate-700"><?= nl2br(htmlspecialchars($comment['comment'])) ?></p>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Attachments -->
                <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <h2 class="text-xl font-bold text-slate-900 mb-4">Attachments</h2>
                    
                    <form method="POST" enctype="multipart/form-data" class="mb-6">
                        <input type="hidden" name="action" value="upload_attachment">
                        <div class="flex items-center gap-2">
                            <input type="file" name="attachment" required
                                   class="flex-1 px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <button type="submit"
                                    class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                                Upload
                            </button>
                        </div>
                    </form>
                    
                    <div class="space-y-2">
                        <?php if (empty($task['attachments'])): ?>
                            <p class="text-slate-500 text-center py-8">No attachments</p>
                        <?php else: ?>
                            <?php foreach ($task['attachments'] as $attachment): ?>
                                <div class="flex items-center justify-between p-3 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">
                                                Uploaded by <?= htmlspecialchars($attachment['uploaded_by_name']) ?> 
                                                on <?= date('M j, Y', strtotime($attachment['created_at'])) ?>
                                            </p>
                                        </div>
                                    </div>
                                    <a href="/download.php?file=<?= urlencode($attachment['file_path']) ?>" 
                                       class="text-blue-600 hover:text-blue-700">
                                        <i class="fas fa-download"></i>
                                    </a>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Sidebar -->
            <div class="space-y-6">
                <!-- Assignees -->
                <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <h3 class="text-lg font-bold text-slate-900 mb-4">Assignees</h3>
                    
                    <div class="space-y-2 mb-4">
                        <?php if (empty($task['assignees'])): ?>
                            <p class="text-sm text-slate-500">No one assigned</p>
                        <?php else: ?>
                            <?php foreach ($task['assignees'] as $assignee): ?>
                                <div class="flex items-center justify-between p-2 rounded-lg hover:bg-slate-50">
                                    <div class="flex items-center gap-2">
                                        <div class="w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center text-sm font-medium">
                                            <?= strtoupper(substr($assignee['name'], 0, 1)) ?>
                                        </div>
                                        <span class="text-sm font-medium text-slate-900"><?= htmlspecialchars($assignee['name']) ?></span>
                                    </div>
                                    <?php if ($hasPermission('tasks_assign')): ?>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="unassign_user">
                                            <input type="hidden" name="user_id" value="<?= $assignee['user_id'] ?>">
                                            <button type="submit" class="text-slate-400 hover:text-rose-600">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($hasPermission('tasks_assign')): ?>
                        <form method="POST">
                            <input type="hidden" name="action" value="assign_user">
                            <select name="user_id" required
                                    class="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2">
                                <option value="">Select member...</option>
                                <?php foreach ($members as $member): ?>
                                    <?php if (!in_array($member['id'], $assignedUserIds)): ?>
                                        <option value="<?= $member['id'] ?>"><?= htmlspecialchars($member['name']) ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit"
                                    class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                                Assign Member
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
                
                <!-- Task Info -->
                <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <h3 class="text-lg font-bold text-slate-900 mb-4">Task Info</h3>
                    
                    <div class="space-y-3 text-sm">
                        <div>
                            <p class="text-slate-500">Created by</p>
                            <p class="font-medium text-slate-900"><?= htmlspecialchars($task['created_by_name'] ?? 'Unknown') ?></p>
                        </div>
                        
                        <div>
                            <p class="text-slate-500">Created at</p>
                            <p class="font-medium text-slate-900"><?= date('M j, Y g:i A', strtotime($task['created_at'])) ?></p>
                        </div>
                        
                        <?php if ($task['updated_at'] && $task['updated_at'] !== $task['created_at']): ?>
                            <div>
                                <p class="text-slate-500">Last updated</p>
                                <p class="font-medium text-slate-900"><?= date('M j, Y g:i A', strtotime($task['updated_at'])) ?></p>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($task['completed_at']): ?>
                            <div>
                                <p class="text-slate-500">Completed at</p>
                                <p class="font-medium text-emerald-600"><?= date('M j, Y g:i A', strtotime($task['completed_at'])) ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </main>
</body>
</html>
