<?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'];
$projectId = (int)($_GET['project_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;
}

// Check permission
if (!PermissionManager::isOwner($userId, $companyId) && !PermissionManager::hasPermission($userId, $companyId, 'tasks_create')) {
    header('Location: /project.php?id=' . $projectId . '&workspace=' . urlencode($company['subdomain']));
    exit;
}

$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $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,
            'assignees' => $_POST['assignees'] ?? [],
        ];
        
        if (empty($data['title'])) {
            throw new Exception('Task title is required');
        }
        
        $taskId = TaskManager::createTask($projectId, $companyId, $userId, $data);
        
        header('Location: /task.php?id=' . $taskId . '&project_id=' . $projectId . '&workspace=' . urlencode($company['subdomain']));
        exit;
    } 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) ?: [];

$pageTitle = 'Create Task';
?>
<!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">
</head>
<body class="bg-slate-50">
    <?php renderNavigation($company, $user, 'Projects'); ?>
    
    <main class="max-w-4xl 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($project['name']) ?>
            </a>
        </div>
        
        <div class="bg-white rounded-2xl p-8 border border-slate-200 shadow-sm">
            <h1 class="text-3xl font-bold text-slate-900 mb-6"><?= $pageTitle ?></h1>
            
            <?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; ?>
            
            <form method="POST" class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Task Title *</label>
                    <input type="text" name="title" required
                           class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                           placeholder="Enter task title">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Description</label>
                    <textarea name="description" rows="4"
                              class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                              placeholder="Enter task description"></textarea>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Status</label>
                        <select name="status_id"
                                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'] ?>" <?= $status['is_default'] ? '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"
                                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">Low</option>
                            <option value="medium" selected>Medium</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Due Date</label>
                        <input type="date" name="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"
                               class="w-full px-4 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                               placeholder="0.0">
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">Assign To</label>
                    <div class="border border-slate-300 rounded-lg p-4 max-h-60 overflow-y-auto">
                        <?php foreach ($members as $member): ?>
                            <label class="flex items-center gap-3 py-2 hover:bg-slate-50 rounded px-2 cursor-pointer">
                                <input type="checkbox" name="assignees[]" value="<?= $member['id'] ?>"
                                       class="w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500">
                                <div class="flex-1">
                                    <p class="text-sm font-medium text-slate-900"><?= htmlspecialchars($member['name']) ?></p>
                                    <p class="text-xs text-slate-500"><?= htmlspecialchars($member['email']) ?></p>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="flex items-center gap-4 pt-4">
                    <button type="submit"
                            class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors">
                        Create Task
                    </button>
                    <a href="/project.php?id=<?= $projectId ?>&workspace=<?= urlencode($company['subdomain']) ?>"
                       class="px-6 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg font-medium transition-colors">
                        Cancel
                    </a>
                </div>
            </form>
        </div>
    </main>
</body>
</html>
