<?php
/**
 * Edit Rubric
 * Update rubric details and associated remedies
 */

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

requireAdmin();

$pdo = getDB();
$rubricId = (int)($_GET['id'] ?? 0);
$error = '';
$success = '';

// Get rubric details
$stmt = $pdo->prepare("SELECT * FROM rubrics WHERE id = ?");
$stmt->execute([$rubricId]);
$rubric = $stmt->fetch();

if (!$rubric) {
    header('Location: index.php?error=Rubric not found');
    exit;
}

// Get associated remedies
$stmt = $pdo->prepare("SELECT r.id, r.name, rr.grade 
                      FROM rubric_remedy rr
                      JOIN remedies r ON rr.remedy_id = r.id
                      WHERE rr.rubric_id = ?");
$stmt->execute([$rubricId]);
$remedies = $stmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $rubricName = trim($_POST['rubric_name']);
        $parentId = $_POST['parent_id'] ?: null;
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        
        $errors = [];
        
        if (!isRequired($rubricName)) {
            $errors[] = "Rubric name is required";
        }
        
        if (empty($errors)) {
            // Update rubric
            $stmt = $pdo->prepare("UPDATE rubrics SET rubric_name = ?, sort_order = ? WHERE id = ?");
            $stmt->execute([$rubricName, $sortOrder, $rubricId]);
            
            // Update parent if changed
            if ($parentId != $rubric['parent_id']) {
                $parent = $parentId ? getRubric($parentId) : null;
                if ($parent) {
                    $fullPath = $parent['full_path'] . ' - ' . $rubricName;
                    $level = $parent['level'] + 1;
                    $chapterName = $parent['chapter_name'];
                } else {
                    $fullPath = $rubricName;
                    $level = 1;
                    $chapterName = $rubricName;
                }
                
                $stmt = $pdo->prepare("UPDATE rubrics SET parent_id = ?, full_path = ?, level = ?, chapter_name = ? WHERE id = ?");
                $stmt->execute([$parentId, $fullPath, $level, $chapterName, $rubricId]);
            }
            
            // Handle remedies - delete existing
            $stmt = $pdo->prepare("DELETE FROM rubric_remedy WHERE rubric_id = ?");
            $stmt->execute([$rubricId]);
            
            // Add new remedies
            if (!empty($_POST['remedies'])) {
                $newRemedies = json_decode($_POST['remedies'], true);
                foreach ($newRemedies as $remedy) {
                    if (!empty($remedy['name']) && !empty($remedy['grade'])) {
                        // Get or create remedy
                        $stmt = $pdo->prepare("SELECT id FROM remedies WHERE name = ?");
                        $stmt->execute([$remedy['name']]);
                        $existing = $stmt->fetch();
                        
                        if ($existing) {
                            $remedyId = $existing['id'];
                        } else {
                            $stmt = $pdo->prepare("INSERT INTO remedies (name) VALUES (?)");
                            $stmt->execute([$remedy['name']]);
                            $remedyId = $pdo->lastInsertId();
                        }
                        
                        $stmt = $pdo->prepare("INSERT INTO rubric_remedy (rubric_id, remedy_id, grade) VALUES (?, ?, ?)");
                        $stmt->execute([$rubricId, $remedyId, $remedy['grade']]);
                    }
                }
            }
            
            $success = "Rubric updated successfully!";
            header("refresh:2;url=index.php");
        } else {
            $error = implode("<br>", $errors);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Rubric - 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">
    <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;
        }
        .form-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 30px;
        }
        .remedy-row {
            background: #f8f9fa;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .grade-1 { font-weight: normal; color: #000; }
        .grade-2 { font-style: italic; color: #0066cc; }
        .grade-3 { font-weight: bold; color: #cc0000; }
        .grade-4 { font-weight: bold; text-decoration: underline; color: #000; }
    </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 active" href="index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </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-edit"></i> Edit Rubric</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 ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                            <br><small>Redirecting to rubric list...</small>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="form-card">
                        <form method="POST" action="" id="rubricForm">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="mb-3">
                                <label class="form-label">Current Path</label>
                                <input type="text" class="form-control" value="<?php echo $rubric['full_path']; ?>" disabled>
                            </div>
                            
                            <div class="mb-3">
                                <label for="parent_id" class="form-label">Parent Rubric</label>
                                <select class="form-control" id="parent_id" name="parent_id">
                                    <option value="">-- Top Level (Chapter) --</option>
                                    <?php echo getRubricSelectOptions($rubric['parent_id']); ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="rubric_name" class="form-label">Rubric Name *</label>
                                <input type="text" class="form-control" id="rubric_name" name="rubric_name" 
                                       value="<?php echo escape($rubric['rubric_name']); ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="sort_order" class="form-label">Sort Order</label>
                                <input type="number" class="form-control" id="sort_order" name="sort_order" 
                                       value="<?php echo $rubric['sort_order']; ?>">
                            </div>
                            
                            <div class="alert alert-info">
                                <strong>Level:</strong> <?php echo $rubric['level']; ?> - <?php echo REPERTORY_LEVELS[$rubric['level']] ?? 'Rubric'; ?>
                                <br>
                                <strong>Chapter:</strong> <?php echo $rubric['chapter_name']; ?>
                            </div>
                            
                            <h5 class="mt-4 mb-3">Remedies with Grades</h5>
                            <div id="remediesContainer">
                                <?php if (empty($remedies)): ?>
                                <div class="remedy-row row">
                                    <div class="col-md-8">
                                        <input type="text" class="form-control remedy-name" placeholder="Remedy name">
                                    </div>
                                    <div class="col-md-3">
                                        <select class="form-control grade-select">
                                            <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-1">
                                        <button type="button" class="btn btn-danger btn-sm remove-remedy">×</button>
                                    </div>
                                </div>
                                <?php else: ?>
                                    <?php foreach($remedies as $remedy): ?>
                                    <div class="remedy-row row">
                                        <div class="col-md-8">
                                            <input type="text" class="form-control remedy-name" value="<?php echo escape($remedy['name']); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <select class="form-control grade-select">
                                                <option value="1" <?php echo $remedy['grade'] == 1 ? 'selected' : ''; ?>>Grade 1 (Normal)</option>
                                                <option value="2" <?php echo $remedy['grade'] == 2 ? 'selected' : ''; ?>>Grade 2 (Blue Italic)</option>
                                                <option value="3" <?php echo $remedy['grade'] == 3 ? 'selected' : ''; ?>>Grade 3 (Bold Red)</option>
                                                <option value="4" <?php echo $remedy['grade'] == 4 ? 'selected' : ''; ?>>Grade 4 (Bold Underline)</option>
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <button type="button" class="btn btn-danger btn-sm remove-remedy">×</button>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <button type="button" class="btn btn-sm btn-secondary mt-2" id="addRemedy">
                                <i class="fas fa-plus"></i> Add Another Remedy
                            </button>
                            
                            <input type="hidden" id="remediesJson" name="remedies">
                            
                            <div class="mt-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Update Rubric
                                </button>
                                <a href="index.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Add remedy row
        $('#addRemedy').click(function() {
            const newRow = `
                <div class="remedy-row row">
                    <div class="col-md-8">
                        <input type="text" class="form-control remedy-name" placeholder="Remedy name">
                    </div>
                    <div class="col-md-3">
                        <select class="form-control grade-select">
                            <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-1">
                        <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();
            }
        });
        
        // Collect remedies before submit
        $('#rubricForm').on('submit', function(e) {
            const remedies = [];
            $('.remedy-row').each(function() {
                const name = $(this).find('.remedy-name').val().trim();
                const grade = $(this).find('.grade-select').val();
                if (name) {
                    remedies.push({ name: name, grade: parseInt(grade) });
                }
            });
            $('#remediesJson').val(JSON.stringify(remedies));
        });
    </script>
</body>
</html>