<?php
/**
 * Assign Grade to Remedy in Rubric
 * Link remedies to rubrics with specific grades
 */

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

requireAdmin();

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

// Get parameters
$remedyId = (int)($_GET['remedy_id'] ?? 0);
$rubricId = (int)($_GET['rubric_id'] ?? 0);

// Get all remedies for dropdown
$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();

// Get selected remedy details
$selectedRemedy = null;
if ($remedyId) {
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE id = ?");
    $stmt->execute([$remedyId]);
    $selectedRemedy = $stmt->fetch();
}

// Get existing assignments for selected remedy
$existingAssignments = [];
if ($remedyId) {
    $stmt = $pdo->prepare("SELECT rr.rubric_id, rr.grade, r.full_path 
                          FROM rubric_remedy rr
                          JOIN rubrics r ON rr.rubric_id = r.id
                          WHERE rr.remedy_id = ?");
    $stmt->execute([$remedyId]);
    $existingAssignments = $stmt->fetchAll();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action == 'add') {
            $remedyId = (int)$_POST['remedy_id'];
            $rubricId = (int)$_POST['rubric_id'];
            $grade = (int)$_POST['grade'];
            
            // Check if assignment exists
            $stmt = $pdo->prepare("SELECT id FROM rubric_remedy WHERE rubric_id = ? AND remedy_id = ?");
            $stmt->execute([$rubricId, $remedyId]);
            
            if ($stmt->fetch()) {
                // Update grade
                $stmt = $pdo->prepare("UPDATE rubric_remedy SET grade = ? WHERE rubric_id = ? AND remedy_id = ?");
                if ($stmt->execute([$grade, $rubricId, $remedyId])) {
                    $success = "Grade updated successfully!";
                } else {
                    $error = "Failed to update grade";
                }
            } else {
                // Insert new
                $stmt = $pdo->prepare("INSERT INTO rubric_remedy (rubric_id, remedy_id, grade) VALUES (?, ?, ?)");
                if ($stmt->execute([$rubricId, $remedyId, $grade])) {
                    $success = "Grade assigned successfully!";
                } else {
                    $error = "Failed to assign grade";
                }
            }
            
        } elseif ($action == 'remove') {
            $assignmentId = (int)$_POST['assignment_id'];
            $stmt = $pdo->prepare("DELETE FROM rubric_remedy WHERE id = ?");
            if ($stmt->execute([$assignmentId])) {
                $success = "Assignment removed successfully!";
            } else {
                $error = "Failed to remove assignment";
            }
        }
        
        // Refresh data
        if ($remedyId) {
            $stmt = $pdo->prepare("SELECT rr.rubric_id, rr.grade, r.full_path 
                                  FROM rubric_remedy rr
                                  JOIN rubrics r ON rr.rubric_id = r.id
                                  WHERE rr.remedy_id = ?");
            $stmt->execute([$remedyId]);
            $existingAssignments = $stmt->fetchAll();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Grade - 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;
        }
        .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;
        }
        .grade-4 { background: #ffeb3b; font-weight: bold; text-decoration: underline; }
        .grade-3 { background: #ffcdd2; color: #c62828; font-weight: bold; }
        .grade-2 { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1 { background: #e0e0e0; color: #333; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">Dashboard</a>
                    <a class="nav-link" href="../doctors/index.php">Doctors</a>
                    <a class="nav-link" href="../subscriptions/index.php">Subscriptions</a>
                    <a class="nav-link" href="../rubrics/index.php">Rubrics</a>
                    <a class="nav-link active" href="index.php">Remedies</a>
                    <a class="nav-link" href="../../logout.php">Logout</a>
                </nav>
            </div>
            
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <h4 class="mb-0">Assign Grades to Rubrics</h4>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">Select Remedy</div>
                                <div class="card-body">
                                    <form method="GET">
                                        <select name="remedy_id" class="form-control" onchange="this.form.submit()">
                                            <option value="">-- Select Remedy --</option>
                                            <?php foreach($remedies as $remedy): ?>
                                                <option value="<?php echo $remedy['id']; ?>" <?php echo $remedyId == $remedy['id'] ? 'selected' : ''; ?>>
                                                    <?php echo escape($remedy['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </form>
                                </div>
                            </div>
                            
                            <?php if ($selectedRemedy): ?>
                            <div class="card mt-3">
                                <div class="card-header">Add New Assignment</div>
                                <div class="card-body">
                                    <form method="POST">
                                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                        <input type="hidden" name="action" value="add">
                                        <input type="hidden" name="remedy_id" value="<?php echo $remedyId; ?>">
                                        
                                        <div class="mb-3">
                                            <label>Select Rubric</label>
                                            <select name="rubric_id" class="form-control" required>
                                                <option value="">-- Select Rubric --</option>
                                                <?php echo getRubricSelectOptions(); ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label>Grade</label>
                                            <select name="grade" class="form-control" required>
                                                <option value="4">Grade 4 - Bold Underline (Most Indicated)</option>
                                                <option value="3">Grade 3 - Bold Red</option>
                                                <option value="2">Grade 2 - Blue Italic</option>
                                                <option value="1">Grade 1 - Normal (Least Indicated)</option>
                                            </select>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary w-100">Assign Grade</button>
                                    </form>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <?php if ($selectedRemedy): ?>
                                        Existing Assignments for <?php echo escape($selectedRemedy['name']); ?>
                                    <?php else: ?>
                                        Existing Assignments
                                    <?php endif; ?>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($existingAssignments)): ?>
                                        <p class="text-muted text-center">No assignments found. Select a remedy and add rubric grades.</p>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Rubric</th>
                                                        <th width="100">Grade</th>
                                                        <th width="80">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach($existingAssignments as $assignment): ?>
                                                    <tr>
                                                        <td><?php echo escape($assignment['full_path']); ?></td>
                                                        <td class="text-center">
                                                            <span class="grade-<?php echo $assignment['grade']; ?> px-2 py-1 rounded">
                                                                Grade <?php echo $assignment['grade']; ?>
                                                            </span>
                                                        </td>
                                                        <td class="text-center">
                                                            <form method="POST" style="display:inline">
                                                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                                <input type="hidden" name="action" value="remove">
                                                                <input type="hidden" name="assignment_id" value="<?php echo $assignment['rubric_id']; ?>">
                                                                <button type="submit" class="btn btn-danger btn-sm" 
                                                                        onclick="return confirm('Remove this grade assignment?')">
                                                                    <i class="fas fa-trash"></i>
                                                                </button>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>