<?php
/**
 * Create Project
 * LandSales Pro - Add new land development project
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];

// Check plan limit
$projectLimit = checkPlanLimit($userId, 'projects');
if (!$projectLimit['allowed']) {
    setFlashMessage('error', 'You have reached your project limit. Please upgrade your plan.');
    header('Location: index.php');
    exit;
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $totalArea = floatval($_POST['total_area'] ?? 0);
    $areaUnit = $_POST['area_unit'] ?? 'sqm';

    // Validation
    if (empty($name)) $errors[] = "Project name is required";
    if (strlen($name) > 255) $errors[] = "Project name is too long";

    if (empty($errors)) {
        $sql = "INSERT INTO projects (user_id, name, location, description, total_area, area_unit)
                VALUES (?, ?, ?, ?, ?, ?)";

        if (db_execute($sql, 'isssds', [$userId, $name, $location, $description, $totalArea, $areaUnit])) {
            $projectId = db_last_id();
            logActivity('project_created', "Created project: {$name}");
            setFlashMessage('success', 'Project created successfully!');
            header('Location: view.php?id=' . $projectId);
            exit;
        } else {
            $errors[] = "Failed to create project. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Project - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Create Project</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-project-diagram"></i> Project Details</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label for="name">Project Name *</label>
                            <input type="text" name="name" id="name" class="form-control"
                                   value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>"
                                   placeholder="e.g., Green Valley Estate" required>
                        </div>

                        <div class="form-group">
                            <label for="location">Location</label>
                            <input type="text" name="location" id="location" class="form-control"
                                   value="<?php echo htmlspecialchars($_POST['location'] ?? ''); ?>"
                                   placeholder="e.g., Kigamboni, Dar es Salaam">
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="total_area">Total Area</label>
                                <input type="number" name="total_area" id="total_area" class="form-control"
                                       value="<?php echo $_POST['total_area'] ?? ''; ?>"
                                       placeholder="e.g., 50000" step="0.01" min="0">
                            </div>
                            <div class="form-group">
                                <label for="area_unit">Unit</label>
                                <select name="area_unit" id="area_unit" class="form-control">
                                    <option value="sqm" <?php echo ($_POST['area_unit'] ?? '') === 'sqm' ? 'selected' : ''; ?>>Square Meters (sqm)</option>
                                    <option value="acres" <?php echo ($_POST['area_unit'] ?? '') === 'acres' ? 'selected' : ''; ?>>Acres</option>
                                    <option value="hectares" <?php echo ($_POST['area_unit'] ?? '') === 'hectares' ? 'selected' : ''; ?>>Hectares</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea name="description" id="description" class="form-control" rows="4"
                                      placeholder="Brief description of the project..."><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="index.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Create Project
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions { display: flex; gap: 0.75rem; }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-outline {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
        }

        .form-container { max-width: 600px; }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            gap: 0.75rem;
        }

        .alert-danger {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #991b1b;
        }

        .alert ul { margin: 0; padding-left: 1rem; }

        .card {
            background: white;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
        }

        .card-header h3 {
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-header h3 i { color: #667eea; }

        .card-body { padding: 1.5rem; }

        .card-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
        }

        .form-row {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 1rem;
        }

        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
            font-size: 0.875rem;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: all 0.2s;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        textarea.form-control { resize: vertical; min-height: 100px; }

        @media (max-width: 576px) {
            .form-row { grid-template-columns: 1fr; }
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
        }
    </style>
</body>
</html>
