<?php
// Fetch Departments for Dropdown
$deptQuery = "SELECT * FROM departments ORDER BY name_$lang";
$deptStmt = $db->query($deptQuery);
$all_departments = $deptStmt->fetchAll();

// Pagination and Search
$search_name = $_GET['name'] ?? '';
$search_dept = $_GET['department_id'] ?? '';
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$where = "WHERE 1=1";
$params = [];

if ($search_name) {
    $where .= " AND (s.name_en LIKE ? OR s.name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}
if ($search_dept) {
    $where .= " AND s.department_id = ?";
    $params[] = $search_dept;
}

// Count Total
$countQuery = "SELECT COUNT(*) FROM services s $where";
$stmt = $db->prepare($countQuery);
$stmt->execute($params);
$totalServices = $stmt->fetchColumn();
$totalPages = ceil($totalServices / $limit);

// Fetch Data
$query = "
    SELECT s.*, d.name_$lang as department_name 
    FROM services s 
    LEFT JOIN departments d ON s.department_id = d.id 
    $where
    ORDER BY s.id DESC
    LIMIT $limit OFFSET $offset";

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

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold text-secondary"><?php echo __('services'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addServiceModal">
        <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_service'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form method="GET" action="hospital_services.php" 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" class="form-control bg-light border-start-0" placeholder="<?php echo __('search_by_name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>">
                </div>
            </div>
            <div class="col-md-4">
                <select name="department_id" class="form-select bg-light">
                    <option value=""><?php echo __('department'); ?> (<?php echo __('all'); ?>)</option>
                    <?php foreach ($all_departments as $dept): ?>
                        <option value="<?php echo $dept['id']; ?>" <?php echo $search_dept == $dept['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($dept['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"><?php echo __('name'); ?></th>
                        <th class="py-3"><?php echo __('department'); ?></th>
                        <th class="py-3"><?php echo __('price'); ?></th>
                        <th class="py-3"><?php echo __('status'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($services)): ?>
                    <tr>
                        <td colspan="5" class="text-center py-5 text-muted">
                            <i class="bi bi-gear-wide-connected display-4 d-block mb-3"></i>
                            <?php echo __('no_services_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($services as $s): ?>
                    <tr>
                        <td class="px-4">
                            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($s['name_'.$lang]); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($s['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
                        </td>
                        <td>
                            <span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 px-2 py-1">
                                <?php echo htmlspecialchars($s['department_name'] ?: '-'); ?>
                            </span>
                        </td>
                        <td class="fw-bold text-success">
                            <?php echo format_currency($s['price']); ?>
                        </td>
                        <td>
                            <?php if ($s['is_active']): ?>
                                <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-2 py-1">
                                    <i class="bi bi-check-circle me-1"></i> <?php echo __('active'); ?>
                                </span>
                            <?php else: ?>
                                <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-25 px-2 py-1">
                                    <i class="bi bi-slash-circle me-1"></i> <?php echo __('inactive'); ?>
                                </span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end px-4">
                            <div class="btn-group shadow-sm border rounded bg-white">
                                <button class="btn btn-link text-primary py-1 px-2 border-end" 
                                        onclick="showEditServiceModal(<?php echo htmlspecialchars(json_encode($s, 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="showDeleteServiceModal(<?php echo $s['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 -->
        <?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, $totalServices); ?> <?php echo __('of'); ?> <?php echo $totalServices; ?>
            </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); ?>&department_id=<?php echo urlencode($search_dept); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&name=<?php echo urlencode($search_name); ?>&department_id=<?php echo urlencode($search_dept); ?>">
                            <?php echo $i; ?>
                        </a>
                    </li>
                    <?php endfor; ?>
                    <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); ?>&department_id=<?php echo urlencode($search_dept); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add Service Modal -->
<div class="modal fade" id="addServiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="hospital_services.php" class="modal-content">
            <input type="hidden" name="action" value="add_service">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('add_service'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label"><?php echo __('name_en'); ?></label>
                    <input type="text" name="name_en" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('name_ar'); ?></label>
                    <input type="text" name="name_ar" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('department'); ?></label>
                    <select name="department_id" class="form-select" required>
                        <option value=""><?php echo __('select_department'); ?></option>
                        <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>">
                                <?php echo htmlspecialchars($dept['name_'.$lang]); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('price'); ?></label>
                    <input type="number" name="price" step="0.01" class="form-control" required>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" name="is_active" id="addServiceActive" checked>
                    <label class="form-check-label" for="addServiceActive"><?php echo __('active'); ?></label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Service Modal -->
<div class="modal fade" id="editServiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="hospital_services.php" class="modal-content">
            <input type="hidden" name="action" value="edit_service">
            <input type="hidden" name="id" id="editServiceId">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('edit_service'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label"><?php echo __('name_en'); ?></label>
                    <input type="text" name="name_en" id="editServiceNameEn" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('name_ar'); ?></label>
                    <input type="text" name="name_ar" id="editServiceNameAr" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('department'); ?></label>
                    <select name="department_id" id="editServiceDeptId" class="form-select" required>
                        <option value=""><?php echo __('select_department'); ?></option>
                        <?php foreach ($all_departments as $dept): ?>
                            <option value="<?php echo $dept['id']; ?>">
                                <?php echo htmlspecialchars($dept['name_'.$lang]); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label"><?php echo __('price'); ?></label>
                    <input type="number" name="price" id="editServicePrice" step="0.01" class="form-control" required>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" name="is_active" id="editServiceActive">
                    <label class="form-check-label" for="editServiceActive"><?php echo __('active'); ?></label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-primary"><?php echo __('save_changes'); ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Service Modal -->
<div class="modal fade" id="deleteServiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="hospital_services.php" class="modal-content">
            <input type="hidden" name="action" value="delete_service">
            <input type="hidden" name="id" id="deleteServiceId">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('delete_service'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p><?php echo __('are_you_sure_delete_service'); ?></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-danger"><?php echo __('delete'); ?></button>
            </div>
        </form>
    </div>
</div>

<script>
function showEditServiceModal(service) {
    document.getElementById('editServiceId').value = service.id;
    document.getElementById('editServiceNameEn').value = service.name_en;
    document.getElementById('editServiceNameAr').value = service.name_ar;
    document.getElementById('editServiceDeptId').value = service.department_id;
    document.getElementById('editServicePrice').value = service.price;
    document.getElementById('editServiceActive').checked = service.is_active == 1;
    
    var modal = new bootstrap.Modal(document.getElementById('editServiceModal'));
    modal.show();
}

function showDeleteServiceModal(id) {
    document.getElementById('deleteServiceId').value = id;
    var modal = new bootstrap.Modal(document.getElementById('deleteServiceModal'));
    modal.show();
}
</script>