<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();

$page_title = 'Administrar Profesores';

// Pagination and Search
$per_page = 12;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $per_page;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$career_filter = isset($_GET['career']) ? (int)$_GET['career'] : '';

// Get careers for filter dropdown
$careers_stmt = $pdo->query("SELECT id, name FROM careers ORDER BY name");
$careers = $careers_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get total count
$count_query = "SELECT COUNT(*) as total FROM users u JOIN teachers t ON u.id = t.user_id WHERE u.deleted_at IS NULL";
$params = [];
if ($search) {
    $count_query .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.username LIKE ? OR t.department LIKE ? OR t.dni LIKE ? OR t.phone LIKE ? OR t.address LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%"];
}
if ($career_filter) {
    $count_query .= " AND t.career_id = ?";
    $params[] = $career_filter;
}
$total_stmt = $pdo->prepare($count_query);
$total_stmt->execute($params);
$total_teachers = $total_stmt->fetch()['total'];
$total_pages = ceil($total_teachers / $per_page);

$content = '
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Profesores</h3>
                <div class="card-tools">
                    <div class="total-teachers-badge">
                        <i class="fas fa-chalkboard-teacher text-warning me-1"></i>
                        <span class="fw-bold text-warning">' . $total_teachers . '</span>
                        <small class="text-muted ms-1">Profesores</small>
                    </div>
                    <div class="btn-group">
                        <a href="' . url('admin/teachers/new') . '" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> Agregar Profesor</a>
                        <a href="' . url('admin/export-teachers?format=excel&search=' . urlencode($search)) . '" class="btn btn-success btn-sm"><i class="fas fa-file-excel"></i> Exportar a Excel</a>
                        <a href="' . url('admin/export-teachers?format=pdf&search=' . urlencode($search)) . '" class="btn btn-danger btn-sm"><i class="fas fa-file-pdf"></i> Exportar a PDF</a>
                    </div>
                </div>
            </div>
            <div class="card-header">
                <form method="get" class="row g-3">
                    <div class="col-md-5">
                        <input type="text" name="search" class="form-control" placeholder="Buscar profesores..." value="' . htmlspecialchars($search) . '">
                    </div>
                    <div class="col-md-4">
                        <select name="career" class="form-select" onchange="this.form.submit()">
                            <option value="">Todos los programas</option>';
foreach ($careers as $career) {
    $selected = ($career_filter == $career['id']) ? ' selected' : '';
    $content .= '<option value="' . $career['id'] . '"' . $selected . '>' . htmlspecialchars($career['name']) . '</option>';
}
$content .= '
                        </select>
                    </div>
                    <div class="col-md-3">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">Buscar</button>
                            ' . (($search || $career_filter) ? '<a href="' . url('admin/teachers') . '" class="btn btn-secondary flex-fill">Limpiar</a>' : '') . '
                        </div>
                    </div>
                </form>
            </div>
            <div class="card-body">
                <div class="row">';

// Build query with search and pagination
$query = "SELECT u.*, t.career_id, t.department, t.bio, t.dni, t.birth_date, t.address, t.phone, t.gender, c.name as career_name FROM users u JOIN teachers t ON u.id = t.user_id LEFT JOIN careers c ON t.career_id = c.id WHERE u.deleted_at IS NULL";
$params = [];
if ($search) {
    $query .= " AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR u.username LIKE ? OR t.department LIKE ? OR t.dni LIKE ? OR t.phone LIKE ? OR t.address LIKE ?)";
    $params = ["%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%", "%$search%"];
}
if ($career_filter) {
    $query .= " AND t.career_id = ?";
    $params[] = $career_filter;
}
$query .= " ORDER BY u.created_at DESC LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$teachers = $stmt->fetchAll();

if (count($teachers) > 0) {
    foreach ($teachers as $teacher) {
        $avatar = (isset($teacher['photo']) && $teacher['photo']) ? '<img src="../' . htmlspecialchars($teacher['photo']) . '" class="img-fluid rounded-circle" style="width: 200px; height: 200px; object-fit: cover;" alt="Teacher Photo">' : '<div class="text-center text-muted"><i class="fas fa-chalkboard-teacher fa-2x"></i></div>';

        $content .= '<div class="col-md-6 col-lg-4 mb-4">
            <div class="card h-100 job-card-modern shadow-sm">
                <div class="card-header text-center bg-gradient-cambridge">
                    <div class="company-logo-container">
                        ' . $avatar . '
                    </div>
                    <div class="company-logo-container mb-1 text-white font-weight-bold">
                        ' . htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']) . '
                    </div>

                    <div class="mt-2">
                        <span class="badge bg-celadon text-black-bean">Profesor</span>
                    </div>
                </div>
                <div class="card-body">
                    <div class="job-details">
                        <div class="detail-row">
                            <span class="detail-label">📧 Email:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['email']) . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">🎓 Programa:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['career_name'] ?: 'No especificado') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">🆔 DNI:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['dni'] ?: 'No especificado') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">📅 Nacimiento:</span>
                            <span class="detail-value">' . ($teacher['birth_date'] ? date('d/m/Y', strtotime($teacher['birth_date'])) : 'No especificado') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">📍 Dirección:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['address'] ?: 'No especificada') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">📞 Teléfono:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['phone'] ?: 'No especificado') . '</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">⚧ Género:</span>
                            <span class="detail-value">' . htmlspecialchars($teacher['gender'] ?: 'No especificado') . '</span>
                        </div>
                        ' . ($teacher['bio'] ? '<div class="detail-row">
                            <span class="detail-label">📝 Bio:</span>
                            <span class="detail-value">' . htmlspecialchars(substr($teacher['bio'], 0, 50)) . (mb_strlen($teacher['bio']) > 50 ? '...' : '') . '</span>
                        </div>' : '') . '
                    </div>


                </div>
                <div class="card-footer bg-light">
                    <div class="d-flex justify-content-between gap-2">
                        <a href="' . url('admin/teachers/view/' . $teacher['id']) . '" class="btn btn-info btn-sm flex-fill">
                            <i class="fas fa-eye"></i> Ver
                        </a>
                        <a href="' . url('admin/teachers/edit/' . $teacher['id']) . '" class="btn btn-warning btn-sm flex-fill">
                            <i class="fas fa-edit"></i> Editar
                        </a>
                        <a href="' . url('admin/teachers/delete/' . $teacher['id']) . '" class="btn btn-danger btn-sm flex-fill" onclick="return confirm(\'¿Estás seguro de que deseas eliminar este profesor?\')">
                            <i class="fas fa-trash"></i> Borrar
                        </a>
                    </div>
                </div>
            </div>
        </div>';
    }
} else {
    $content .= '<div class="col-12">
        <div class="alert alert-info">
            <i class="icon fas fa-info"></i> No teachers found.
        </div>
    </div>';
}

$content .= '</div>
            </div>
        </div>
    </div>
</div>';

// Pagination
if ($total_pages > 1) {
    $content .= '<div class="row">
        <div class="col-12">
            <nav aria-label="Teachers pagination">
                <ul class="pagination justify-content-center">';

    // Previous button
    if ($page > 1) {
        $search_param = $search ? '?search=' . urlencode($search) . '&page=' . ($page - 1) : '?page=' . ($page - 1);
        $content .= '<li class="page-item"><a class="page-link" href="' . url('admin/teachers' . $search_param) . '">Anterior</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Anterior</span></li>';
    }

    // Page numbers
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);

    if ($start_page > 1) {
        $search_param = $search ? '?search=' . urlencode($search) . '&page=1' : '?page=1';
        $content .= '<li class="page-item"><a class="page-link" href="' . url('admin/teachers' . $search_param) . '">1</a></li>';
        if ($start_page > 2) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }

    for ($i = $start_page; $i <= $end_page; $i++) {
        $search_param = $search ? '?search=' . urlencode($search) . '&page=' . $i : '?page=' . $i;
        if ($i == $page) {
            $content .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $content .= '<li class="page-item"><a class="page-link" href="' . url('admin/teachers' . $search_param) . '">' . $i . '</a></li>';
        }
    }

    if ($end_page < $total_pages) {
        $search_param = $search ? '?search=' . urlencode($search) . '&page=' . $total_pages : '?page=' . $total_pages;
        if ($end_page < $total_pages - 1) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
        $content .= '<li class="page-item"><a class="page-link" href="' . url('admin/teachers' . $search_param) . '">' . $total_pages . '</a></li>';
    }

    // Next button
    if ($page < $total_pages) {
        $search_param = $search ? '?search=' . urlencode($search) . '&page=' . ($page + 1) : '?page=' . ($page + 1);
        $content .= '<li class="page-item"><a class="page-link" href="' . url('admin/teachers' . $search_param) . '">Siguiente</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Siguiente</span></li>';
    }

    $content .= '</ul>
            </nav>
        </div>
    </div>';
}

$content .= '
<style>
.job-card-modern {
    border: 2px solid var(--celadon);
    border-radius: 20px;
    overflow: hidden;
    background: linear-gradient(145deg, #ffffff, var(--mint-cream));
    box-shadow: 0 6px 20px rgba(121, 183, 145, 0.15);
    position: relative;
}
.job-card-modern::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--cambridge-blue), var(--celadon));
}
.job-card-modern .card-header {
    background: #9BABBF !important;
    border: none;
    padding: 2rem 1.5rem 1.5rem;
    position: relative;
}
.job-card-modern .card-header::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60%;
    height: 3px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
}
.job-card-modern .card-body {
    padding: 2rem 1.5rem;
    background: linear-gradient(180deg, rgba(237, 244, 237, 0.3), rgba(255, 255, 255, 0.8));
}
.job-card-modern .card-footer {
    border: none;
    padding: 1.5rem;
    background: var(--mint-cream);
    border-top: 2px solid var(--celadon);
}
.company-logo-container {
    margin-bottom: 1rem;
}
.detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.75rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--celadon);
    background: rgba(237, 244, 237, 0.3);
    border-radius: 8px;
    padding-left: 0.75rem;
    padding-right: 0.75rem;
    margin-left: -0.75rem;
    margin-right: -0.75rem;
}
.detail-row:last-child {
    border-bottom: none;
    margin-bottom: 0;
}
.detail-label {
    font-weight: 600;
    color: var(--caput-mortuum);
    font-size: 0.875rem;
    display: flex;
    align-items: center;
}
.detail-value {
    color: var(--black-bean);
    font-weight: 500;
    text-align: right;
    flex: 1;
    margin-left: 1rem;
}
.card-footer .btn {
    border-radius: 8px !important;
    font-weight: 500;
    padding: 0.5rem 0.25rem;
    transition: all 0.3s ease;
    border: 2px solid transparent;
    background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon));
    color: white;
    position: relative;
    overflow: hidden;
    font-size: 0.8rem;
    line-height: 1.2;
    min-height: 2.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}
.card-footer .btn::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}
.card-footer .btn:hover::before {
    left: 100%;
}
.card-footer .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(121, 183, 145, 0.3);
    border-color: var(--celadon);
}
.card-footer .btn-info {
    background: linear-gradient(135deg, var(--cambridge-blue), var(--celadon));
}
.card-footer .btn-success {
    background: linear-gradient(135deg, var(--celadon), var(--mint-cream));
    color: var(--caput-mortuum);
}
.card-footer .btn-warning {
    background: linear-gradient(135deg, #f39c12, #e67e22);
}
.card-footer .btn-danger {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
}
.badge {
    font-size: 0.75rem;
    padding: 0.5rem 0.75rem;
    border-radius: 20px;
    font-weight: 500;
    border: 1px solid rgba(255,255,255,0.3);
}
@media (max-width: 768px) {
    .detail-row {
        flex-direction: column;
        align-items: flex-start;
    }
    .detail-value {
        margin-left: 0;
        margin-top: 0.25rem;
        text-align: left;
    }
    .job-card-modern .card-header,
    .job-card-modern .card-body,
    .job-card-modern .card-footer {
        padding: 1rem;
    }
}
/* Text color improvements */
.text-white-80 {
    color: rgba(255, 255, 255, 0.8) !important;
}

/* Total Teachers Badge Styling */
.total-teachers-badge {
    display: inline-flex;
    align-items: center;
    background: linear-gradient(135deg, #fff3cd, #f3e5f5);
    border: 2px solid #ffc107;
    border-radius: 25px;
    padding: 0.5rem 1rem;
    margin-right: 0.5rem;
    box-shadow: 0 2px 8px rgba(255, 193, 7, 0.15);
    transition: all 0.3s ease;
    font-size: 0.875rem;
}

.total-teachers-badge:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(255, 193, 7, 0.25);
    border-color: #e0a800;
}

.total-teachers-badge i {
    font-size: 1rem;
}

.total-teachers-badge .fw-bold {
    font-size: 1.1rem;
    margin: 0 0.25rem;
}

.total-teachers-badge small {
    font-weight: 500;
}

/* Top buttons styling */
.card-tools .btn-group {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
}

.card-tools .btn-group .btn {
    border-radius: 0 !important;
    border: none !important;
    font-weight: 500;
    padding: 0.5rem 1rem;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.card-tools .btn-group .btn::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

.card-tools .btn-group .btn:hover::before {
    left: 100%;
}

.card-tools .btn-group .btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-tools .btn-group .btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>';

include BASE_PATH . '/includes/layout.php';
?>
