<?php
/**
 * Projects Management
 */

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

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle project creation/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'] ?? 'published');
    $featured = isset($_POST['featured']) ? 1 : 0;
    $imageUrl = null;
    
    // Handle image upload
    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)) {
                $imageUrl = $filename;
            } else {
                $message = 'Failed to upload image.';
            }
        }
    }
    
    if (empty($title)) {
        $message = 'Title is required.';
    } elseif (empty($message)) { // Only proceed if no error message was set
        $stmt = $pdo->prepare("
            INSERT INTO projects (title, description, location, service_type, status, featured, image_url)
            VALUES (:title, :description, :location, :service_type, :status, :featured, :image_url)
        ");
        
        $stmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':location' => $location,
            ':service_type' => $serviceType,
            ':status' => $status,
            ':featured' => $featured,
            ':image_url' => $imageUrl
        ]);
        
        $message = 'Project created successfully!';
    }
}

// Get all projects
$projects = $pdo->query("
    SELECT id, title, location, service_type, status, featured, image_url, created_at
    FROM projects
    ORDER BY created_at DESC
")->fetchAll();
?>
<!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 success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 1.5rem;">
                <!-- Form -->
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title">Add New Project</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label class="form-label">Title *</label>
                            <input type="text" id="title" name="title" class="form-control" 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;">
                                Recommended: 1200x800px. Max size: 5MB. Formats: JPEG, PNG, WebP, GIF
                            </small>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Description</label>
                            <textarea id="description" name="description" class="form-control" rows="4"></textarea>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Location</label>
                            <input type="text" id="location" name="location" class="form-control">
                        </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">Hydrogeological Survey</option>
                                <option value="drilling">Borehole Drilling</option>
                                <option value="solar-pump">Solarized Pumps</option>
                                <option value="home-solar">Home Solar</option>
                                <option value="water-supply">Water Supply</option>
                                <option value="irrigation">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">Draft (Hidden from frontend)</option>
                                <option value="published" selected>Published (Visible on frontend)</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"> Featured Project
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary">Create Project</button>
                    </form>
                </div>
                
                <!-- Projects List -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">All Projects (<?php echo count($projects); ?>)</h3>
                    </div>
            <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Image</th>
                                    <th>Title</th>
                                    <th>Location</th>
                                    <th>Service</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($projects as $project): ?>
                                <tr>
                                    <td>
                                        <?php 
                                        $imagePath = __DIR__ . '/../uploads/projects/' . $project['image_url'];
                                        if (!empty($project['image_url']) && file_exists($imagePath)): 
                                        ?>
                                            <img src="../uploads/projects/<?php echo htmlspecialchars($project['image_url']); ?>" 
                                                 alt="<?php echo htmlspecialchars($project['title']); ?>"
                                                 style="width: 60px; height: 60px; object-fit: cover; border-radius: 6px;">
                                        <?php else: ?>
                                            <span style="color: var(--text-secondary); font-size: 0.875rem;">No image</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: var(--text-primary);">
                                            <?php echo htmlspecialchars($project['title']); ?>
                                        </div>
                                        <?php if ($project['featured']): ?>
                                            <span class="badge badge-warning" style="font-size: 0.625rem; margin-top: 0.25rem;">Featured</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($project['location'] ?: 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($project['service_type'] ?: 'N/A'); ?></td>
                                    <td>
                                        <span class="badge badge-<?php echo $project['status'] === 'published' ? 'success' : 'warning'; ?>">
                                            <?php echo ucfirst($project['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div style="display: flex; gap: 0.5rem;">
                                            <a href="project-edit.php?id=<?php echo $project['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                            <a href="project-delete.php?id=<?php echo $project['id']; ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('Delete this project?')">Delete</a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

