<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Check if admin is logged in
if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

// Load DatabaseHelper for cross-platform compatibility
require_once __DIR__ . '/helpers/database_helper.php';

// Load awards settings using DatabaseHelper
$awards = DatabaseHelper::loadJson('awards.json', ['enabled' => true, 'images' => []]);

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Add new award image
    if (isset($_POST['action']) && $_POST['action'] === 'add_image') {
        if (isset($_FILES['award_image']) && $_FILES['award_image']['size'] > 0) {
            try {
                $uploadResult = DatabaseHelper::saveUploadedFile($_FILES['award_image']);
                if (is_array($uploadResult) && !empty($uploadResult['success']) && !empty($uploadResult['filename'])) {
                    $imagePath = $uploadResult['filename'];
                } elseif (is_string($uploadResult)) {
                    $imagePath = $uploadResult;
                } else {
                    throw new Exception('Invalid upload response');
                }
                
                if (!is_array($awards['images'])) {
                    $awards['images'] = [];
                }
                
                $newId = 1;
                foreach ($awards['images'] as $img) {
                    if (isset($img['id']) && $img['id'] >= $newId) {
                        $newId = $img['id'] + 1;
                    }
                }
                
                $awards['images'][] = [
                    'id' => $newId,
                    'image' => $imagePath,
                    'uploaded_at' => date('Y-m-d H:i:s')
                ];
                
                if (DatabaseHelper::saveJson('awards.json', $awards)) {
                    $message = 'Award image added successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Error saving award image.';
                    $messageType = 'error';
                }
            } catch (Exception $e) {
                $message = 'Error uploading image: ' . $e->getMessage();
                $messageType = 'error';
            }
        } else {
            $message = 'Please select an image to upload.';
            $messageType = 'error';
        }
    }
    
    // Delete award image
    if (isset($_POST['action']) && $_POST['action'] === 'delete_image') {
        $imageId = (int)$_POST['image_id'];
        if (is_array($awards['images'])) {
            $awards['images'] = array_values(array_filter($awards['images'], function($img) use ($imageId) {
                return $img['id'] !== $imageId;
            }));
            
            if (DatabaseHelper::saveJson('awards.json', $awards)) {
                $message = 'Award image deleted successfully!';
                $messageType = 'success';
            } else {
                $message = 'Error deleting award image.';
                $messageType = 'error';
            }
        }
    }
    
    // Update awards settings
    if (isset($_POST['action']) && $_POST['action'] === 'update_settings') {
        $awards['enabled'] = isset($_POST['enabled']) ? true : false;
        
        if (DatabaseHelper::saveJson('awards.json', $awards)) {
            $message = 'Awards settings updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Error saving awards settings.';
            $messageType = 'error';
        }
    }
}

include 'admin_sidebar.php';
?>

<style>
    .admin-content-area {
        padding: 30px;
        margin-left: 20%; 
        background: #f9f9f9;
        min-height: calc(100vh - 200px);
    }

    .admin-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
    }

    .admin-header h1 {
        font-size: 28px;
        color: #333;
        margin: 0;
    }

    .admin-section {
        background: white;
        border-radius: 8px;
        padding: 25px;
        margin-bottom: 30px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .admin-section h2 {
        font-size: 20px;
        color: #333;
        margin-top: 0;
        margin-bottom: 20px;
        border-bottom: 2px solid #F07E2D;
        padding-bottom: 10px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }

    .form-group input[type="file"],
    .form-group input[type="text"],
    .form-group input[type="number"],
    .form-group textarea,
    .form-group select {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        font-family: inherit;
    }

    .form-group input[type="file"] {
        padding: 8px;
    }

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

    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .checkbox-group input[type="checkbox"] {
        width: auto;
        margin: 0;
    }

    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-primary {
        background: #F07E2D;
        color: white;
    }

    .btn-primary:hover {
        background: #e06a1a;
    }

    .btn-danger {
        background: #dc3545;
        color: white;
        padding: 8px 12px;
        font-size: 12px;
    }

    .btn-danger:hover {
        background: #c82333;
    }

    .btn-secondary {
        background: #6c757d;
        color: white;
    }

    .btn-secondary:hover {
        background: #5a6268;
    }

    .message {
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 20px;
        font-weight: 500;
    }

    .message.success {
        background: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }

    .message.error {
        background: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }

    .awards-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }

    .award-card {
        background: #f9f9f9;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        text-align: center;
    }

    .award-image {
        width: 100%;
        height: 150px;
        object-fit: cover;
        border-radius: 4px;
        margin-bottom: 10px;
    }

    .award-info {
        font-size: 12px;
        color: #666;
        margin-bottom: 10px;
    }

    .award-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
    }

    @media (max-width: 768px) {
        .admin-content-area {
            margin-left: 0;
            padding: 15px;
        }

        .admin-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 15px;
        }

        .awards-grid {
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        }
    }
</style>

<div class="admin-content-area">
    <div class="admin-header">
        <h1>🏆 Awards Management</h1>
    </div>

    <?php if (!empty($message)): ?>
        <div class="message <?php echo htmlspecialchars($messageType); ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <!-- Settings Section -->
    <div class="admin-section">
        <h2>Awards Settings</h2>
        <form method="POST" style="max-width: 400px;">
            <input type="hidden" name="action" value="update_settings">
            
            <div class="form-group checkbox-group">
                <input type="checkbox" id="enabled" name="enabled" <?php echo (!empty($awards['enabled']) ? 'checked' : ''); ?>>
                <label for="enabled" style="margin: 0;">Enable Awards Section on About Page</label>
            </div>

            <button type="submit" class="btn btn-primary">Save Settings</button>
        </form>
    </div>

    <!-- Upload New Award Image -->
    <div class="admin-section">
        <h2>Add Award Image</h2>
        <form method="POST" enctype="multipart/form-data" style="max-width: 500px;">
            <input type="hidden" name="action" value="add_image">
            
            <div class="form-group">
                <label for="award_image">Select Award Image</label>
                <input type="file" id="award_image" name="award_image" accept="image/*" required>
                <small style="color: #666; display: block; margin-top: 5px;">Supported formats: JPG, PNG, GIF, WebP</small>
            </div>

            <button type="submit" class="btn btn-primary">Upload Award Image</button>
        </form>
    </div>

    <!-- Existing Award Images -->
    <div class="admin-section">
        <h2>Award Images (<?php echo count($awards['images'] ?? []); ?>)</h2>
        
        <?php if (empty($awards['images'])): ?>
            <p style="color: #666;">No award images uploaded yet. Add your first award image above.</p>
        <?php else: ?>
            <div class="awards-grid">
                <?php foreach ($awards['images'] as $award): ?>
                    <div class="award-card">
                        <img src="<?php echo htmlspecialchars($award['image']); ?>" alt="Award" class="award-image">
                        <div class="award-info">
                            <div><strong>ID:</strong> <?php echo (int)$award['id']; ?></div>
                            <?php if (!empty($award['uploaded_at'])): ?>
                                <div><strong>Uploaded:</strong> <?php echo htmlspecialchars($award['uploaded_at']); ?></div>
                            <?php endif; ?>
                        </div>
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this award image?');">
                            <input type="hidden" name="action" value="delete_image">
                            <input type="hidden" name="image_id" value="<?php echo (int)$award['id']; ?>">
                            <button type="submit" class="btn btn-danger">Delete</button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

</body>
</html>
