<?php
/**
 * Edit Project
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$id = intval($_GET['id'] ?? 0);
$pdo = getDBConnection();
$message = '';

// Get project data
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = :id");
$stmt->execute([':id' => $id]);
$project = $stmt->fetch();

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

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = sanitizeInput($_POST['title'] ?? '');
    $description = sanitizeInput($_POST['description'] ?? '');
    $location = sanitizeInput($_POST['location'] ?? '');
    $serviceType = sanitizeInput($_POST['service_type'] ?? '');
    $status = sanitizeInput($_POST['status'] ?? 'draft');
    $featured = isset($_POST['featured']) ? 1 : 0;
    $imageUrl = $project['image_url']; // Keep existing image by default
    
    // Handle image upload/replacement
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
        $maxSize = 5 * 1024 * 1024; // 5MB
        
        if (!in_array($_FILES['image']['type'], $allowedTypes)) {
            $message = 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.';
        } elseif ($_FILES['image']['size'] > $maxSize) {
            $message = 'File size exceeds 5MB limit.';
        } else {
            $uploadDir = __DIR__ . '/../uploads/projects/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            $filepath = $uploadDir . $filename;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $filepath)) {
                // Delete old image if it exists
                if (!empty($project['image_url'])) {
                    $oldFile = $uploadDir . $project['image_url'];
                    if (file_exists($oldFile)) {
                        unlink($oldFile);
                    }
                }
                $imageUrl = $filename;
            } else {
                $message = 'Failed to upload new image.';
            }
        }
    }
    
    if (empty($title)) {
        $message = 'Title is required.';
    } elseif (empty($message)) { // Only proceed if no error message was set
        $updateStmt = $pdo->prepare("
            UPDATE projects 
            SET title = :title, description = :description, location = :location, 
                service_type = :service_type, status = :status, featured = :featured, image_url = :image_url
            WHERE id = :id
        ");
        
        $updateStmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':location' => $location,
            ':service_type' => $serviceType,
            ':status' => $status,
            ':featured' => $featured,
            ':image_url' => $imageUrl,
            ':id' => $id
        ]);
        
        $message = 'Project updated successfully!';
        // Refresh project data
        $stmt = $pdo->prepare("SELECT * FROM projects WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $project = $stmt->fetch();
    }
}
?>
$pageTitle = 'Edit Project';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message <?php echo strpos($message, 'successfully') !== false ? 'success' : 'error'; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>
            
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title">Edit Project</h3>
                    </div>
                    <?php if (!empty($project['image_url'])): ?>
                    <div style="margin: 0 1.5rem 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border-color);">
                        <h4 style="margin-bottom: 0.75rem; color: var(--text-primary); font-size: 0.875rem;">Current Image</h4>
                        <img src="../uploads/projects/<?php echo htmlspecialchars($project['image_url']); ?>" 
                             alt="<?php echo htmlspecialchars($project['title']); ?>"
                             style="max-width: 100%; border-radius: var(--radius-md); box-shadow: var(--shadow-md);">
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" enctype="multipart/form-data" style="padding: 0 1.5rem 1.5rem;">
                        <div class="form-group">
                            <label class="form-label">Title *</label>
                            <input type="text" id="title" name="title" class="form-control"
                                   value="<?php echo htmlspecialchars($project['title']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Project Image</label>
                            <input type="file" id="image" name="image" accept="image/*" class="form-control">
                            <small style="color: var(--text-secondary); display: block; margin-top: 0.25rem;">
                                <?php if (!empty($project['image_url'])): ?>
                                    Leave empty to keep current image. Upload a new image to replace it.
                                <?php else: ?>
                                    Recommended: 1200x800px. Max size: 5MB. Formats: JPEG, PNG, WebP, GIF
                                <?php endif; ?>
                            </small>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Description</label>
                            <textarea id="description" name="description" class="form-control" rows="4"><?php echo htmlspecialchars($project['description']); ?></textarea>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Location</label>
                            <input type="text" id="location" name="location" class="form-control"
                                   value="<?php echo htmlspecialchars($project['location']); ?>">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Service Type</label>
                            <select id="service_type" name="service_type" class="form-control">
                                <option value="">Select service</option>
                                <option value="survey" <?php echo $project['service_type'] === 'survey' ? 'selected' : ''; ?>>Hydrogeological Survey</option>
                                <option value="drilling" <?php echo $project['service_type'] === 'drilling' ? 'selected' : ''; ?>>Borehole Drilling</option>
                                <option value="solar-pump" <?php echo $project['service_type'] === 'solar-pump' ? 'selected' : ''; ?>>Solarized Pumps</option>
                                <option value="home-solar" <?php echo $project['service_type'] === 'home-solar' ? 'selected' : ''; ?>>Home Solar</option>
                                <option value="water-supply" <?php echo $project['service_type'] === 'water-supply' ? 'selected' : ''; ?>>Water Supply</option>
                                <option value="irrigation" <?php echo $project['service_type'] === 'irrigation' ? 'selected' : ''; ?>>Irrigation</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Status *</label>
                            <select id="status" name="status" class="form-control" required>
                                <option value="draft" <?php echo $project['status'] === 'draft' ? 'selected' : ''; ?>>Draft (Hidden from frontend)</option>
                                <option value="published" <?php echo $project['status'] === 'published' ? 'selected' : ''; ?>>Published (Visible on frontend)</option>
                                <option value="archived" <?php echo $project['status'] === 'archived' ? 'selected' : ''; ?>>Archived</option>
                            </select>
                            <small style="color: var(--text-secondary); display: block; margin-top: 0.25rem;">
                                Only "Published" projects will appear on the frontend website.
                            </small>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="featured" value="1" 
                                       <?php echo $project['featured'] ? 'checked' : ''; ?>> Featured Project
                            </label>
                        </div>
                        <div style="display: flex; gap: 1rem;">
                            <button type="submit" class="btn btn-primary">Update Project</button>
                            <a href="projects.php" class="btn btn-secondary">Cancel</a>
                        </div>
                    </form>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

