<?php 
// Advanced Configuration
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 

// ==========================================
// 🛠️ AUTO-FIX DATABASE: Ensure Table Exists
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `team_members` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(255) NOT NULL,
        `role_or_spec` varchar(255) DEFAULT NULL,
        `team_type` varchar(100) DEFAULT 'Teacher',
        `image_url` varchar(255) DEFAULT 'assets/images/default.png',
        `created_at` timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch(PDOException $e) {}

$msg = '';

// --- Delete Logic ---
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    
    // Delete image file from server
    $img_stmt = $pdo->prepare("SELECT image_url FROM team_members WHERE id = ?");
    $img_stmt->execute([$del_id]);
    $old_img = $img_stmt->fetchColumn();
    if ($old_img && $old_img != 'assets/images/default.png' && file_exists('../' . $old_img)) {
        unlink('../' . $old_img);
    }

    try {
        $pdo->prepare("DELETE FROM team_members WHERE id = ?")->execute([$del_id]);
        $msg = "<div class='alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up'><i class='fas fa-check-circle me-3 fa-2x text-success'></i> <div><strong class='d-block text-success'>Removed!</strong> <span class='text-muted'>Team member removed successfully from the website.</span></div></div>";
    } catch (PDOException $e) { }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// Fetch All Team Members
$members = $pdo->query("SELECT * FROM team_members ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }
    
    .btn-add { background: var(--theme-green); color: #fff; border-radius: 12px; font-weight: 700; padding: 12px 24px; transition: 0.3s; border: none; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; }
    .btn-add:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Desktop Table */
    .desktop-table-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; }
    .table-hover tbody tr:hover { background-color: #f8fafc; }
    .table thead th { border: none; padding: 18px 20px; color: #64748b; font-weight: 800; text-transform: uppercase; font-size: 11px; letter-spacing: 0.5px; background-color: #f1f5f9; }
    
    /* Image */
    .team-img { width: 45px; height: 45px; object-fit: cover; border-radius: 12px; border: 2px solid #f1f5f9; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    
    /* Animations */
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }
    
    /* Actions & Badges */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; border: none; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; }
    .act-edit { background: #f1f5f9; color: var(--theme-green); } 
    .act-edit:hover { background: var(--theme-green); color: #fff; }
    .act-delete { background: #fef2f2; color: #ef4444; } 
    .act-delete:hover { background: #ef4444; color: #fff; }
    
    .role-badge { padding: 6px 14px; border-radius: 8px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }

    /* 📱 Mobile Specific Styles */
    .team-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .dashboard-header .btn-add { width: 100%; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) {
        #sidebarToggle { display: none !important; }
    }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm">
                <i class="fas fa-bars fs-5"></i>
            </button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title">Website Team</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Manage instructors and board members for the frontend</p>
            </div>
        </div>
        <a href="add_team_member.php" class="btn-add shadow-sm">
            <i class="fas fa-plus-circle me-2"></i> Add Member
        </a>
    </div>

    <?= $msg ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">Profile</th>
                        <th>Member Details</th>
                        <th>Category</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($members)): foreach($members as $m): ?>
                    <tr>
                        <td class="py-3 ps-4">
                            <img src="../<?= htmlspecialchars($m['image_url']) ?>" alt="Photo" class="team-img" onerror="this.src='../assets/images/default.png'">
                        </td>
                        <td>
                            <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars($m['name']) ?></div>
                            <small class="text-muted fw-bold"><i class="fas fa-briefcase me-1"></i> <?= htmlspecialchars($m['role_or_spec']) ?></small>
                        </td>
                        <td>
                            <span class="role-badge bg-light text-dark border border-secondary-subtle">
                                <?= htmlspecialchars($m['team_type']) ?>
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <a href="edit_team_member.php?id=<?= $m['id'] ?>" class="act-btn act-edit" title="Edit"><i class="fas fa-pen"></i></a>
                            <a href="?delete=<?= $m['id'] ?>" class="act-btn act-delete" onclick="return confirm('Remove this member from website?');" title="Delete"><i class="fas fa-trash-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted fw-bold">No team members added yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php if(!empty($members)): foreach($members as $m): ?>
            <div class="col-12">
                <div class="team-mobile-card p-3">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <img src="../<?= htmlspecialchars($m['image_url']) ?>" alt="Photo" class="team-img" style="width: 55px; height: 55px;" onerror="this.src='../assets/images/default.png'">
                        <div>
                            <h6 class="fw-bold text-dark mb-1" style="font-size: 16px;"><?= htmlspecialchars($m['name']) ?></h6>
                            <span class="role-badge bg-light text-dark border" style="font-size: 9px; padding: 4px 8px;">
                                <?= htmlspecialchars($m['team_type']) ?>
                            </span>
                        </div>
                    </div>
                    
                    <div class="mb-3 px-2">
                        <small class="text-muted text-uppercase fw-bold" style="font-size: 10px;">Designation</small>
                        <div class="fw-bold text-dark" style="font-size: 14px;"><i class="fas fa-briefcase text-muted me-2"></i> <?= htmlspecialchars($m['role_or_spec']) ?></div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <a href="edit_team_member.php?id=<?= $m['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 13px; padding: 10px;"><i class="fas fa-pen me-2"></i> Edit</a>
                        <a href="?delete=<?= $m['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 13px; padding: 10px;" onclick="return confirm('Remove this member?');"><i class="fas fa-trash-alt me-2"></i> Delete</a>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-users-slash fa-3x text-muted opacity-25 mb-3"></i>
                    <h6 class="fw-bold text-muted">No members found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<script>
    // Sidebar Mobile Menu Toggle Logic
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebarMenu'); 
        
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                if(sidebar) {
                    sidebar.classList.toggle('active');
                } else {
                    const fallbackSidebar = document.querySelector('.sidebar');
                    if(fallbackSidebar) fallbackSidebar.classList.toggle('active');
                }
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>