<?php
/**
 * Reorder Rubric Hierarchy
 * Drag and drop reordering of rubrics within parent
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/rubric-tree.php';

requireAdmin();

$pdo = getDB();
$message = '';
$error = '';

// Handle reorder update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['order'])) {
    $orderData = json_decode($_POST['order'], true);
    
    if (!empty($orderData)) {
        beginTransaction();
        
        try {
            foreach ($orderData as $item) {
                $stmt = $pdo->prepare("UPDATE rubrics SET sort_order = ? WHERE id = ?");
                $stmt->execute([$item['order'], $item['id']]);
            }
            commitTransaction();
            $message = "Rubric order updated successfully!";
        } catch (Exception $e) {
            rollbackTransaction();
            $error = "Failed to update order: " . $e->getMessage();
        }
    }
}

// Get all rubrics grouped by parent for sorting
$stmt = $pdo->query("SELECT r.*, 
                    (SELECT COUNT(*) FROM rubrics WHERE parent_id = r.id) as child_count
                    FROM rubrics r 
                    ORDER BY r.parent_id, r.sort_order, r.rubric_name");
$allRubrics = $stmt->fetchAll();

// Group by parent
$rubricsByParent = [];
foreach ($allRubrics as $rubric) {
    $parentKey = $rubric['parent_id'] ?? 0;
    if (!isset($rubricsByParent[$parentKey])) {
        $rubricsByParent[$parentKey] = [];
    }
    $rubricsByParent[$parentKey][] = $rubric;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reorder Rubrics - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .sortable-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sortable-item {
            background: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 12px 15px;
            margin-bottom: 5px;
            cursor: move;
            transition: all 0.2s;
        }
        .sortable-item:hover {
            background: #f8f9fa;
            border-color: #3498db;
        }
        .sortable-item.dragging {
            opacity: 0.5;
        }
        .sortable-handle {
            cursor: grab;
            margin-right: 10px;
            color: #999;
        }
        .sortable-handle:active {
            cursor: grabbing;
        }
        .level-badge {
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 10px;
            margin-left: 10px;
        }
        .parent-title {
            background: #e9ecef;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link active" href="reorder.php">
                        <i class="fas fa-arrows-alt"></i> Reorder
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-arrows-alt"></i> Reorder Rubric Hierarchy</h4>
                        <div>
                            <a href="index.php" class="btn btn-secondary btn-sm">
                                <i class="fas fa-arrow-left"></i> Back to List
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($message): ?>
                        <div class="alert alert-success"><?php echo $message; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> 
                        Drag and drop items to reorder them within their parent category. Changes are saved automatically.
                    </div>
                    
                    <form method="POST" id="reorderForm">
                        <input type="hidden" name="order" id="orderData">
                        
                        <?php foreach ($rubricsByParent as $parentId => $rubrics): ?>
                            <?php
                            if ($parentId == 0) {
                                $parentTitle = "📚 CHAPTERS (Top Level)";
                            } else {
                                $parent = getRubric($parentId);
                                $parentTitle = $parent ? "📁 " . $parent['rubric_name'] : "Unknown Parent";
                            }
                            ?>
                            <div class="card mb-4">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0"><?php echo $parentTitle; ?></h5>
                                </div>
                                <div class="card-body">
                                    <ul class="sortable-list" data-parent="<?php echo $parentId; ?>">
                                        <?php foreach ($rubrics as $index => $rubric): ?>
                                            <li class="sortable-item" data-id="<?php echo $rubric['id']; ?>" data-order="<?php echo $index; ?>">
                                                <i class="fas fa-grip-vertical sortable-handle"></i>
                                                <?php 
                                                $levelIcon = '';
                                                if ($rubric['level'] == 1) $levelIcon = '📚 ';
                                                elseif ($rubric['level'] == 2) $levelIcon = '📖 ';
                                                elseif ($rubric['level'] == 3) $levelIcon = '📌 ';
                                                else $levelIcon = '• ';
                                                ?>
                                                <?php echo $levelIcon . escape($rubric['rubric_name']); ?>
                                                <span class="level-badge badge bg-secondary">Level <?php echo $rubric['level']; ?></span>
                                                <?php if ($rubric['child_count'] > 0): ?>
                                                    <span class="badge bg-info"><?php echo $rubric['child_count']; ?> children</span>
                                                <?php endif; ?>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Order
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script>
        // Initialize Sortable for each list
        const sortableLists = [];
        
        document.querySelectorAll('.sortable-list').forEach((list, index) => {
            const sortable = new Sortable(list, {
                handle: '.sortable-handle',
                animation: 150,
                ghostClass: 'dragging',
                onEnd: function() {
                    updateOrder();
                }
            });
            sortableLists.push(sortable);
        });
        
        function updateOrder() {
            const orderData = [];
            
            document.querySelectorAll('.sortable-list').forEach((list) => {
                const parentId = list.dataset.parent;
                const items = list.querySelectorAll('.sortable-item');
                
                items.forEach((item, order) => {
                    orderData.push({
                        id: item.dataset.id,
                        order: order,
                        parent_id: parentId
                    });
                });
            });
            
            $('#orderData').val(JSON.stringify(orderData));
        }
        
        // Auto-save on order change (optional)
        let autoSaveTimeout;
        function autoSave() {
            clearTimeout(autoSaveTimeout);
            autoSaveTimeout = setTimeout(() => {
                $('#reorderForm').submit();
            }, 1000);
        }
        
        // Uncomment to enable auto-save
        // document.querySelectorAll('.sortable-list').forEach(list => {
        //     list.addEventListener('sortupdate', autoSave);
        // });
    </script>
</body>
</html>