<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';

// Get public token
$token = $_GET['token'] ?? '';

if (!$token) {
    http_response_code(404);
    echo 'Invalid link';
    exit;
}

// Get project by public token
$project = ProjectManager::getProjectByPublicToken($token);

if (!$project) {
    http_response_code(404);
    echo 'Project not found or link is disabled';
    exit;
}

$projectId = (int)$project['id'];
$companyId = (int)$project['company_id'];

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

// 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;
    }
}

$statusColors = [
    'planning' => 'bg-slate-100 text-slate-700',
    'active' => 'bg-emerald-100 text-emerald-700',
    'on_hold' => 'bg-amber-100 text-amber-700',
    'completed' => 'bg-blue-100 text-blue-700',
    'archived' => 'bg-slate-100 text-slate-500'
];

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

// Calculate progress
$totalTasks = count($tasks);
$completedTasks = 0;
foreach ($tasks as $task) {
    if ($task['is_completed']) {
        $completedTasks++;
    }
}
$progress = $totalTasks > 0 ? round(($completedTasks / $totalTasks) * 100) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($project['name']) ?> - <?= htmlspecialchars($project['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-50">
    <!-- Header -->
    <header class="bg-white border-b border-slate-200 sticky top-0 z-10">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-bold text-slate-900"><?= htmlspecialchars($project['name']) ?></h1>
                    <p class="text-sm text-slate-600"><?= htmlspecialchars($project['company_name']) ?></p>
                </div>
                <div class="flex items-center gap-2">
                    <span class="px-3 py-1.5 rounded-lg text-sm font-medium <?= $statusColors[$project['status']] ?? '' ?>">
                        <?= ucfirst($project['status']) ?>
                    </span>
                    <span class="text-sm text-slate-500">
                        <i class="fas fa-eye"></i> Read-only view
                    </span>
                </div>
            </div>
        </div>
    </header>
    
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Project Info -->
        <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm mb-8">
            <?php if ($project['description']): ?>
                <div class="mb-6">
                    <h2 class="text-sm font-semibold text-slate-500 uppercase mb-2">Description</h2>
                    <p class="text-slate-700"><?= nl2br(htmlspecialchars($project['description'])) ?></p>
                </div>
            <?php endif; ?>
            
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <div>
                    <p class="text-sm text-slate-500 mb-1">Progress</p>
                    <div class="flex items-center gap-3">
                        <div class="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full bg-blue-600 transition-all" style="width: <?= $progress ?>%"></div>
                        </div>
                        <span class="text-sm font-semibold text-slate-900"><?= $progress ?>%</span>
                    </div>
                </div>
                
                <?php if ($project['client_name']): ?>
                    <div>
                        <p class="text-sm text-slate-500 mb-1">Client</p>
                        <p class="font-medium text-slate-900"><?= htmlspecialchars($project['client_name']) ?></p>
                    </div>
                <?php endif; ?>
                
                <?php if ($project['start_date']): ?>
                    <div>
                        <p class="text-sm text-slate-500 mb-1">Start Date</p>
                        <p class="font-medium text-slate-900"><?= date('M j, Y', strtotime($project['start_date'])) ?></p>
                    </div>
                <?php endif; ?>
                
                <?php if ($project['due_date']): ?>
                    <div>
                        <p class="text-sm text-slate-500 mb-1">Due Date</p>
                        <p class="font-medium text-slate-900"><?= date('M j, Y', strtotime($project['due_date'])) ?></p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Task Board -->
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-slate-900 mb-4">Tasks</h2>
            
            <div class="flex gap-4 overflow-x-auto pb-4">
                <?php foreach ($tasksByStatus as $statusGroup): 
                    $status = $statusGroup['status'];
                    $statusTasks = $statusGroup['tasks'];
                ?>
                    <div class="flex-shrink-0 w-80">
                        <div class="bg-white rounded-xl border border-slate-200 shadow-sm">
                            <div class="p-4 border-b border-slate-200">
                                <div class="flex items-center justify-between">
                                    <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-semibold text-slate-900"><?= htmlspecialchars($status['name']) ?></h3>
                                        <span class="text-sm text-slate-500"><?= count($statusTasks) ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="p-4 space-y-3 max-h-[600px] overflow-y-auto">
                                <?php if (empty($statusTasks)): ?>
                                    <p class="text-sm text-slate-400 text-center py-8">No tasks</p>
                                <?php else: ?>
                                    <?php foreach ($statusTasks as $task): ?>
                                        <div class="bg-slate-50 rounded-lg p-4 border border-slate-200">
                                            <div class="flex items-start justify-between mb-2">
                                                <h4 class="font-medium text-slate-900 flex-1"><?= 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"><?= nl2br(htmlspecialchars($task['description'])) ?></p>
                                            <?php endif; ?>
                                            
                                            <div class="flex items-center justify-between text-xs text-slate-500">
                                                <div class="flex items-center gap-2">
                                                    <?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; ?>
                                                </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-blue-600 text-white flex items-center justify-center text-xs font-medium border-2 border-white"
                                                                 title="<?= htmlspecialchars($assignee['name']) ?>">
                                                                <?= strtoupper(substr($assignee['name'], 0, 1)) ?>
                                                            </div>
                                                        <?php endforeach; ?>
                                                        <?php if (count($task['assignees']) > 3): ?>
                                                            <div class="w-6 h-6 rounded-full bg-slate-400 text-white flex items-center justify-center text-xs font-medium border-2 border-white">
                                                                +<?= count($task['assignees']) - 3 ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <?php if ($task['due_date']): ?>
                                                <div class="mt-2 pt-2 border-t border-slate-200">
                                                    <span class="text-xs text-slate-500">
                                                        <i class="fas fa-clock"></i>
                                                        <?= date('M j, Y', strtotime($task['due_date'])) ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="text-center text-sm text-slate-500 mt-12 pb-8">
            <p>Powered by <?= htmlspecialchars($project['company_name']) ?></p>
            <p class="mt-1">This is a read-only view. Contact the project owner for access.</p>
        </div>
    </main>
</body>
</html>
