<?php
/**
 * Edit Project
 * LandSales Pro - Update project details
 */
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'];
$projectId = intval($_GET['id'] ?? 0);

// Get project
$project = db_fetch_one("SELECT * FROM projects WHERE id = ? AND user_id = ?", 'ii', [$projectId, $userId]);

if (!$project) {
    header('Location: index.php');
    exit;
}

$errors = [];
$success = false;

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';
    $status = $_POST['status'] ?? 'active';

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

    if (empty($errors)) {
        $sql = "UPDATE projects SET name = ?, location = ?, description = ?, total_area = ?, area_unit = ?, status = ? WHERE id = ? AND user_id = ?";

        if (db_execute($sql, 'sssdssii', [$name, $location, $description, $totalArea, $areaUnit, $status, $projectId, $userId])) {
            setFlashMessage('Project updated successfully!', 'success');
            header('Location: view.php?id=' . $projectId);
            exit;
        } else {
            $errors[] = "Failed to update 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>Edit 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">Edit Project</h1>
            <div class="header-actions">
                <a href="view.php?id=<?php echo $projectId; ?>" 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'] ?? $project['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'] ?? $project['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'] ?? $project['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">
                                    <?php $unit = $_POST['area_unit'] ?? $project['area_unit']; ?>
                                    <option value="sqm" <?php echo $unit === 'sqm' ? 'selected' : ''; ?>>Square Meters (sqm)</option>
                                    <option value="acres" <?php echo $unit === 'acres' ? 'selected' : ''; ?>>Acres</option>
                                    <option value="hectares" <?php echo $unit === 'hectares' ? 'selected' : ''; ?>>Hectares</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="status">Status</label>
                            <select name="status" id="status" class="form-control">
                                <?php $status = $_POST['status'] ?? $project['status']; ?>
                                <option value="planning" <?php echo $status === 'planning' ? 'selected' : ''; ?>>Planning</option>
                                <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            </select>
                        </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'] ?? $project['description']); ?></textarea>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="view.php?id=<?php echo $projectId; ?>" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Changes
                        </button>
                    </div>
                </form>

                <!-- Danger Zone -->
                <div class="card danger-zone">
                    <div class="card-header">
                        <h3><i class="fas fa-exclamation-triangle"></i> Danger Zone</h3>
                    </div>
                    <div class="card-body">
                        <div class="danger-item">
                            <div>
                                <strong>Delete this project</strong>
                                <p>Once deleted, all plots and sales data will be permanently removed.</p>
                            </div>
                            <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                                <i class="fas fa-trash"></i> Delete Project
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal-overlay" id="deleteModal">
        <div class="modal">
            <div class="modal-header">
                <h3><i class="fas fa-exclamation-triangle"></i> Delete Project</h3>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete <strong><?php echo htmlspecialchars($project['name']); ?></strong>?</p>
                <p class="text-danger">This will permanently delete all plots, sales, and payment records associated with this project.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <a href="delete.php?id=<?php echo $projectId; ?>&confirm=1" class="btn btn-danger">
                    <i class="fas fa-trash"></i> Yes, Delete
                </a>
            </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;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }

        .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;
            margin-bottom: 1.5rem;
        }

        .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;
            box-sizing: border-box;
        }

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

        /* Danger Zone */
        .danger-zone .card-header {
            background: #fef2f2;
            border-bottom-color: #fecaca;
        }

        .danger-zone .card-header h3 { color: #991b1b; }
        .danger-zone .card-header h3 i { color: #ef4444; }

        .danger-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
        }

        .danger-item p {
            margin: 0.25rem 0 0;
            font-size: 0.85rem;
            color: #64748b;
        }

        /* Modal */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 2000;
        }

        .modal-overlay.active { display: flex; }

        .modal {
            background: white;
            border-radius: 14px;
            max-width: 450px;
            width: 90%;
            box-shadow: 0 20px 50px rgba(0,0,0,0.2);
        }

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

        .modal-header h3 {
            margin: 0;
            font-size: 1.1rem;
            color: #991b1b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .modal-header h3 i { color: #ef4444; }

        .modal-body { padding: 1.5rem; }
        .modal-body p { margin: 0 0 0.75rem; }
        .modal-body p:last-child { margin-bottom: 0; }

        .text-danger { color: #dc2626; font-size: 0.9rem; }

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

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

    <script>
    function confirmDelete() {
        document.getElementById('deleteModal').classList.add('active');
    }

    function closeModal() {
        document.getElementById('deleteModal').classList.remove('active');
    }

    // Close modal on overlay click
    document.getElementById('deleteModal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });

    // Close modal on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });
    </script>
</body>
</html>
