<?php
/**
 * New Case with Repertorization
 * Create new case with rubric selection and repertorization
 */

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

requireLogin();

// Clear temporary session data
unset($_SESSION['temp_rubrics']);
$selectedRubrics = [];

// Get available remedies for dropdown
$pdo = getDB();
$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>New Case - Repertorization</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/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <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; margin: 5px 10px; border-radius: 8px; }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .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); }
        .rubric-browser { height: 70vh; overflow-y: auto; border-right: 1px solid #ddd; }
        .selected-rubrics { height: 70vh; overflow-y: auto; }
        .rubric-node { margin-left: 20px; cursor: pointer; }
        .rubric-item { padding: 5px; border-bottom: 1px solid #eee; }
        .rubric-item:hover { background: #f0f0f0; }
        .selected-rubric-item { background: #e8f4f8; padding: 8px; margin-bottom: 5px; border-radius: 5px; display: flex; justify-content: space-between; }
        .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; }
        .remedy-list span { margin-right: 5px; font-size: 12px; }
        @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 mb-0">🏥 Homoeopathy</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="index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link active" href="new.php"><i class="fas fa-plus-circle"></i> <span>New Case</span></a>
            <a class="nav-link" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</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> New Case with Repertorization</h4></div>
        
        <form method="POST" action="save.php" id="caseForm">
            <div class="row">
                <div class="col-md-4 rubric-browser">
                    <h5>Kent's Repertory</h5>
                    <input type="text" id="rubricSearch" class="form-control mb-2" placeholder="Search rubrics...">
                    <div id="rubricTree"><?php echo getRubricTreeHTML(); ?></div>
                </div>
                
                <div class="col-md-3 selected-rubrics">
                    <h5>Selected Symptoms</h5>
                    <div id="selectedList"></div>
                    <button type="button" id="repertorizeBtn" class="btn btn-primary w-100 mt-3">Update Analysis</button>
                    <div id="analysisLoader" class="text-center mt-2" style="display: none;"><i class="fas fa-spinner fa-spin"></i> Analyzing...</div>
                </div>
                
                <div class="col-md-5">
                    <h5>Repertorization Results</h5>
                    <div id="repertorizationResults" class="mb-3" style="max-height: 300px; overflow-y: auto;"></div>
                    
                    <h5 class="mt-3">Patient Details</h5>
                    <div class="row"><div class="col-md-6 mb-2"><input type="text" name="patient_name" class="form-control" placeholder="Patient Name *" required></div>
                    <div class="col-md-6 mb-2"><input type="tel" name="patient_mobile" class="form-control" placeholder="Mobile Number *" required></div></div>
                    <div class="row"><div class="col-md-6 mb-2"><input type="number" name="patient_age" class="form-control" placeholder="Age"></div>
                    <div class="col-md-6 mb-2"><select name="patient_gender" class="form-control"><option value="">Gender</option><option value="M">Male</option><option value="F">Female</option><option value="Other">Other</option></select></div></div>
                    <div class="mb-2"><textarea name="chief_complaint" class="form-control" rows="2" placeholder="Chief Complaint *" required></textarea></div>
                    <div class="mb-2"><textarea name="case_history" class="form-control" rows="2" placeholder="Case History"></textarea></div>
                    <div class="mb-2"><textarea name="physical_generals" class="form-control" rows="2" placeholder="Physical Generals (Appetite, thirst, sleep, stool, urine, thermal state)"></textarea></div>
                    <div class="mb-2"><textarea name="mental_emotional" class="form-control" rows="2" placeholder="Mental/Emotional State"></textarea></div>
                    <div class="mb-2"><textarea name="modalities" class="form-control" rows="2" placeholder="Modalities (Better/Worse conditions)"></textarea></div>
                    
                    <input type="hidden" name="selected_rubrics" id="selectedRubricsJson" value="[]">
                    <button type="submit" class="btn btn-success w-100"><i class="fas fa-save"></i> Save Case</button>
                </div>
            </div>
        </form>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        let selectedRubrics = [];
        
        function selectRubric(id, path) {
            if (!selectedRubrics.includes(id)) {
                selectedRubrics.push(id);
                $('#selectedList').append(`<div class="selected-rubric-item" data-id="${id}">${path}<button type="button" class="btn-remove btn-sm btn-danger" onclick="removeRubric(${id})">×</button></div>`);
                updateRepertorization();
                updateSelectedRubricsField();
            }
        }
        
        function removeRubric(id) {
            selectedRubrics = selectedRubrics.filter(r => r !== id);
            $(`.selected-rubric-item[data-id="${id}"]`).remove();
            updateRepertorization();
            updateSelectedRubricsField();
        }
        
        function updateSelectedRubricsField() { $('#selectedRubricsJson').val(JSON.stringify(selectedRubrics)); }
        
        function updateRepertorization() {
            if (selectedRubrics.length === 0) { $('#repertorizationResults').html('<div class="alert alert-info">Select symptoms to see top remedies</div>'); return; }
            $('#analysisLoader').show();
            $.post('repertorize.php', { rubric_ids: selectedRubrics }, function(response) {
                if (response.success && response.results) {
                    let html = '<div class="list-group">';
                    response.results.forEach(function(r, i) {
                        if (i < 20) html += `<div class="list-group-item"><strong>${r.name}</strong><span class="float-end">Score: ${r.score}</span><br><small class="text-muted">Grades: ${r.grades.join(', ')}</small></div>`;
                    });
                    html += '</div>';
                    $('#repertorizationResults').html(html);
                } else { $('#repertorizationResults').html('<div class="alert alert-danger">Error in repertorization</div>'); }
                $('#analysisLoader').hide();
            }, 'json');
        }
        
        $('#rubricSearch').on('keyup', function() {
            let query = $(this).val();
            if (query.length > 2) {
                $.post('../../api/search-rubrics.php', { query: query }, function(res) {
                    if (res.success && res.results.length) {
                        let html = '<div class="search-results">';
                        res.results.forEach(r => { html += `<div class="rubric-item" onclick="selectRubric(${r.id}, '${r.full_path}')">${r.full_path}</div>`; });
                        html += '</div>';
                        $('#rubricTree').html(html);
                    } else if (query.length === 0) { location.reload(); }
                }, 'json');
            }
        });
        
        $(document).on('click', '.rubric-name', function() { selectRubric($(this).data('id'), $(this).data('path')); });
    </script>
</body>
</html>