<?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/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'];

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

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
            'category_id' => !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null,
            'client_id' => !empty($_POST['client_id']) ? (int)$_POST['client_id'] : null,
            'status' => $_POST['status'] ?? 'planning',
            'priority' => $_POST['priority'] ?? 'medium',
            'start_date' => !empty($_POST['start_date']) ? $_POST['start_date'] : null,
            'due_date' => !empty($_POST['due_date']) ? $_POST['due_date'] : null,
        ];
        
        if (empty($data['name'])) {
            throw new Exception('Project name is required');
        }
        
        $projectId = ProjectManager::createProject($companyId, $userId, $data);
        
        header('Location: /project.php?id=' . $projectId . '&workspace=' . urlencode($company['subdomain']));
        exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get categories and clients
$categories = ProjectManager::getCategories($companyId);
$clientStmt = $pdo->prepare('SELECT id, name FROM clients WHERE company_id = ? ORDER BY name ASC');
$clientStmt->execute([$companyId]);
$clients = $clientStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$pageTitle = 'Create Project';
?>
<!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="/projects.php?workspace=<?= urlencode($company['subdomain']) ?>" class="text-blue-600 hover:text-blue-700">
                <i class="fas fa-arrow-left"></i> Back to Projects
            </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">Project Name *</label>
                    <input type="text" name="name" 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 project name">
                </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 project 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">Category</label>
                        <select name="category_id"
                                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="">No category</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?= $category['id'] ?>"><?= htmlspecialchars($category['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Client</label>
                        <select name="client_id"
                                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="">No client</option>
                            <?php foreach ($clients as $client): ?>
                                <option value="<?= $client['id'] ?>"><?= htmlspecialchars($client['name']) ?></option>
                            <?php endforeach; ?>
                        </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">Status</label>
                        <select name="status"
                                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="planning">Planning</option>
                            <option value="active">Active</option>
                            <option value="on_hold">On Hold</option>
                            <option value="completed">Completed</option>
                            <option value="archived">Archived</option>
                        </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">Start Date</label>
                        <input type="date" name="start_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">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>
                
                <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 Project
                    </button>
                    <a href="/projects.php?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>
