<?php
$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 (d.name_en LIKE ? OR d.name_ar LIKE ?)";
    $params[] = "%$search_name%";
    $params[] = "%$search_name%";
}
if ($search_dept) {
    $where .= " AND d.department_id = ?";
    $params[] = $search_dept;
}

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

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

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

// --- AJAX HANDLER ---
if (isset($_GET['ajax_search'])) {
    ob_start();
    if (empty($doctors)):
    ?>
    <tr>
        <td colspan="5" class="text-center py-5 text-muted">
            <i class="bi bi-person-badge display-4 d-block mb-3"></i>
            <?php echo __('no_doctors_found'); ?>
        </td>
    </tr>
    <?php else: ?>
    <?php foreach ($doctors as $d): ?>
    <tr>
        <td class="px-4">
            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($d['name_'.$lang]); ?></div>
            <small class="text-muted"><?php echo htmlspecialchars($d['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
        </td>
        <td><?php echo htmlspecialchars($d['specialization_'.$lang]); ?></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($d['department_name'] ?: '-'); ?>
            </span>
        </td>
        <td>
            <div class="small text-secondary"><i class="bi bi-telephone me-1"></i> <?php echo htmlspecialchars($d['tel'] ?: '-'); ?></div>
            <div class="small text-secondary"><i class="bi bi-envelope me-1"></i> <?php echo htmlspecialchars($d['email'] ?: '-'); ?></div>
        </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="showEditDoctorModal(<?php echo htmlspecialchars(json_encode($d, 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-warning py-1 px-2 border-end" 
                        onclick="showDoctorHolidays(<?php echo $d['id']; ?>, '<?php echo htmlspecialchars($d['name_'.$lang]); ?>')"
                        data-bs-toggle="tooltip" title="Holidays">
                    <i class="bi bi-calendar-x"></i>
                </button>
                <button class="btn btn-link text-danger py-1 px-2" 
                        onclick="showDeleteDoctorModal(<?php echo $d['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, $totalDoctors); ?> <?php echo __('of'); ?> <?php echo $totalDoctors; ?>
        </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="#" data-page="<?php echo $page - 1; ?>" 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="#" data-page="<?php echo $p; ?>">
                            <?php echo $p; ?>
                        </a>
                    </li>
                    <?php 
                    $prev_page = $p;
                endforeach; 
                ?>
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" 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 __('doctors'); ?></h3>
    <button class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#addDoctorModal">
        <i class="bi bi-person-plus-fill me-1"></i> <?php echo __('add_doctor'); ?>
    </button>
</div>

<!-- Search Bar -->
<div class="card shadow-sm border-0 mb-4">
    <div class="card-body">
        <form id="doctorsSearchForm" class="row g-3" onsubmit="return false;">
            <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="doctorSearchName" class="form-control bg-light border-start-0" placeholder="<?php echo __('name'); ?>" value="<?php echo htmlspecialchars($search_name); ?>">
                </div>
            </div>
            <div class="col-md-4">
                <select name="department_id" id="doctorSearchDept" 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']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-secondary w-100" onclick="fetchDoctors(1)"><?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 __('specialization'); ?></th>
                        <th class="py-3"><?php echo __('department'); ?></th>
                        <th class="py-3"><?php echo __('contact'); ?></th>
                        <th class="py-3 text-end px-4"><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="doctorsTableBody">
                    <?php if (empty($doctors)): ?>
                    <tr>
                        <td colspan="5" class="text-center py-5 text-muted">
                            <i class="bi bi-person-badge display-4 d-block mb-3"></i>
                            <?php echo __('no_doctors_found'); ?>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($doctors as $d): ?>
                    <tr>
                        <td class="px-4">
                            <div class="fw-semibold text-dark"><?php echo htmlspecialchars($d['name_'.$lang]); ?></div>
                            <small class="text-muted"><?php echo htmlspecialchars($d['name_'.($lang == 'en' ? 'ar' : 'en')]); ?></small>
                        </td>
                        <td><?php echo htmlspecialchars($d['specialization_'.$lang]); ?></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($d['department_name'] ?: '-'); ?>
                            </span>
                        </td>
                        <td>
                            <div class="small text-secondary"><i class="bi bi-telephone me-1"></i> <?php echo htmlspecialchars($d['tel'] ?: '-'); ?></div>
                            <div class="small text-secondary"><i class="bi bi-envelope me-1"></i> <?php echo htmlspecialchars($d['email'] ?: '-'); ?></div>
                        </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="showEditDoctorModal(<?php echo htmlspecialchars(json_encode($d, 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-warning py-1 px-2 border-end" 
                                        onclick="showDoctorHolidays(<?php echo $d['id']; ?>, '<?php echo htmlspecialchars($d['name_'.$lang]); ?>')"
                                        data-bs-toggle="tooltip" title="Holidays">
                                    <i class="bi bi-calendar-x"></i>
                                </button>
                                <button class="btn btn-link text-danger py-1 px-2" 
                                        onclick="showDeleteDoctorModal(<?php echo $d['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="doctorsPagination">
        <?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, $totalDoctors); ?> <?php echo __('of'); ?> <?php echo $totalDoctors; ?>
            </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="#" data-page="<?php echo $page - 1; ?>" 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="#" data-page="<?php echo $p; ?>">
                                <?php echo $p; ?>
                            </a>
                        </li>
                        <?php 
                        $prev_page = $p;
                    endforeach; 
                    ?>
                    <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="#" data-page="<?php echo $page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
        </div>
    </div>
</div>

<!-- Doctor Holidays Modal -->
<div class="modal fade" id="doctorHolidaysModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold text-secondary" id="doctorHolidaysTitle">Doctor Holidays</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body pt-3">
                <input type="hidden" id="holidayDoctorId">
                <form id="addHolidayForm" onsubmit="addDoctorHoliday(); return false;">
                    <div class="row g-2 mb-3">
                        <div class="col-md-5">
                            <label class="small text-muted">Start Date</label>
                            <input type="date" id="holidayStartDate" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-md-5">
                            <label class="small text-muted">End Date</label>
                            <input type="date" id="holidayEndDate" class="form-control form-control-sm" required>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary btn-sm w-100">Add</button>
                        </div>
                        <div class="col-12 mt-1">
                            <input type="text" id="holidayNote" class="form-control form-control-sm" placeholder="Note (optional)">
                        </div>
                    </div>
                </form>
                
                <h6 class="small text-muted text-uppercase fw-bold mb-2">Current Holidays</h6>
                <div class="table-responsive" style="max-height: 200px; overflow-y: auto;">
                    <table class="table table-sm table-bordered mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Start</th>
                                <th>End</th>
                                <th>Note</th>
                                <th style="width: 50px;"></th>
                            </tr>
                        </thead>
                        <tbody id="holidaysListBody">
                            <tr><td colspan="4" class="text-center text-muted">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchName = document.getElementById('doctorSearchName');
    const searchDept = document.getElementById('doctorSearchDept');
    const tableBody = document.getElementById('doctorsTableBody');
    const paginationContainer = document.getElementById('doctorsPagination');

    let timeout = null;

    if (searchName) {
        searchName.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => fetchDoctors(1), 300);
        });
    }

    if (searchDept) {
        searchDept.addEventListener('change', function() {
            fetchDoctors(1);
        });
    }

    // Event delegation for pagination clicks
    if (paginationContainer) {
        paginationContainer.addEventListener('click', function(e) {
            e.preventDefault();
            const link = e.target.closest('.page-link');
            if (link && !link.parentElement.classList.contains('disabled')) {
                const page = link.getAttribute('data-page');
                if (page) fetchDoctors(page);
            }
        });
    }
});

function fetchDoctors(page) {
    const name = document.getElementById('doctorSearchName').value;
    const dept = document.getElementById('doctorSearchDept').value;
    const tableBody = document.getElementById('doctorsTableBody');
    const paginationContainer = document.getElementById('doctorsPagination');

    if (tableBody) tableBody.style.opacity = '0.5';

    const params = new URLSearchParams();
    if (name) params.append('name', name);
    if (dept) params.append('department_id', dept);
    params.append('page', page);
    params.append('ajax_search', '1');

    fetch('doctors.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 doctors:', error);
            if (tableBody) tableBody.style.opacity = '1';
        });
}

function showDoctorHolidays(doctorId, doctorName) {
    document.getElementById('holidayDoctorId').value = doctorId;
    document.getElementById('doctorHolidaysTitle').innerText = 'Holidays - ' + doctorName;
    
    // Clear form
    document.getElementById('holidayStartDate').value = '';
    document.getElementById('holidayEndDate').value = '';
    document.getElementById('holidayNote').value = '';
    
    // Fetch holidays
    fetchHolidays(doctorId);
    
    var modal = new bootstrap.Modal(document.getElementById('doctorHolidaysModal'));
    modal.show();
}

function fetchHolidays(doctorId) {
    fetch('api/doctor_holidays.php?doctor_id=' + doctorId)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('holidaysListBody');
            tbody.innerHTML = '';
            
            if (data.success && data.holidays.length > 0) {
                data.holidays.forEach(h => {
                    tbody.innerHTML += `
                        <tr>
                            <td>${h.start_date}</td>
                            <td>${h.end_date}</td>
                            <td>${h.note || '-'}</td>
                            <td class="text-center">
                                <button class="btn btn-link text-danger p-0" onclick="deleteDoctorHoliday(${h.id})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No holidays found.</td></tr>';
            }
        })
        .catch(err => console.error(err));
}

function addDoctorHoliday() {
    const doctorId = document.getElementById('holidayDoctorId').value;
    const start = document.getElementById('holidayStartDate').value;
    const end = document.getElementById('holidayEndDate').value;
    const note = document.getElementById('holidayNote').value;
    
    if (!start || !end) return;
    
    fetch('api/doctor_holidays.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            action: 'create',
            doctor_id: doctorId,
            start_date: start,
            end_date: end,
            note: note
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            fetchHolidays(doctorId); // Refresh list
            document.getElementById('holidayStartDate').value = '';
            document.getElementById('holidayEndDate').value = '';
            document.getElementById('holidayNote').value = '';
        } else {
            alert('Error adding holiday: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(err => console.error(err));
}

function deleteDoctorHoliday(id) {
    if (!confirm('Delete this holiday?')) return;
    
    const doctorId = document.getElementById('holidayDoctorId').value;
    
    fetch('api/doctor_holidays.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            action: 'delete',
            id: id
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            fetchHolidays(doctorId); // Refresh list
        } else {
            alert('Error deleting holiday: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(err => console.error(err));
}
</script>