<?php
/**
 * Edit Remedy
 * Update remedy details, Materia Medica, and modalities
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';

requireAdmin();

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

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

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

// Parse modalities
$modalities = json_decode($remedy['modalities'], true);
$betterModalities = implode("\n", $modalities['better'] ?? []);
$worseModalities = implode("\n", $modalities['worse'] ?? []);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $name = trim($_POST['name']);
        $abbreviation = trim($_POST['abbreviation']);
        $materiaMedica = trim($_POST['materia_medica']);
        $clinicalIndications = trim($_POST['clinical_indications']);
        $betterModalitiesNew = array_filter(array_map('trim', explode("\n", $_POST['better_modalities'] ?? '')));
        $worseModalitiesNew = array_filter(array_map('trim', explode("\n", $_POST['worse_modalities'] ?? '')));
        
        $modalitiesJson = json_encode([
            'better' => array_values($betterModalitiesNew),
            'worse' => array_values($worseModalitiesNew)
        ]);
        
        // Validation
        $errors = [];
        
        if (!isRequired($name)) {
            $errors[] = "Remedy name is required";
        }
        
        // Check if remedy already exists (excluding current)
        $stmt = $pdo->prepare("SELECT id FROM remedies WHERE name = ? AND id != ?");
        $stmt->execute([$name, $remedyId]);
        if ($stmt->fetch()) {
            $errors[] = "Remedy name already exists";
        }
        
        if (empty($errors)) {
            $stmt = $pdo->prepare("UPDATE remedies 
                                  SET name = ?, abbreviation = ?, materia_medica_text = ?, 
                                      clinical_indications = ?, modalities = ?
                                  WHERE id = ?");
            if ($stmt->execute([$name, $abbreviation, $materiaMedica, $clinicalIndications, $modalitiesJson, $remedyId])) {
                $success = "Remedy updated successfully!";
                // Refresh data
                $remedy['name'] = $name;
                $remedy['abbreviation'] = $abbreviation;
                $remedy['materia_medica_text'] = $materiaMedica;
                $remedy['clinical_indications'] = $clinicalIndications;
                $betterModalities = implode("\n", $betterModalitiesNew);
                $worseModalities = implode("\n", $worseModalitiesNew);
            } else {
                $error = "Failed to update remedy";
            }
        } else {
            $error = implode("<br>", $errors);
        }
    }
}

// Get statistics for this remedy
$stmt = $pdo->prepare("SELECT 
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = ?) as rubric_count,
                      (SELECT COUNT(*) FROM cases WHERE prescribed_remedy_id = ?) as prescription_count,
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = ? AND grade = 4) as grade4_count,
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = ? AND grade = 3) as grade3_count,
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = ? AND grade = 2) as grade2_count,
                      (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = ? AND grade = 1) as grade1_count");
$stmt->execute([$remedyId, $remedyId, $remedyId, $remedyId, $remedyId, $remedyId]);
$stats = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Remedy - 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/summernote@0.8.18/dist/summernote-bs4.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;
        }
        .stats-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
        }
        .grade-4 { background: #ffeb3b; font-weight: bold; text-decoration: underline; padding: 2px 8px; border-radius: 3px; }
        .grade-3 { background: #ffcdd2; color: #c62828; font-weight: bold; padding: 2px 8px; border-radius: 3px; }
        .grade-2 { background: #bbdefb; color: #1565c0; font-style: italic; padding: 2px 8px; border-radius: 3px; }
        .grade-1 { background: #e0e0e0; color: #333; padding: 2px 8px; border-radius: 3px; }
    </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="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link active" href="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 Remedy: <?php echo escape($remedy['name']); ?></h4>
                        <div>
                            <a href="view.php?id=<?php echo $remedyId; ?>" class="btn btn-info btn-sm">
                                <i class="fas fa-eye"></i> View
                            </a>
                            <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"><?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-9">
                            <div class="form-card">
                                <form method="POST" action="" id="remedyForm">
                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="name" class="form-label">Remedy Name *</label>
                                            <input type="text" class="form-control" id="name" name="name" 
                                                   value="<?php echo escape($remedy['name']); ?>" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="abbreviation" class="form-label">Abbreviation</label>
                                            <input type="text" class="form-control" id="abbreviation" name="abbreviation" 
                                                   value="<?php echo escape($remedy['abbreviation']); ?>">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="materia_medica" class="form-label">Materia Medica Text</label>
                                        <textarea name="materia_medica" id="materiaMedica" class="form-control" rows="15"><?php echo escape($remedy['materia_medica_text']); ?></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="clinical_indications" class="form-label">Clinical Indications</label>
                                        <textarea name="clinical_indications" class="form-control" rows="4"><?php echo escape($remedy['clinical_indications']); ?></textarea>
                                    </div>
                                    
                                    <h5 class="mt-4 mb-3">Modalities</h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="better_modalities" class="form-label">Better (Amelioration)</label>
                                            <textarea name="better_modalities" class="form-control" rows="5"><?php echo escape($betterModalities); ?></textarea>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="worse_modalities" class="form-label">Worse (Aggravation)</label>
                                            <textarea name="worse_modalities" class="form-control" rows="5"><?php echo escape($worseModalities); ?></textarea>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> Update Remedy
                                        </button>
                                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">Remedy Statistics</h6>
                                </div>
                                <div class="card-body">
                                    <div class="stats-card mb-2">
                                        <strong><?php echo $stats['rubric_count']; ?></strong><br>
                                        <small>Rubrics Linked</small>
                                    </div>
                                    <div class="stats-card mb-2">
                                        <strong><?php echo $stats['prescription_count']; ?></strong><br>
                                        <small>Prescriptions</small>
                                    </div>
                                    <div class="stats-card">
                                        <strong>Grade Distribution</strong><br>
                                        <span class="grade-4">G4: <?php echo $stats['grade4_count']; ?></span>
                                        <span class="grade-3">G3: <?php echo $stats['grade3_count']; ?></span>
                                        <span class="grade-2">G2: <?php echo $stats['grade2_count']; ?></span>
                                        <span class="grade-1">G1: <?php echo $stats['grade1_count']; ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0">Quick Actions</h6>
                                </div>
                                <div class="card-body">
                                    <a href="assign-grade.php?remedy_id=<?php echo $remedyId; ?>" class="btn btn-warning btn-sm w-100 mb-2">
                                        <i class="fas fa-star"></i> Assign Grades
                                    </a>
                                    <a href="../rubrics/index.php?remedy=<?php echo urlencode($remedy['name']); ?>" class="btn btn-info btn-sm w-100 mb-2">
                                        <i class="fas fa-tree"></i> View in Rubrics
                                    </a>
                                    <a href="delete.php?id=<?php echo $remedyId; ?>" class="btn btn-danger btn-sm w-100" 
                                       onclick="return confirm('Delete this remedy? This action cannot be undone.')">
                                        <i class="fas fa-trash"></i> Delete Remedy
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#materiaMedica').summernote({
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
        });
    </script>
</body>
</html>