<?php
/**
 * Manage Remedies - List View
 * Display all remedies with search, filter, and pagination
 */

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

requireAdmin();

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

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_action'])) {
    $selectedIds = $_POST['selected_ids'] ?? [];
    $bulkAction = $_POST['bulk_action'];
    
    if (!empty($selectedIds)) {
        $placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
        
        if ($bulkAction == 'delete') {
            // Check if any remedy is used in prescriptions
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cases WHERE prescribed_remedy_id IN ($placeholders)");
            $stmt->execute($selectedIds);
            $caseCount = $stmt->fetch()['count'];
            
            if ($caseCount > 0) {
                $error = "Cannot delete remedies that are used in prescriptions. ($caseCount cases affected)";
            } else {
                $stmt = $pdo->prepare("DELETE FROM remedies WHERE id IN ($placeholders)");
                $stmt->execute($selectedIds);
                $message = count($selectedIds) . " remedies deleted.";
            }
        }
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$letter = $_GET['letter'] ?? '';
$page = (int)($_GET['page'] ?? 1);
$limit = ITEMS_PER_PAGE;
$offset = ($page - 1) * $limit;

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

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

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

$whereClause = implode(" AND ", $whereConditions);

// Get total count for pagination
$countSql = "SELECT COUNT(*) as total FROM remedies r WHERE $whereClause";
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$totalRemedies = $stmt->fetch()['total'];
$totalPages = ceil($totalRemedies / $limit);

// Get remedies list
$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 $whereClause
        ORDER BY r.name
        LIMIT ? OFFSET ?";

$params[] = $limit;
$params[] = $offset;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$remedies = $stmt->fetchAll();

// Get statistics
$stmt = $pdo->query("SELECT 
                    COUNT(*) as total,
                    (SELECT COUNT(DISTINCT rubric_id) FROM rubric_remedy) as total_links,
                    (SELECT COUNT(*) FROM rubric_remedy WHERE grade = 4) as grade4_count,
                    (SELECT COUNT(*) FROM rubric_remedy WHERE grade = 3) as grade3_count,
                    (SELECT COUNT(*) FROM rubric_remedy WHERE grade = 2) as grade2_count,
                    (SELECT COUNT(*) FROM rubric_remedy WHERE grade = 1) as grade1_count
                    FROM remedies");
$stats = $stmt->fetch();

// Get letters for alphabet filter
$letters = range('A', 'Z');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Remedies - 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.datatables.net/1.11.5/css/dataTables.bootstrap5.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;
        }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stats-number {
            font-size: 28px;
            font-weight: bold;
        }
        .letter-filter {
            display: inline-block;
            margin: 2px;
        }
        .letter-filter a {
            display: inline-block;
            width: 36px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            border-radius: 50%;
            background: #f0f0f0;
            color: #333;
            text-decoration: none;
            transition: all 0.2s;
        }
        .letter-filter a:hover, .letter-filter a.active {
            background: #3498db;
            color: white;
        }
        .grade-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            margin: 0 2px;
        }
        .grade-4 { background: #ffeb3b; font-weight: bold; text-decoration: underline; }
        .grade-3 { background: #ffcdd2; color: #c62828; font-weight: bold; }
        .grade-2 { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1 { background: #e0e0e0; color: #333; }
    </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="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </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-capsules"></i> Manage Remedies</h4>
                        <div>
                            <a href="add.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus"></i> Add Remedy
                            </a>
                            <a href="bulk-import.php" class="btn btn-info btn-sm">
                                <i class="fas fa-upload"></i> Bulk Import
                            </a>
                            <a href="export.php" class="btn btn-success btn-sm">
                                <i class="fas fa-download"></i> Export
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['total']; ?></div>
                                <div class="text-muted">Total Remedies</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['total_links']; ?></div>
                                <div class="text-muted">Rubric Links</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number">
                                    <span class="grade-4"><?php echo $stats['grade4_count']; ?></span> /
                                    <span class="grade-3"><?php echo $stats['grade3_count']; ?></span> /
                                    <span class="grade-2"><?php echo $stats['grade2_count']; ?></span> /
                                    <span class="grade-1"><?php echo $stats['grade1_count']; ?></span>
                                </div>
                                <div class="text-muted">Grade Distribution</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number">
                                    <a href="assign-grade.php" class="btn btn-warning btn-sm w-100">
                                        <i class="fas fa-star"></i> Assign Grades
                                    </a>
                                </div>
                                <div class="text-muted">Quick Actions</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Alphabet Filter -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="text-center">
                                <strong class="me-3">Filter by Letter:</strong>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['letter' => '', 'page' => 1])); ?>" 
                                   class="letter-filter"><a href="#" class="<?php echo empty($letter) ? 'active' : ''; ?>">All</a></a>
                                <?php foreach($letters as $l): ?>
                                    <a href="?<?php echo http_build_query(array_merge($_GET, ['letter' => $l, 'page' => 1])); ?>" 
                                       class="letter-filter"><a href="#" class="<?php echo $letter == $l ? 'active' : ''; ?>"><?php echo $l; ?></a></a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Search Bar -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-10">
                                    <input type="text" class="form-control" name="search" 
                                           placeholder="Search by remedy name, abbreviation, or Materia Medica text..." 
                                           value="<?php echo escape($search); ?>">
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="fas fa-search"></i> Search
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Remedies Table -->
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">Remedies List</h5>
                                <span class="badge bg-primary"><?php echo $totalRemedies; ?> Total</span>
                            </div>
                        </div>
                        <div class="card-body">
                            <form method="POST" id="bulkForm">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" id="selectAll">
                                                </th>
                                                <th>ID</th>
                                                <th>Remedy Name</th>
                                                <th>Abbreviation</th>
                                                <th>Rubrics</th>
                                                <th>Prescriptions</th>
                                                <th>Grade Summary</th>
                                                <th>Created</th>
                                                <th width="150">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (empty($remedies)): ?>
                                                <tr>
                                                    <td colspan="9" class="text-center text-muted py-4">
                                                        <i class="fas fa-capsules fa-2x mb-2 d-block"></i>
                                                        No remedies found
                                                    