<?php
/**
 * Technology & Equipment 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'] ?? '');
    $iconClass = sanitizeInput($_POST['icon_class'] ?? '');
    $category = sanitizeInput($_POST['category'] ?? '');
    $features = sanitizeInput($_POST['features'] ?? '[]');
    $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/technology/';
            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($title)) {
        $message = 'Title is required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO technology_items (title, description, icon_class, image_url, category, features, display_order, status) 
                VALUES (:title, :desc, :icon, :image, :category, :features, :order, :status)
            ");
            $stmt->execute([
                ':title' => $title,
                ':desc' => $description,
                ':icon' => $iconClass,
                ':image' => $imageUrl,
                ':category' => $category,
                ':features' => $features,
                ':order' => $displayOrder,
                ':status' => $status
            ]);
            $message = 'Technology item created successfully!';
        } else {
            if ($imageUrl) {
                // Delete old image
                $oldStmt = $pdo->prepare("SELECT image_url FROM technology_items WHERE id = :id");
                $oldStmt->execute([':id' => $id]);
                $oldImage = $oldStmt->fetchColumn();
                if ($oldImage && file_exists(__DIR__ . '/../uploads/technology/' . $oldImage)) {
                    unlink(__DIR__ . '/../uploads/technology/' . $oldImage);
                }
                $stmt = $pdo->prepare("
                    UPDATE technology_items SET title = :title, description = :desc, icon_class = :icon,
                    image_url = :image, category = :category, features = :features, 
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':desc' => $description, ':icon' => $iconClass,
                    ':image' => $imageUrl, ':category' => $category, ':features' => $features,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE technology_items SET title = :title, description = :desc, icon_class = :icon,
                    category = :category, features = :features, 
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':desc' => $description, ':icon' => $iconClass,
                    ':category' => $category, ':features' => $features,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            }
            $message = 'Technology item updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT image_url FROM technology_items WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $image = $stmt->fetchColumn();
    if ($image && file_exists(__DIR__ . '/../uploads/technology/' . $image)) {
        unlink(__DIR__ . '/../uploads/technology/' . $image);
    }
    $pdo->prepare("DELETE FROM technology_items WHERE id = :id")->execute([':id' => $id]);
    $message = 'Technology item deleted successfully!';
}

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

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

$pageTitle = 'Technology & Equipment';
?>
<!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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php 
    $GLOBALS['pdo'] = $pdo;
    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; ?>
            
            <!-- Add/Edit Form -->
            <div class="card slide-up">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $editItem ? 'Edit Technology Item' : 'Add New Technology Item'; ?></h3>
                </div>
                <form method="POST" enctype="multipart/form-data" style="padding: 1.5rem;">
                    <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 style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Title *</label>
                            <input type="text" name="title" class="form-control" required
                                   value="<?php echo htmlspecialchars($editItem['title'] ?? ''); ?>">
                        </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., Equipment, Survey, Solar">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="4"><?php echo htmlspecialchars($editItem['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Icon Class (Font Awesome)</label>
                            <input type="text" name="icon_class" class="form-control"
                                   value="<?php echo htmlspecialchars($editItem['icon_class'] ?? ''); ?>"
                                   placeholder="e.g., fa-hard-hat">
                            <small style="color: var(--text-secondary);">Use Font Awesome class names</small>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Technology Image</label>
                            <input type="file" name="image" accept="image/jpeg,image/png,image/webp" class="form-control">
                            <?php if ($editItem && $editItem['image_url']): ?>
                                <div style="margin-top: 0.5rem;">
                                    <img src="../uploads/technology/<?php echo htmlspecialchars($editItem['image_url']); ?>" 
                                         alt="Current image" style="max-width: 200px; border-radius: var(--radius-md);">
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Features (JSON Array)</label>
                        <textarea name="features" class="form-control" rows="3"><?php echo htmlspecialchars($editItem['features'] ?? '[]'); ?></textarea>
                        <small style="color: var(--text-secondary);">Format: ["Feature 1", "Feature 2", "Feature 3"]</small>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <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; ?>">
                        </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>
                    
                    <div style="margin-top: 1.5rem;">
                        <button type="submit" class="btn btn-primary">
                            <?php echo $editItem ? 'Update Item' : 'Create Item'; ?>
                        </button>
                        <?php if ($editItem): ?>
                            <a href="technology.php" class="btn btn-secondary">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            
            <!-- Items List -->
            <div class="card slide-up" style="animation-delay: 0.1s; margin-top: 1.5rem;">
                <div class="card-header">
                    <h3 class="card-title">All Technology Items (<?php echo count($items); ?>)</h3>
                </div>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Icon</th>
                                <th>Title</th>
                                <th>Category</th>
                                <th>Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item): ?>
                            <tr>
                                <td>
                                    <?php if ($item['icon_class']): ?>
                                        <i class="<?php echo htmlspecialchars($item['icon_class']); ?>" 
                                           style="font-size: 1.5rem; color: var(--primary-color);"></i>
                                    <?php else: ?>
                                        <span style="font-size: 1.5rem;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($item['title']); ?></td>
                                <td><?php echo htmlspecialchars($item['category'] ?? '—'); ?></td>
                                <td><?php echo $item['display_order']; ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $item['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst($item['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <a href="?edit=<?php echo $item['id']; ?>" class="btn btn-primary" style="padding: 0.375rem 0.75rem; font-size: 0.875rem;">Edit</a>
                                        <a href="?delete=<?php echo $item['id']; ?>" 
                                           class="btn" 
                                           style="padding: 0.375rem 0.75rem; font-size: 0.875rem; background: var(--danger-color, #EF4444); color: white;"
                                           onclick="return confirm('Are you sure you want to delete this item?')">Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

