<?php
/**
 * About Content 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 form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $sectionKey = sanitizeInput($_POST['section_key'] ?? '');
    $title = sanitizeInput($_POST['title'] ?? '');
    $content = sanitizeInput($_POST['content'] ?? '');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    // Handle image upload
    $imageUrl = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (in_array($_FILES['image']['type'], $allowedTypes)) {
            $uploadDir = __DIR__ . '/../uploads/about/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $filename)) {
                $imageUrl = $filename;
            }
        }
    }
    
    if (empty($sectionKey) || empty($title)) {
        $message = 'Section key and title are required.';
    } else {
        // Check if exists
        $check = $pdo->prepare("SELECT id FROM about_content WHERE section_key = :key");
        $check->execute([':key' => $sectionKey]);
        $exists = $check->fetch();
        
        if ($exists) {
            if ($imageUrl) {
                $stmt = $pdo->prepare("
                    UPDATE about_content SET title = :title, content = :content, 
                    image_url = :image, display_order = :order, status = :status 
                    WHERE section_key = :key
                ");
                $stmt->execute([
                    ':title' => $title, ':content' => $content, ':image' => $imageUrl,
                    ':order' => $displayOrder, ':status' => $status, ':key' => $sectionKey
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE about_content SET title = :title, content = :content, 
                    display_order = :order, status = :status WHERE section_key = :key
                ");
                $stmt->execute([
                    ':title' => $title, ':content' => $content,
                    ':order' => $displayOrder, ':status' => $status, ':key' => $sectionKey
                ]);
            }
            $message = 'About section updated successfully!';
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO about_content (section_key, title, content, image_url, display_order, status)
                VALUES (:key, :title, :content, :image, :order, :status)
            ");
            $stmt->execute([
                ':key' => $sectionKey, ':title' => $title, ':content' => $content,
                ':image' => $imageUrl, ':order' => $displayOrder, ':status' => $status
            ]);
            $message = 'About section created successfully!';
        }
    }
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $key = sanitizeInput($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM about_content WHERE section_key = :key");
    $stmt->execute([':key' => $key]);
    $editItem = $stmt->fetch();
}

// Get all about sections
$sections = $pdo->query("
    SELECT * FROM about_content ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'About Content';
?>
<!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"><?php echo $editItem ? 'Edit' : 'Add'; ?> About Section</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label class="form-label">Section Key *</label>
                            <input type="text" name="section_key" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['section_key'] ?? ''); ?>" 
                                   required placeholder="e.g., mission, vision, values"
                                   <?php echo $editItem ? 'readonly' : ''; ?>>
                            <small style="color: var(--text-secondary); display: block; margin-top: 0.25rem;">
                                Unique identifier (lowercase, no spaces)
                            </small>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Title *</label>
                            <input type="text" name="title" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['title'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Content *</label>
                            <textarea name="content" class="form-control" rows="6" required><?php echo htmlspecialchars($editItem['content'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Image</label>
                            <input type="file" name="image" accept="image/*" class="form-control">
                            <?php if ($editItem && $editItem['image_url']): ?>
                                <div style="margin-top: 0.5rem;">
                                    <img src="../uploads/about/<?php echo htmlspecialchars($editItem['image_url']); ?>" 
                                         style="max-width: 200px; border-radius: 8px;">
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" class="form-control" 
                                   value="<?php echo $editItem['display_order'] ?? 0; ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        
                        <div style="display: flex; gap: 0.75rem;">
                            <button type="submit" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Create'; ?></button>
                            <?php if ($editItem): ?>
                                <a href="about.php" class="btn btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
                
                <!-- List -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">About Sections</h3>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php if (empty($sections)): ?>
                            <p style="text-align: center; padding: 2rem; color: var(--text-secondary);">No sections yet</p>
                        <?php else: ?>
                            <?php foreach ($sections as $section): ?>
                            <div style="padding: 1rem; border-bottom: 1px solid var(--border-color);">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                    <div style="flex: 1;">
                                        <div style="font-weight: 600; color: var(--text-primary); margin-bottom: 0.25rem;">
                                            <?php echo htmlspecialchars($section['title']); ?>
                                        </div>
                                        <div style="font-size: 0.75rem; color: var(--text-secondary); font-family: monospace; margin-bottom: 0.5rem;">
                                            Key: <?php echo htmlspecialchars($section['section_key']); ?>
                                        </div>
                                        <div style="font-size: 0.875rem; color: var(--text-secondary);">
                                            <?php echo htmlspecialchars(substr($section['content'], 0, 150)); ?><?php echo strlen($section['content']) > 150 ? '...' : ''; ?>
                                        </div>
                                    </div>
                                    <span class="badge badge-<?php echo $section['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst($section['status']); ?>
                                    </span>
                                </div>
                                <?php if ($section['image_url']): ?>
                                    <div style="margin: 0.75rem 0;">
                                        <img src="../uploads/about/<?php echo htmlspecialchars($section['image_url']); ?>" 
                                             style="max-width: 150px; border-radius: 8px;">
                                    </div>
                                <?php endif; ?>
                                <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
                                    <a href="?edit=<?php echo urlencode($section['section_key']); ?>" class="btn btn-sm btn-secondary">Edit</a>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

