<?php
/**
 * Advanced Remedy Search
 * Search remedies by name, indication, or Materia Medica text
 */

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

requireLogin();

$pdo = getDB();
$query = $_GET['q'] ?? '';
$searchIn = $_GET['search_in'] ?? 'all';
$minRubrics = (int)($_GET['min_rubrics'] ?? 0);
$minPrescriptions = (int)($_GET['min_prescriptions'] ?? 0);

// Build search query
$where = "1=1";
$params = [];

if (!empty($query)) {
    if ($searchIn == 'name') {
        $where .= " AND (name LIKE ? OR abbreviation LIKE ?)";
        $searchTerm = "%$query%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    } elseif ($searchIn == 'materia_medica') {
        $where .= " AND materia_medica_text LIKE ?";
        $params[] = "%$query%";
    } elseif ($searchIn == 'indications') {
        $where .= " AND clinical_indications LIKE ?";
        $params[] = "%$query%";
    } else {
        $where .= " AND (name LIKE ? OR abbreviation LIKE ? OR materia_medica_text LIKE ? OR clinical_indications LIKE ?)";
        $searchTerm = "%$query%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
}

if ($minRubrics > 0) {
    $where .= " AND (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = remedies.id) >= ?";
    $params[] = $minRubrics;
}

// Execute search
$sql = "SELECT r.*, 
        (SELECT COUNT(*) FROM rubric_remedy WHERE remedy_id = r.id) as rubric_count,
        (SELECT COUNT(*) FROM cases WHERE prescribed_remedy_id = r.id) as prescription_count
        FROM remedies r
        WHERE $where
        ORDER BY r.name
        LIMIT 100";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();

// Get search statistics
$stats = [
    'total' => count($results),
    'has_materia_medica' => count(array_filter($results, function($r) { return !empty($r['materia_medica_text']); })),
    'has_prescriptions' => count(array_filter($results, function($r) { return $r['prescription_count'] > 0; }))
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Materia Medica</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; }
        .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; }
        .sidebar .nav-link i { margin-right: 10px; }
        .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);
        }
        .search-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .result-item {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.2s;
            border-left: 4px solid #2ecc71;
        }
        .result-item:hover { transform: translateX(5px); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        @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">🏥</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="../cases/index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link" href="search.php"><i class="fas fa-search"></i> <span>Search</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">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-search"></i> Advanced Remedy Search</h4>
                <a href="index.php" class="btn btn-secondary btn-sm">Browse All</a>
            </div>
        </div>
        
        <!-- Search Form -->
        <div class="search-card">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Search Keywords</label>
                        <input type="text" name="q" class="form-control" placeholder="Enter remedy name, indication, or Materia Medica text..." 
                               value="<?php echo escape($query); ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Search In</label>
                        <select name="search_in" class="form-control">
                            <option value="all" <?php echo $searchIn == 'all' ? 'selected' : ''; ?>>All Fields</option>
                            <option value="name" <?php echo $searchIn == 'name' ? 'selected' : ''; ?>>Remedy Name Only</option>
                            <option value="materia_medica" <?php echo $searchIn == 'materia_medica' ? 'selected' : ''; ?>>Materia Medica Text</option>
                            <option value="indications" <?php echo $searchIn == 'indications' ? 'selected' : ''; ?>>Clinical Indications</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Minimum Rubrics</label>
                        <input type="number" name="min_rubrics" class="form-control" value="<?php echo $minRubrics; ?>" min="0">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Minimum Prescriptions</label>
                        <input type="number" name="min_prescriptions" class="form-control" value="<?php echo $minPrescriptions; ?>" min="0">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
                <a href="search.php" class="btn btn-secondary">Reset</a>
            </form>
        </div>
        
        <!-- Results -->
        <?php if ($query || $minRubrics > 0 || $minPrescriptions > 0): ?>
            <div class="search-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="fas fa-list"></i> Search Results (<?php echo $stats['total']; ?> found)</h5>
                    <div>
                        <span class="badge bg-info">With Materia Medica: <?php echo $stats['has_materia_medica']; ?></span>
                        <span class="badge bg-success">With Prescriptions: <?php echo $stats['has_prescriptions']; ?></span>
                    </div>
                </div>
                
                <?php if (empty($results)): ?>
                    <div class="alert alert-info">No remedies found matching your criteria.</div>
                <?php else: ?>
                    <?php foreach($results as $remedy): ?>
                        <div class="result-item">
                            <div class="row">
                                <div class="col-md-8">
                                    <h5>
                                        <a href="view.php?id=<?php echo $remedy['id']; ?>" class="text-decoration-none">
                                            <?php echo escape($remedy['name']); ?>
                                        </a>
                                        <?php if($remedy['abbreviation']): ?>
                                            <small class="text-muted">(<?php echo escape($remedy['abbreviation']); ?>)</small>
                                        <?php endif; ?>
                                    </h5>
                                    <div class="mt-1">
                                        <span class="badge bg-primary"><?php echo $remedy['rubric_count']; ?> rubrics</span>
                                        <span class="badge bg-success"><?php echo $remedy['prescription_count']; ?> prescriptions</span>
                                    </div>
                                    <?php if($remedy['materia_medica_text']): ?>
                                        <p class="mt-2 small text-muted">
                                            <?php echo truncate(strip_tags($remedy['materia_medica_text']), 200); ?>
                                        </p>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4 text-end">
                                    <a href="view.php?id=<?php echo $remedy['id']; ?>" class="btn btn-sm btn-primary">
                                        <i class="fas fa-eye"></i> View Details
                                    </a>
                                    <a href="compare.php?remedy=<?php echo $remedy['id']; ?>" class="btn btn-sm btn-info">
                                        <i class="fas fa-chart-line"></i> Compare
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="search-card">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-search fa-3x mb-3"></i>
                    <p>Enter search criteria above to find remedies in the Materia Medica.</p>
                    <small>You can search by remedy name, clinical indications, or full Materia Medica text.</small>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>