<?php
require_once '../includes/config.php';
requireAuth();
require_once '../includes/functions.php';

$project = ['title' => '', 'description' => '', 'image_url' => '', 'client' => '', 'location' => '', 'completed_date' => date('Y-m-d')];
$isEdit = false;

if (isset($_GET['id'])) {
    $project = getProject($_GET['id']);
    $isEdit = true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'title' => $_POST['title'],
        'description' => $_POST['description'],
        'image_url' => $_POST['image_url'] ?? '',
        'client' => $_POST['client'],
        'location' => $_POST['location'],
        'completed_date' => $_POST['completed_date']
    ];
    
    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        $upload = uploadImage($_FILES['image']);
        if ($upload['success']) {
            $data['image_url'] = $upload['file'];
        } else {
            $error = $upload['message'];
        }
    }
    
    // Handle image removal
    if (!empty($_POST['remove_image']) && !empty($data['image_url'])) {
        $filePath = "../" . $data['image_url'];
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        $data['image_url'] = '';
    }
    
    if (empty($error)) {
        if ($isEdit) {
            $success = saveProject($data, $_GET['id']);
        } else {
            $success = saveProject($data);
        }
        
        if ($success) {
            header("Location: projects.php?success=Project+" . ($isEdit ? "updated" : "created"));
            exit;
        } else {
            $error = "Error saving project";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $isEdit ? 'Edit' : 'Add' ?> Project - <?= SITE_NAME ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #1a5276;
            --secondary: #2980b9;
            --accent: #e67e22;
            --light: #ecf0f1;
            --dark: #2c3e50;
            --success: #27ae60;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: 250px;
            background-color: var(--primary);
            color: white;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        
        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .sidebar-menu {
            padding: 20px 0;
        }
        
        .sidebar-menu a {
            display: block;
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
        }
        
        .sidebar-menu a:hover, 
        .sidebar-menu a.active {
            background-color: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .form-control, .form-select {
            border-radius: 5px;
            padding: 10px;
            border: 1px solid #ced4da;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.25rem rgba(26, 82, 118, 0.25);
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 5px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
        }
        
        .btn-primary:hover {
            background-color: var(--secondary);
            border-color: var(--secondary);
        }
        
        .preview-image {
            max-height: 200px;
            margin-top: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
            padding: 5px;
            background: white;
        }
        
        .file-upload-area {
            border: 2px dashed #ced4da;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .file-upload-area:hover {
            border-color: var(--primary);
            background-color: rgba(26, 82, 118, 0.05);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            
            .main-content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <h4><?= SITE_NAME ?></h4>
            <p class="mb-0">Admin Dashboard</p>
        </div>
        <div class="sidebar-menu">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="services.php"><i class="fas fa-tools"></i> Services</a>
            <a href="projects.php" class="active"><i class="fas fa-project-diagram"></i> Projects</a>
            <a href="gallery.php"><i class="fas fa-images"></i> Gallery</a>
            <a href="users.php"><i class="fas fa-users"></i> Users</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="projects.php">Projects</a></li>
                <li class="breadcrumb-item active" aria-current="page"><?= $isEdit ? 'Edit' : 'Add' ?> Project</li>
            </ol>
        </nav>
        
        <h1 class="mb-4"><?= $isEdit ? 'Edit' : 'Add' ?> Project</h1>
        
        <?php if (isset($error)): ?>
        <div class="alert alert-danger mb-4"><?= $error ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Project Details</h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="title" class="form-label">Title *</label>
                            <input type="text" class="form-control" id="title" name="title" 
                                   value="<?= htmlspecialchars($project['title']) ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="client" class="form-label">Client *</label>
                            <input type="text" class="form-control" id="client" name="client" 
                                   value="<?= htmlspecialchars($project['client']) ?>" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="location" class="form-label">Location *</label>
                            <input type="text" class="form-control" id="location" name="location" 
                                   value="<?= htmlspecialchars($project['location']) ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="completed_date" class="form-label">Completion Date *</label>
                            <input type="date" class="form-control" id="completed_date" name="completed_date" 
                                   value="<?= htmlspecialchars($project['completed_date']) ?>" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="description" class="form-label">Description *</label>
                        <textarea class="form-control" id="description" name="description" 
                                  rows="5" required><?= htmlspecialchars($project['description']) ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="image" class="form-label">Project Image</label>
                        <div class="file-upload-area" onclick="document.getElementById('image').click()">
                            <p>Drag & drop your image here or click to browse</p>
                            <p class="text-muted small">Recommended size: 1200x800px (JPG, PNG, max 2MB)</p>
                        </div>
                        <input type="file" class="d-none" id="image" name="image" accept="image/*" onchange="previewImage(this)">
                        
                        <?php if (!empty($project['image_url'])): ?>
                        <div class="mt-3">
                            <p class="mb-1">Current Image:</p>
                            <img src="../<?= $project['image_url'] ?>" class="preview-image" id="imagePreview">
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="removeImage" name="remove_image">
                                <label class="form-check-label" for="removeImage">
                                    Remove current image
                                </label>
                            </div>
                            <input type="hidden" name="image_url" value="<?= $project['image_url'] ?>">
                        </div>
                        <?php else: ?>
                        <div class="mt-3">
                            <img src="" class="preview-image d-none" id="imagePreview">
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="d-flex justify-content-end mt-4">
                        <a href="projects.php" class="btn btn-secondary me-2">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-1"></i> Save Project
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Image preview function
        function previewImage(input) {
            const preview = document.getElementById('imagePreview');
            const file = input.files[0];
            const reader = new FileReader();
            
            preview.classList.remove('d-none');
            
            reader.onloadend = function() {
                preview.src = reader.result;
            }
            
            if (file) {
                reader.readAsDataURL(file);
            } else {
                preview.src = "";
                preview.classList.add('d-none');
            }
        }
        
        // Drag and drop functionality
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('image');
            const dropArea = document.querySelector('.file-upload-area');
            
            if (dropArea) {
                // Highlight drop area when item is dragged over it
                ['dragenter', 'dragover'].forEach(eventName => {
                    dropArea.addEventListener(eventName, highlight, false);
                });

                ['dragleave', 'drop'].forEach(eventName => {
                    dropArea.addEventListener(eventName, unhighlight, false);
                });

                // Handle dropped files
                dropArea.addEventListener('drop', handleDrop, false);
            }

            function highlight(e) {
                e.preventDefault();
                e.stopPropagation();
                dropArea.classList.add('highlight');
            }

            function unhighlight(e) {
                e.preventDefault();
                e.stopPropagation();
                dropArea.classList.remove('highlight');
            }

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                fileInput.files = files;
                previewImage(fileInput);
            }
        });
    </script>
</body>
</html>