<?php
/**
 * Browse Materia Medica
 * Alphabetical listing of all remedies
 */

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

requireLogin();

$pdo = getDB();
$letter = $_GET['letter'] ?? '';
$search = $_GET['search'] ?? '';

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

if (!empty($letter)) {
    $where .= " AND name LIKE ?";
    $params[] = "$letter%";
}

if (!empty($search)) {
    $where .= " AND (name LIKE ? OR abbreviation LIKE ? OR materia_medica_text LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

// Get remedies
$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";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$remedies = $stmt->fetchAll();

// Get alphabet letters with counts
$letters = [];
foreach (range('A', 'Z') as $l) {
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM remedies WHERE name LIKE ?");
    $stmt->execute(["$l%"]);
    $letters[$l] = $stmt->fetch()['count'];
}

// Get featured remedies (most prescribed)
$featured = $pdo->query("SELECT r.id, r.name, r.abbreviation, COUNT(c.id) as prescription_count
                        FROM remedies r
                        LEFT JOIN cases c ON r.id = c.prescribed_remedy_id
                        GROUP BY r.id
                        ORDER BY prescription_count DESC
                        LIMIT 10")->fetchAll();

$totalRemedies = count($remedies);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Materia Medica - Browse Remedies</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;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); transform: translateX(5px); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .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);
        }
        .letter-filter {
            display: inline-block;
            margin: 3px;
        }
        .letter-filter a {
            display: inline-block;
            width: 40px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            border-radius: 50%;
            background: white;
            color: #333;
            text-decoration: none;
            font-weight: bold;
            transition: all 0.2s;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .letter-filter a:hover, .letter-filter a.active {
            background: #2ecc71;
            color: white;
            transform: scale(1.1);
        }
        .remedy-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.2s;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        .remedy-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="text-center py-4">
            <h4 class="text-white mb-0">🏥 Homoeopathy</h4>
            <small class="text-white-50">Kent's Repertory</small>
        </div>
        <nav class="nav flex-column mt-3">
            <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="compare.php"><i class="fas fa-chart-line"></i> <span>Compare</span></a>
            <a class="nav-link" href="bookmark.php"><i class="fas fa-bookmark"></i> <span>Bookmarks</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr class="bg-secondary my-3">
            <a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <!-- Main Content -->
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="fas fa-capsules"></i> Materia Medica</h4>
                <div>
                    <form method="GET" class="d-inline">
                        <div class="input-group">
                            <input type="text" name="search" class="form-control form-control-sm" 
                                   placeholder="Search remedies..." value="<?php echo escape($search); ?>" style="width: 250px;">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="fas fa-search"></i>
                            </button>
                            <?php if($search): ?>
                                <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-9">
                <!-- Alphabet Filter -->
                <div class="stats-card text-center">
                    <div class="letter-filter">
                        <a href="index.php" class="<?php echo empty($letter) ? 'active' : ''; ?>">All</a>
                    </div>
                    <?php foreach($letters as $l => $count): ?>
                        <?php if($count > 0): ?>
                            <div class="letter-filter">
                                <a href="?letter=<?php echo $l; ?>" class="<?php echo $letter == $l ? 'active' : ''; ?>">
                                    <?php echo $l; ?>
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="letter-filter">
                                <a href="#" class="text-muted disabled" style="background: #f0f0f0; cursor: default;"><?php echo $l; ?></a>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
                
                <!-- Results Count -->
                <div class="stats-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-list"></i> Found <strong><?php echo $totalRemedies; ?></strong> remedies</span>
                        <?php if($letter): ?>
                            <span class="text-muted">Showing remedies starting with '<?php echo $letter; ?>'</span>
                        <?php endif; ?>
                        <?php if($search): ?>
                            <span class="text-muted">Search results for: "<?php echo escape($search); ?>"</span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Remedies Grid -->
                <div class="row">
                    <?php if(empty($remedies)): ?>
                        <div class="col-12">
                            <div class="stats-card text-center text-muted py-5">
                                <i class="fas fa-capsules fa-3x mb-3"></i>
                                <p>No remedies found matching your criteria.</p>
                                <a href="index.php" class="btn btn-primary">View All Remedies</a>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php foreach($remedies as $remedy): ?>
                            <div class="col-md-6 col-lg-4">
                                <div class="remedy-card">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h5 class="mb-1">
                                                <a href="view.php?id=<?php echo $remedy['id']; ?>" class="text-decoration-none">
                                                    <?php echo escape($remedy['name']); ?>
                                                </a>
                                            </h5>
                                            <?php if($remedy['abbreviation']): ?>
                                                <small class="text-muted"><?php echo escape($remedy['abbreviation']); ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                                <i class="fas fa-ellipsis-v"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li><a class="dropdown-item" href="view.php?id=<?php echo $remedy['id']; ?>">
                                                    <i class="fas fa-eye"></i> View Details</a>
                                                </li>
                                                <li><a class="dropdown-item" href="#" onclick="bookmark(<?php echo $remedy['id']; ?>)">
                                                    <i class="fas fa-bookmark"></i> Bookmark</a>
                                                </li>
                                                <li><a class="dropdown-item" href="compare.php?remedy=<?php echo $remedy['id']; ?>">
                                                    <i class="fas fa-chart-line"></i> Compare</a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-2">
                                        <span class="badge bg-info"><?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']), 120); ?>
                                        </p>
                                    <?php endif; ?>
                                    
                                    <div class="mt-2">
                                        <a href="view.php?id=<?php echo $remedy['id']; ?>" class="btn btn-sm btn-primary">
                                            Read More <i class="fas fa-arrow-right"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="col-md-3">
                <!-- Featured Remedies -->
                <div class="stats-card">
                    <h6><i class="fas fa-fire"></i> Most Prescribed</h6>
                    <div class="mt-2">
                        <?php foreach($featured as $remedy): ?>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <a href="view.php?id=<?php echo $remedy['id']; ?>" class="text-decoration-none">
                                    <?php echo escape($remedy['name']); ?>
                                </a>
                                <span class="badge bg-primary"><?php echo $remedy['prescription_count']; ?>x</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- Quick Stats -->
                <div class="stats-card">
                    <h6><i class="fas fa-chart-bar"></i> Statistics</h6>
                    <div class="mt-2">
                        <div class="d-flex justify-content-between mb-2">
                            <span>Total Remedies:</span>
                            <strong><?php echo $pdo->query("SELECT COUNT(*) FROM remedies")->fetchColumn(); ?></strong>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>With Materia Medica:</span>
                            <strong><?php echo $pdo->query("SELECT COUNT(*) FROM remedies WHERE materia_medica_text IS NOT NULL AND materia_medica_text != ''")->fetchColumn(); ?></strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span>Total Rubric Links:</span>
                            <strong><?php echo $pdo->query("SELECT COUNT(*) FROM rubric_remedy")->fetchColumn(); ?></strong>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div class="stats-card">
                    <h6><i class="fas fa-link"></i> Quick Links</h6>
                    <div class="mt-2">
                        <a href="compare.php" class="d-block mb-2">
                            <i class="fas fa-chart-line"></i> Compare Remedies
                        </a>
                        <a href="search.php" class="d-block mb-2">
                            <i class="fas fa-search"></i> Advanced Search
                        </a>
                        <a href="bookmark.php" class="d-block">
                            <i class="fas fa-bookmark"></i> My Bookmarks
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function bookmark(remedyId) {
            $.post('bookmark.php', { action: 'add', remedy_id: remedyId }, function(response) {
                if (response.success) {
                    alert('Remedy bookmarked!');
                } else {
                    alert('Failed to bookmark');
                }
            }, 'json');
        }
    </script>
</body>
</html>