<?php
/**
 * Resources 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') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $title = sanitizeInput($_POST['title'] ?? '');
    $description = sanitizeInput($_POST['description'] ?? '');
    $resourceType = sanitizeInput($_POST['resource_type'] ?? 'guide');
    $category = sanitizeInput($_POST['category'] ?? '');
    $externalUrl = sanitizeInput($_POST['external_url'] ?? '');
    $icon = sanitizeInput($_POST['icon'] ?? '');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    // Handle file upload
    $fileUrl = null;
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/../uploads/resources/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        $filename = uniqid() . '_' . time() . '_' . basename($_FILES['file']['name']);
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $filename)) {
            $fileUrl = $filename;
        }
    }
    
    if (empty($title)) {
        $message = 'Title is required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO resources (title, description, resource_type, category, file_url, external_url, icon, display_order, status)
                VALUES (:title, :description, :type, :category, :file, :url, :icon, :order, :status)
            ");
            $stmt->execute([
                ':title' => $title, ':description' => $description, ':type' => $resourceType,
                ':category' => $category, ':file' => $fileUrl, ':url' => $externalUrl,
                ':icon' => $icon, ':order' => $displayOrder, ':status' => $status
            ]);
            $message = 'Resource created successfully!';
        } elseif ($action === 'update' && $id > 0) {
            if ($fileUrl) {
                // Delete old file
                $old = $pdo->prepare("SELECT file_url FROM resources WHERE id = :id");
                $old->execute([':id' => $id]);
                $oldFile = $old->fetchColumn();
                if ($oldFile) {
                    $file = __DIR__ . '/../uploads/resources/' . $oldFile;
                    if (file_exists($file)) unlink($file);
                }
                $stmt = $pdo->prepare("
                    UPDATE resources SET title = :title, description = :description, resource_type = :type,
                    category = :category, file_url = :file, external_url = :url, icon = :icon,
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':description' => $description, ':type' => $resourceType,
                    ':category' => $category, ':file' => $fileUrl, ':url' => $externalUrl,
                    ':icon' => $icon, ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE resources SET title = :title, description = :description, resource_type = :type,
                    category = :category, external_url = :url, icon = :icon,
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':description' => $description, ':type' => $resourceType,
                    ':category' => $category, ':url' => $externalUrl, ':icon' => $icon,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            }
            $message = 'Resource updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT file_url FROM resources WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $file = $stmt->fetchColumn();
    if ($file) {
        $filePath = __DIR__ . '/../uploads/resources/' . $file;
        if (file_exists($filePath)) unlink($filePath);
    }
    $pdo->prepare("DELETE FROM resources WHERE id = :id")->execute([':id' => $id]);
    $message = 'Resource deleted successfully!';
}

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

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

$pageTitle = 'Resources';
?>
<!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'; ?> Resource</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                        <?php if ($editItem): ?>
                            <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                        <?php endif; ?>
                        
                        <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">Description</label>
                            <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($editItem['description'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Resource Type *</label>
                            <select name="resource_type" class="form-control" required>
                                <option value="guide" <?php echo ($editItem['resource_type'] ?? 'guide') === 'guide' ? 'selected' : ''; ?>>Guide</option>
                                <option value="blog" <?php echo ($editItem['resource_type'] ?? '') === 'blog' ? 'selected' : ''; ?>>Blog</option>
                                <option value="video" <?php echo ($editItem['resource_type'] ?? '') === 'video' ? 'selected' : ''; ?>>Video</option>
                                <option value="document" <?php echo ($editItem['resource_type'] ?? '') === 'document' ? 'selected' : ''; ?>>Document</option>
                                <option value="link" <?php echo ($editItem['resource_type'] ?? '') === 'link' ? 'selected' : ''; ?>>External Link</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Category</label>
                            <input type="text" name="category" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['category'] ?? ''); ?>"
                                   placeholder="e.g., Maintenance, Installation, Safety">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">File Upload</label>
                            <input type="file" name="file" class="form-control">
                            <?php if ($editItem && $editItem['file_url']): ?>
                                <div style="margin-top: 0.5rem; font-size: 0.875rem; color: var(--text-secondary);">
                                    Current: <?php echo htmlspecialchars($editItem['file_url']); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">External URL</label>
                            <input type="url" name="external_url" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['external_url'] ?? ''); ?>"
                                   placeholder="https://...">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Icon (Emoji)</label>
                            <input type="text" name="icon" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['icon'] ?? ''); ?>"
                                   placeholder="📄">
                        </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="resources.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">All Resources</h3>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php if (empty($resources)): ?>
                            <p style="text-align: center; padding: 2rem; color: var(--text-secondary);">No resources yet</p>
                        <?php else: ?>
                            <?php foreach ($resources as $resource): ?>
                            <div style="padding: 1rem; border-bottom: 1px solid var(--border-color);">
                                <div style="display: flex; gap: 1rem; align-items: start;">
                                    <div style="font-size: 2rem; line-height: 1;">
                                        <?php echo htmlspecialchars($resource['icon'] ?: '📄'); ?>
                                    </div>
                                    <div style="flex: 1;">
                                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                            <div style="font-weight: 600; color: var(--text-primary);">
                                                <?php echo htmlspecialchars($resource['title']); ?>
                                            </div>
                                            <div style="display: flex; gap: 0.5rem;">
                                                <span class="badge badge-info"><?php echo ucfirst($resource['resource_type']); ?></span>
                                                <span class="badge badge-<?php echo $resource['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($resource['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <?php if ($resource['description']): ?>
                                            <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
                                                <?php echo htmlspecialchars(substr($resource['description'], 0, 100)); ?><?php echo strlen($resource['description']) > 100 ? '...' : ''; ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($resource['category']): ?>
                                            <span class="badge badge-info" style="margin-bottom: 0.5rem; display: inline-block;">
                                                <?php echo htmlspecialchars($resource['category']); ?>
                                            </span>
                                        <?php endif; ?>
                                        <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
                                            <a href="?edit=<?php echo $resource['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                            <a href="?delete=<?php echo $resource['id']; ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('Delete this resource?')">Delete</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

