<?php
/**
 * Add New Rubric
 * Admin page for adding rubrics to Kent's Repertory
 */

require_once __DIR__ . '/../../config/config.php';
requireAdmin();

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

// Get parent ID if pre-selected
$parentId = isset($_GET['parent_id']) ? (int)$_GET['parent_id'] : null;

// Fetch all potential parent rubrics for dropdown
$parentOptions = getRubricOptions($pdo);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF protection
    if (!isset($_POST['csrf_token']) || !verifyCsrfToken($_POST['csrf_token'])) {
        $error = "Security validation failed. Please refresh and try again.";
    } else {
        $rubricName = trim($_POST['rubric_name'] ?? '');
        $parentId = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $remedies = isset($_POST['remedies']) ? json_decode($_POST['remedies'], true) : [];

        if (empty($rubricName)) {
            $error = "Rubric name is required.";
        } else {
            // Start transaction
            $pdo->beginTransaction();
            try {
                // Calculate full path and level based on parent
                if ($parentId) {
                    $stmt = $pdo->prepare("SELECT full_path, level, chapter_name FROM rubrics WHERE id = ?");
                    $stmt->execute([$parentId]);
                    $parent = $stmt->fetch();
                    if (!$parent) {
                        throw new Exception("Invalid parent rubric selected.");
                    }
                    $fullPath = $parent['full_path'] . ' - ' . $rubricName;
                    $level = $parent['level'] + 1;
                    $chapterName = $parent['chapter_name'];
                } else {
                    $fullPath = $rubricName;
                    $level = 1;
                    $chapterName = $rubricName;
                }

                // Insert rubric
                $stmt = $pdo->prepare("INSERT INTO rubrics (parent_id, chapter_name, rubric_name, full_path, level, sort_order) 
                                      VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$parentId, $chapterName, $rubricName, $fullPath, $level, $sortOrder]);
                $newRubricId = $pdo->lastInsertId();

                // Process remedies
                if (!empty($remedies)) {
                    $remedyStmt = $pdo->prepare("INSERT IGNORE INTO remedies (name) VALUES (?)");
                    $linkStmt = $pdo->prepare("INSERT INTO rubric_remedy (rubric_id, remedy_id, grade) VALUES (?, ?, ?)");
                    foreach ($remedies as $remedy) {
                        $remedyName = trim($remedy['name']);
                        $grade = (int)$remedy['grade'];
                        if (empty($remedyName) || $grade < 1 || $grade > 4) {
                            continue;
                        }
                        // Insert or get remedy id
                        $remedyStmt->execute([$remedyName]);
                        $remedyId = $pdo->lastInsertId();
                        if (!$remedyId) {
                            // If already exists, fetch id
                            $stmt2 = $pdo->prepare("SELECT id FROM remedies WHERE name = ?");
                            $stmt2->execute([$remedyName]);
                            $remedyId = $stmt2->fetchColumn();
                        }
                        // Link to rubric
                        $linkStmt->execute([$newRubricId, $remedyId, $grade]);
                    }
                }

                $pdo->commit();
                $success = "Rubric added successfully!";
                // Clear form after success (redirect to avoid resubmission)
                header("refresh:2;url=index.php");
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Error: " . $e->getMessage();
            }
        }
    }
}

/**
 * Recursively build select options for rubrics
 */
function getRubricOptions($pdo, $parentId = null, $prefix = '') {
    $sql = "SELECT id, rubric_name FROM rubrics WHERE parent_id " . ($parentId === null ? "IS NULL" : "= ?") . " ORDER BY sort_order, rubric_name";
    $stmt = $pdo->prepare($sql);
    if ($parentId !== null) {
        $stmt->execute([$parentId]);
    } else {
        $stmt->execute();
    }
    $options = '';
    while ($row = $stmt->fetch()) {
        $options .= '<option value="' . $row['id'] . '">' . $prefix . htmlspecialchars($row['rubric_name']) . '</option>';
        $options .= getRubricOptions($pdo, $row['id'], $prefix . '-- ');
    }
    return $options;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Rubric - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: rgba(255,255,255,0.1);
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #2ecc71;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            margin-left: 260px;
            padding: 20px;
        }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .remedy-row {
            background: #f8f9fa;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 8px;
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
<div class="sidebar">
    <div class="text-center py-4">
        <h4 class="text-white">🏥 Admin</h4>
    </div>
    <nav class="nav flex-column">
        <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
        <a class="nav-link" href="../doctors/index.php"><i class="fas fa-user-md"></i> <span>Doctors</span></a>
        <a class="nav-link" href="../subscriptions/index.php"><i class="fas fa-credit-card"></i> <span>Subscriptions</span></a>
        <a class="nav-link active" href="index.php"><i class="fas fa-tree"></i> <span>Rubrics</span></a>
        <a class="nav-link" href="../remedies/index.php"><i class="fas fa-capsules"></i> <span>Remedies</span></a>
        <a class="nav-link" href="../reports/index.php"><i class="fas fa-chart-line"></i> <span>Reports</span></a>
        <a class="nav-link" href="../settings/index.php"><i class="fas fa-cog"></i> <span>Settings</span></a>
        <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
        <hr>
        <a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
    </nav>
</div>

<div class="main-content">
    <div class="top-navbar">
        <h4 class="mb-0"><i class="fas fa-plus-circle"></i> Add New Rubric</h4>
    </div>

    <div class="form-card">
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?> Redirecting...</div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST" id="rubricForm">
            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
            <input type="hidden" name="remedies" id="remediesJson">

            <div class="mb-3">
                <label for="parent_id" class="form-label">Parent Rubric (Optional)</label>
                <select name="parent_id" id="parent_id" class="form-control">
                    <option value="">-- Top Level (Chapter) --</option>
                    <?php echo getRubricOptions($pdo); ?>
                </select>
                <div class="form-text">Leave empty to create a new chapter.</div>
            </div>

            <div class="mb-3">
                <label for="rubric_name" class="form-label">Rubric Name <span class="text-danger">*</span></label>
                <input type="text" name="rubric_name" id="rubric_name" class="form-control" required>
            </div>

            <div class="mb-3">
                <label for="sort_order" class="form-label">Sort Order</label>
                <input type="number" name="sort_order" id="sort_order" class="form-control" value="0">
                <div class="form-text">Lower numbers appear first.</div>
            </div>

            <h5 class="mt-4">Remedies with Grades</h5>
            <div id="remediesContainer">
                <div class="remedy-row row g-2">
                    <div class="col-md-7">
                        <input type="text" class="form-control remedy-name" placeholder="Remedy name (e.g., Sulphur)">
                    </div>
                    <div class="col-md-3">
                        <select class="form-control remedy-grade">
                            <option value="1">Grade 1 (Normal)</option>
                            <option value="2">Grade 2 (Blue Italic)</option>
                            <option value="3">Grade 3 (Bold Red)</option>
                            <option value="4">Grade 4 (Bold Underline)</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-danger btn-sm remove-remedy">×</button>
                    </div>
                </div>
            </div>
            <button type="button" id="addRemedyBtn" class="btn btn-secondary btn-sm mt-2"><i class="fas fa-plus"></i> Add Another Remedy</button>

            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Rubric</button>
                <a href="index.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Add remedy row
    $('#addRemedyBtn').click(function() {
        var newRow = `
            <div class="remedy-row row g-2">
                <div class="col-md-7">
                    <input type="text" class="form-control remedy-name" placeholder="Remedy name">
                </div>
                <div class="col-md-3">
                    <select class="form-control remedy-grade">
                        <option value="1">Grade 1 (Normal)</option>
                        <option value="2">Grade 2 (Blue Italic)</option>
                        <option value="3">Grade 3 (Bold Red)</option>
                        <option value="4">Grade 4 (Bold Underline)</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-danger btn-sm remove-remedy">×</button>
                </div>
            </div>
        `;
        $('#remediesContainer').append(newRow);
    });

    // Remove remedy row
    $(document).on('click', '.remove-remedy', function() {
        if ($('.remedy-row').length > 1) {
            $(this).closest('.remedy-row').remove();
        } else {
            alert('You must keep at least one remedy row. Delete the rubric if no remedy needed.');
        }
    });

    // On form submit, collect remedies into JSON
    $('#rubricForm').on('submit', function(e) {
        var remedies = [];
        $('.remedy-row').each(function() {
            var name = $(this).find('.remedy-name').val().trim();
            var grade = $(this).find('.remedy-grade').val();
            if (name !== '') {
                remedies.push({ name: name, grade: parseInt(grade) });
            }
        });
        $('#remediesJson').val(JSON.stringify(remedies));
    });
</script>
</body>
</html>