<?php
/**
 * Add New Remedy
 * Create a new remedy with Materia Medica and modalities
 */

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

requireAdmin();

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

// 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']);
        $betterModalities = array_filter(array_map('trim', explode("\n", $_POST['better_modalities'] ?? '')));
        $worseModalities = array_filter(array_map('trim', explode("\n", $_POST['worse_modalities'] ?? '')));
        
        $modalities = json_encode([
            'better' => array_values($betterModalities),
            'worse' => array_values($worseModalities)
        ]);
        
        // Validation
        $errors = [];
        
        if (!isRequired($name)) {
            $errors[] = "Remedy name is required";
        }
        
        // Check if remedy already exists
        $stmt = $pdo->prepare("SELECT id FROM remedies WHERE name = ?");
        $stmt->execute([$name]);
        if ($stmt->fetch()) {
            $errors[] = "Remedy already exists";
        }
        
        if (empty($errors)) {
            $stmt = $pdo->prepare("INSERT INTO remedies (name, abbreviation, materia_medica_text, clinical_indications, modalities) 
                                  VALUES (?, ?, ?, ?, ?)");
            if ($stmt->execute([$name, $abbreviation, $materiaMedica, $clinicalIndications, $modalities])) {
                $success = "Remedy added successfully!";
                header("refresh:2;url=index.php");
            } else {
                $error = "Failed to add remedy";
            }
        } 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>Add 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;
        }
        .note-editor {
            border-radius: 5px;
        }
    </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="../reports/index.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </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-plus"></i> Add New Remedy</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 remedy 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="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" required>
                                    <small class="text-muted">e.g., Sulphur, Lycopodium, Arsenicum Album</small>
                                </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">
                                    <small class="text-muted">e.g., Sulph, Lyc, Ars</small>
                                </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"></textarea>
                                <small class="text-muted">Detailed remedy description including mental, physical, and characteristic symptoms</small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="clinical_indications" class="form-label">Clinical Indications</label>
                                <textarea name="clinical_indications" class="form-control" rows="4" 
                                          placeholder="List key clinical conditions where this remedy is indicated..."></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" 
                                              placeholder="Open air&#10;Warmth&#10;Lying down&#10;Pressure"></textarea>
                                    <small class="text-muted">One modality per line</small>
                                </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"
                                              placeholder="Cold&#10;Night&#10;Wet weather&#10;Motion"></textarea>
                                    <small class="text-muted">One modality per line</small>
                                </div>
                            </div>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle"></i>
                                <strong>Tip:</strong> After adding the remedy, you can assign grades to rubrics using the 
                                <a href="assign-grade.php" class="alert-link">Assign Grade</a> feature.
                            </div>
                            
                            <div class="mt-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save Remedy
                                </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 src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#materiaMedica').summernote({
                height: 300,
                placeholder: 'Enter Materia Medica text...',
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });
        });
    </script>
</body>
</html>