<?php
$search_name = $_GET['name'] ?? '';
$search_group = $_GET['group_id'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build WHERE clause
$where = "WHERE 1=1";
$params = [];

if ($search_name) {
    $where .= " AND (d.name_en LIKE ? OR d.name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}
if ($search_group) {
    $where .= " AND d.group_id = ?";
    $params[] = $search_group;
}

// Count total drugs
$countQuery = "SELECT COUNT(*) FROM drugs d $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalDrugs = $stmt->fetchColumn();
$totalPages = ceil($totalDrugs / $limit);

// Fetch drugs with pagination
$query = "
    SELECT d.*, g.name_$lang as group_name, s.name_$lang as supplier_name
    FROM drugs d 
    LEFT JOIN drugs_groups g ON d.group_id = g.id 
    LEFT JOIN suppliers s ON d.supplier_id = s.id
    $where
    ORDER BY d.id DESC
    LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($query);
$stmt->execute($params);
$drugs = $stmt->fetchAll();

// Fetch all groups for filter dropdown
$gStmt = $db->query("SELECT * FROM drugs_groups ORDER BY name_$lang");
$all_drug_groups = $gStmt->fetchAll();

// Fetch all suppliers
$sStmt = $db->query("SELECT * FROM suppliers ORDER BY name_$lang");
$all_suppliers = $sStmt->fetchAll();

$sys_settings = get_system_settings();
$currency_symbol = $sys_settings['currency_symbol'] ?? '$';

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($drugs)):
    ?>
    <tr>
        <td colspan="8" class="text-center py-5 text-muted">
            <i class="bi bi-capsule display-4 d-block mb-3"></i>
            <?php echo __('no_drugs_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($drugs as $drug): ?>
    <tr>
        <td class="px-4 fw-medium text-secondary"><?php echo $drug['id']; ?></td>
        <td>
            <?php if (!empty($drug['image'])): ?>
                <img src="<?php echo htmlspecialchars($drug['image']); ?>" class="rounded" style="width: 40px; height: 40px; object-fit: cover;">
            <?php else: ?>
                <div class="bg-light rounded d-flex align-items-center justify-content-center text-muted" style="width: 40px; height: 40px;">
                    <i class="bi bi-image"></i>
                </div>
            <?php endif; ?>
        </td>
        <td>
            <div class="d-flex align-items-center">
                <div class="text-wrap" style="word-break: break-word;">
                    <div class="fw-semibold text-dark"><?php echo htmlspecialchars($drug['name_'.$lang]); ?></div>
                    <small class="text-muted d-block"><?php echo htmlspecialchars($drug['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
                </div>
            </div>
        </td>
        <td>
            <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25 px-2 py-1 text-wrap text-start">
                <?php echo htmlspecialchars($drug['group_name'] ?? '-'); ?>
            </span>
        </td>
        <td class="text-nowrap"><?php echo htmlspecialchars($drug['expiry_date'] ?? '-'); ?></td>
        <td class="text-wrap" style="max-width: 150px;"><?php echo htmlspecialchars($drug['supplier_name'] ?? '-'); ?></td>
        <td class="text-secondary fw-bold"><?php echo format_currency($drug['price']); ?></td>
        <td class="text-end px-4 text-nowrap">
            <div class="btn-group shadow-sm border rounded bg-white">
                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                        onclick="showEditDrugModal(<?php echo htmlspecialchars(json_encode($drug, JSON_UNESCAPED_UNICODE)); ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                    <i class="bi bi-pencil-square"></i>
                </button>
                <button class="btn btn-link text-danger py-1 px-2" 
                        onclick="showDeleteDrugModal(<?php echo $drug['id']; ?>)"
                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                    <i class="bi bi-trash3"></i>
                </button>
            </div>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php endif;
    $table_html = ob_get_clean();

    ob_start();
    if ($totalPages > 1): ?>
    <div class="d-flex justify-content-between align-items-center p-3 border-top">
        <div class="text-muted small">
            <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalDrugs); ?> <?php echo __('of'); ?> <?php echo $totalDrugs; ?>
        </div>
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <?php
                $range = 2;
                $pages_to_show = [];
                $pages_to_show[] = 1;
                if ($totalPages > 1) { $pages_to_show[] = $totalPages; }
                for ($i = $page - $range; $i <= $page + $range; $i++) {
                    if ($i > 1 && $i < $totalPages) { $pages_to_show[] = $i; }
                }
                $pages_to_show = array_unique($pages_to_show);
                sort($pages_to_show);
                
                $prev_page = 0;
                foreach ($pages_to_show as $p):
                    if ($prev_page > 0 && $p > $prev_page + 1): ?>
                        <li class="page-item disabled"><span class="page-link">...</span></li>
                    <?php endif; ?>
                    <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $p; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>">
                            <?php echo $p; ?>
                        </a>
                    </li>
                    <?php 
                    $prev_page = $p;
                endforeach; 
                ?>
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif;
    $pagination_html = ob_get_clean();

    header('Content-Type: application/json');
    echo json_encode(['html' => $table_html, 'pagination' => $pagination_html]);
    exit;
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('drugs'); ?></h3>
    <div>
        <button class="btn btn-outline-primary shadow-sm me-2" data-bs-toggle="modal" data-bs-target="#importDrugsModal">
            <i class="bi bi-upload me-1"></i> <?php echo __('import'); ?>
        </button>
        <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addDrugModal" onclick="resetDrugModal()">
            <i class="bi bi-plus-circle me-1"></i> <?php echo __('add_drug'); ?>
        </button>
    </div>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="GET" action="" class="row g-3">
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text bg-light border-end-0 text-muted"><i class="bi bi-search"></i></span>
                    <input type="text" name="name" id="drugSearchInput" class="form-control bg-light border-start-0" placeholder="<?php echo __('drug_name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>" autocomplete="off">
                </div>
            </div>
            <div class="col-md-4">
                <select name="group_id" class="form-select bg-light">
                    <option value=""><?php echo __('drug_group'); ?> (<?php echo __('all'); ?>)</option>
                    <?php foreach ($all_drug_groups as $group): ?>
                        <option value="<?php echo $group['id']; ?>" <?php echo $search_group == $group['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($group['name_' . $lang]); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-secondary w-100"><?php echo __('search'); ?></button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light text-secondary">
                    <tr>
                        <th class="px-4 py-3">#</th>
                        <th class="py-3" style="width: 50px;"><?php echo __('image'); ?></th>
                        <th class="py-3" style="width: 30%; min-width: 200px;"><?php echo __('drug_name'); ?></th>
                        <th class="py-3"><?php echo __('drug_group'); ?></th>
                        <th class="py-3"><?php echo __('expiry_date'); ?></th>
                        <th class="py-3" style="max-width: 150px;"><?php echo __('supplier'); ?></th>
                        <th class="py-3"><?php echo __('price'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="drugsTableBody">
                    <?php if (empty($drugs)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-5 text-muted">
                            <i class="bi bi-capsule display-4 d-block mb-3"></i>
                            <?php echo __('no_drugs_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($drugs as $drug): ?>
                    <tr>
                        <td class="px-4 fw-medium text-secondary"><?php echo $drug['id']; ?></td>
                        <td>
                            <?php if (!empty($drug['image'])): ?>
                                <img src="<?php echo htmlspecialchars($drug['image']); ?>" class="rounded" style="width: 40px; height: 40px; object-fit: cover;">
                            <?php else: ?>
                                <div class="bg-light rounded d-flex align-items-center justify-content-center text-muted" style="width: 40px; height: 40px;">
                                    <i class="bi bi-image"></i>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="text-wrap" style="word-break: break-word;">
                                    <div class="fw-semibold text-dark"><?php echo htmlspecialchars($drug['name_'.$lang]); ?></div>
                                    <small class="text-muted d-block"><?php echo htmlspecialchars($drug['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25 px-2 py-1 text-wrap text-start">
                                <?php echo htmlspecialchars($drug['group_name'] ?? '-'); ?>
                            </span>
                        </td>
                        <td class="text-nowrap"><?php echo htmlspecialchars($drug['expiry_date'] ?? '-'); ?></td>
                        <td class="text-wrap" style="max-width: 150px;"><?php echo htmlspecialchars($drug['supplier_name'] ?? '-'); ?></td>
                        <td class="text-secondary fw-bold"><?php echo format_currency($drug['price']); ?></td>
                        <td class="text-end px-4 text-nowrap">
                            <div class="btn-group shadow-sm border rounded bg-white">
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                        onclick="showEditDrugModal(<?php echo htmlspecialchars(json_encode($drug, JSON_UNESCAPED_UNICODE)); ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('edit'); ?>">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button class="btn btn-link text-danger py-1 px-2" 
                                        onclick="showDeleteDrugModal(<?php echo $drug['id']; ?>)"
                                        data-bs-toggle="tooltip" title="<?php echo __('delete'); ?>">
                                    <i class="bi bi-trash3"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <div id="drugsPagination">
        <?php if ($totalPages > 1): ?>
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <div class="text-muted small">
                <?php echo __('showing'); ?> <?php echo $offset + 1; ?> - <?php echo min($offset + $limit, $totalDrugs); ?> <?php echo __('of'); ?> <?php echo $totalDrugs; ?>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php
                    $range = 2; // Number of pages around current page
                    $pages_to_show = [];
                    
                    // Always show first and last
                    $pages_to_show[] = 1;
                    if ($totalPages > 1) {
                        $pages_to_show[] = $totalPages;
                    }
                    
                    // Show range around current page
                    for ($i = $page - $range; $i <= $page + $range; $i++) {
                        if ($i > 1 && $i < $totalPages) {
                            $pages_to_show[] = $i;
                        }
                    }
                    
                    // Remove duplicates and sort
                    $pages_to_show = array_unique($pages_to_show);
                    sort($pages_to_show);
                    
                    $prev_page = 0;
                    foreach ($pages_to_show as $p):
                        // If there's a gap, show ellipsis
                        if ($prev_page > 0 && $p > $prev_page + 1): ?>
                            <li class="page-item disabled"><span class="page-link">...</span></li>
                        <?php endif; ?>
                        
                        <li class="page-item <?php echo $page == $p ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $p; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&name=<?php echo urlencode($search_name); ?>&group_id=<?php echo urlencode($search_group); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add/Edit Drug Modal -->
<div class="modal fade" id="addDrugModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="drugModalTitle"><?php echo __('add_drug'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="" enctype="multipart/form-data">
                <input type="hidden" name="action" id="drugAction" value="add_drug">
                <input type="hidden" name="id" id="drugId">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_en'); ?> <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="name_en" id="drugNameEn" required>
                                <button type="button" class="btn btn-outline-secondary" onclick="translateDrug('en', 'ar')" title="<?php echo __('auto_translate'); ?>">
                                    <i class="bi bi-translate"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('name_ar'); ?> <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="name_ar" id="drugNameAr" required>
                                <button type="button" class="btn btn-outline-secondary" onclick="translateDrug('ar', 'en')" title="<?php echo __('auto_translate'); ?>">
                                    <i class="bi bi-translate"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('drug_group'); ?></label>
                            <select class="form-select" name="group_id" id="drugGroupId">
                                <option value=""><?php echo __('select_group'); ?></option>
                                <?php foreach ($all_drug_groups as $group): ?>
                                    <option value="<?php echo $group['id']; ?>">
                                        <?php echo htmlspecialchars($group['name_' . $lang]); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('price'); ?></label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo htmlspecialchars($currency_symbol); ?></span>
                                <input type="number" step="0.01" class="form-control" name="price" id="drugPrice">
                            </div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('expiry_date'); ?></label>
                            <input type="date" class="form-control" name="expiry_date" id="drugExpiry">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('supplier'); ?></label>
                            <select class="form-select" name="supplier_id" id="drugSupplierId">
                                <option value=""><?php echo __('select_supplier'); ?></option>
                                <?php foreach ($all_suppliers as $supplier): ?>
                                    <option value="<?php echo $supplier['id']; ?>">
                                        <?php echo htmlspecialchars($supplier['name_' . $lang]); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('default_dosage'); ?></label>
                            <input type="text" class="form-control" name="default_dosage" id="drugDosage">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><?php echo __('default_instructions'); ?></label>
                            <input type="text" class="form-control" name="default_instructions" id="drugInstructions">
                        </div>

                        <div class="col-md-12">
                            <label class="form-label"><?php echo __('image'); ?></label>
                            <input type="file" class="form-control" name="image" accept="image/*" onchange="previewImage(this)">
                            <div id="drugImagePreview" class="mt-2"></div>
                        </div>

                        <div class="col-12">
                            <label class="form-label"><?php echo __('description_en'); ?></label>
                            <textarea class="form-control" name="description_en" id="drugDescEn" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label"><?php echo __('description_ar'); ?></label>
                            <textarea class="form-control" name="description_ar" id="drugDescAr" rows="2"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Import Drugs Modal -->
<div class="modal fade" id="importDrugsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><?php echo __('import_drugs'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="" enctype="multipart/form-data">
                <input type="hidden" name="action" value="import_drugs">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label"><?php echo __('upload_file'); ?> (CSV, Excel) <span class="text-danger">*</span></label>
                        <input type="file" class="form-control" name="csv_file" accept=".csv, .xlsx, .xls" required>
                    </div>
                    <div class="alert alert-info small mb-0">
                        <i class="bi bi-info-circle me-1"></i> <?php echo __('csv_format_drugs'); ?>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __('import'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Drug Modal -->
<div class="modal fade" id="deleteDrugModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><?php echo __('delete_drug'); ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="action" value="delete_drug">
                <input type="hidden" name="id" id="deleteDrugId">
                <div class="modal-body p-4 text-center">
                    <div class="mb-3 text-danger">
                        <i class="bi bi-exclamation-triangle display-1"></i>
                    </div>
                    <p class="mb-0 fs-5"><?php echo __('are_you_sure_delete'); ?></p>
                    <p class="text-muted small"><?php echo __('action_cannot_be_undone'); ?></p>
                </div>
                <div class="modal-footer bg-light justify-content-center">
                    <button type="button" class="btn btn-secondary px-4" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-danger px-4"><?php echo __('delete'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetDrugModal() {
    document.getElementById('drugModalTitle').textContent = '<?php echo __('add_drug'); ?>';
    document.getElementById('drugAction').value = 'add_drug';
    document.getElementById('drugId').value = '';
    
    document.getElementById('drugNameEn').value = '';
    document.getElementById('drugNameAr').value = '';
    document.getElementById('drugGroupId').value = '';
    document.getElementById('drugPrice').value = '';
    document.getElementById('drugDosage').value = '';
    document.getElementById('drugInstructions').value = '';
    document.getElementById('drugDescEn').value = '';
    document.getElementById('drugDescAr').value = '';
    document.getElementById('drugExpiry').value = '';
    document.getElementById('drugSupplierId').value = '';
    document.getElementById('drugImagePreview').innerHTML = '';
    document.querySelector('input[name="image"]').value = '';
}

function showEditDrugModal(drug) {
    document.getElementById('drugModalTitle').textContent = '<?php echo __('edit_drug'); ?>';
    document.getElementById('drugAction').value = 'edit_drug';
    document.getElementById('drugId').value = drug.id;
    
    document.getElementById('drugNameEn').value = drug.name_en;
    document.getElementById('drugNameAr').value = drug.name_ar;
    document.getElementById('drugGroupId').value = drug.group_id || '';
    document.getElementById('drugPrice').value = drug.price;
    document.getElementById('drugDosage').value = drug.default_dosage;
    document.getElementById('drugInstructions').value = drug.default_instructions;
    document.getElementById('drugDescEn').value = drug.description_en;
    document.getElementById('drugDescAr').value = drug.description_ar;
    document.getElementById('drugExpiry').value = drug.expiry_date || '';
    document.getElementById('drugSupplierId').value = drug.supplier_id || '';
    
    const preview = document.getElementById('drugImagePreview');
    if (drug.image) {
        preview.innerHTML = `<img src="${drug.image}" class="rounded shadow-sm" style="max-height: 100px;">`;
    } else {
        preview.innerHTML = '';
    }
    
    var modal = new bootstrap.Modal(document.getElementById('addDrugModal'));
    modal.show();
}

function showDeleteDrugModal(id) {
    document.getElementById('deleteDrugId').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteDrugModal'));
    modal.show();
}

function previewImage(input) {
    const preview = document.getElementById('drugImagePreview');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.innerHTML = `<img src="${e.target.result}" class="rounded shadow-sm" style="max-height: 100px;">`;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

async function translateDrug(source, target) {
    const text = document.getElementById(source === 'en' ? 'drugNameEn' : 'drugNameAr').value;
    if (!text) return;
    
    const btn = event.currentTarget;
    const originalContent = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
    
    try {
        const response = await fetch('api/ai_report.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                target: 'translate',
                text: text,
                from: source === 'en' ? 'English' : 'Arabic',
                to: target === 'en' ? 'English' : 'Arabic'
            })
        });
        const data = await response.json();
        if (data.success) {
            document.getElementById(target === 'en' ? 'drugNameEn' : 'drugNameAr').value = data.report;
        } else {
            alert('Translation failed: ' + (data.error || 'Unknown error'));
        }
    } catch (e) {
        console.error(e);
        alert('Network error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalContent;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('drugSearchInput');
    const tableBody = document.getElementById('drugsTableBody');
    const paginationContainer = document.getElementById('drugsPagination');
    const groupIdSelect = document.querySelector('select[name="group_id"]');

    let timeout = null;

    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.trim();
            const groupId = groupIdSelect ? groupIdSelect.value : '';

            // Search after 2 chars or if cleared
            if (query.length >= 2 || query.length === 0) {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    fetchDrugs(query, groupId);
                }, 300);
            }
        });
    }
    
    if (groupIdSelect) {
        groupIdSelect.addEventListener('change', function() {
            const query = searchInput ? searchInput.value.trim() : '';
             fetchDrugs(query, this.value);
        });
    }

    function fetchDrugs(query, groupId) {
        if (tableBody) tableBody.style.opacity = '0.5';
        
        const params = new URLSearchParams();
        if (query) params.append('name', query);
        if (groupId) params.append('group_id', groupId);
        params.append('ajax_search', '1');

        fetch('drugs.php?' + params.toString())
            .then(response => response.json())
            .then(data => {
                if (tableBody) {
                    tableBody.innerHTML = data.html;
                    tableBody.style.opacity = '1';
                }
                if (paginationContainer) {
                    paginationContainer.innerHTML = data.pagination;
                }
                
                // Re-initialize tooltips
                var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
                var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                  return new bootstrap.Tooltip(tooltipTriggerEl)
                })
            })
            .catch(error => {
                console.error('Error fetching drugs:', error);
                if (tableBody) tableBody.style.opacity = '1';
            });
    }
});
</script>