<?php 
session_start();
require_once '../db_connect.php';

// Admin Security Check
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

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

if (!isset($_GET['id'])) { echo "<script>window.location.href='manage_team.php';</script>"; exit; }
$id = (int)$_GET['id'];
$msg = '';

// Fetch Current Data
$stmt = $pdo->prepare("SELECT * FROM team_members WHERE id=?");
$stmt->execute([$id]);
$member = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$member) { 
    die("<div class='p-5 text-center'><div class='alert alert-danger d-inline-block fw-bold shadow-sm rounded-4 border-0'><i class='fas fa-exclamation-triangle me-2'></i> Member not found!</div></div>"); 
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $role = trim($_POST['role_or_spec']);
    $type = $_POST['team_type'];
    
    $img_url = $member['image_url']; // Default keep old image

    if (isset($_FILES['member_image']) && $_FILES['member_image']['error'] == 0) {
        $allowed_ext = ['jpg', 'jpeg', 'png', 'webp'];
        $file_name = $_FILES['member_image']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        if (in_array($file_ext, $allowed_ext)) {
            // Delete old image if it's not the default one
            if ($img_url != 'assets/images/default.png' && file_exists('../' . $img_url)) {
                unlink('../' . $img_url);
            }
            
            $upload_dir = '../uploads/team/';
            if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
            $new_name = 'team_' . time() . '_' . rand(100, 999) . '.' . $file_ext;
            
            if (move_uploaded_file($_FILES['member_image']['tmp_name'], $upload_dir . $new_name)) {
                $img_url = 'uploads/team/' . $new_name;
            }
        }
    }

    $update = $pdo->prepare("UPDATE team_members SET name=?, role_or_spec=?, team_type=?, image_url=? WHERE id=?");
    $update->execute([$name, $role, $type, $img_url, $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'>Success!</strong> <span class='text-muted'>Profile updated successfully.</span></div></div>";
    $stmt->execute([$id]); $member = $stmt->fetch(); // Refresh data
}
?>

<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-back { background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; border-radius: 12px; font-weight: 700; padding: 10px 20px; transition: 0.3s; text-decoration: none; display: inline-flex; align-items: center; }
    .btn-back:hover { background: #e2e8f0; color: var(--theme-dark); transform: translateY(-2px); }

    /* Form Styles */
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .form-label { color: var(--theme-dark); font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 15px; transition: 0.3s; background: #f8fafc; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }
    
    .btn-update { background: var(--theme-green); color: #fff; font-weight: 800; border-radius: 12px; transition: 0.3s; border: none; letter-spacing: 1px; }
    .btn-update:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }

    /* Animations */
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }
    
    /* 📱 Mobile Specific Styles */
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 15px 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-back { width: 100%; justify-content: center; }
        .header-title { font-size: 1.2rem; }
        .form-card { padding: 25px !important; }
    }
    @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">Edit Team Member</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Update profile details for the frontend website</p>
            </div>
        </div>
        <a href="manage_team.php" class="btn-back shadow-sm">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <div class="form-card p-4 p-md-5 mx-auto fade-up" style="max-width: 800px; animation-delay: 0.1s;">
        <?= $msg ?>
        
        <div class="text-center mb-5">
            <div class="position-relative d-inline-block">
                <img src="../<?= htmlspecialchars($member['image_url']) ?>" alt="Photo" class="rounded-circle border border-4 border-white shadow" style="width: 120px; height: 120px; object-fit: cover; background: #f1f5f9;">
                <span class="position-absolute bottom-0 end-0 bg-success border border-light rounded-circle" style="width: 25px; height: 25px; border-width: 3px !important;"></span>
            </div>
        </div>

        <form method="POST" enctype="multipart/form-data">
            <h6 class="fw-bold mb-4 pb-2 border-bottom text-muted"><i class="fas fa-id-card me-2"></i> Profile Information</h6>
            
            <div class="mb-4">
                <label class="form-label fw-bold">Full Name <span class="text-danger">*</span></label>
                <div class="input-group">
                    <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-user"></i></span>
                    <input type="text" name="name" class="form-control border-start-0 ps-0" value="<?= htmlspecialchars($member['name']) ?>" required>
                </div>
            </div>

            <div class="row g-4 mb-5">
                <div class="col-md-6">
                    <label class="form-label fw-bold">Designation / Role <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-briefcase"></i></span>
                        <input type="text" name="role_or_spec" class="form-control border-start-0 ps-0" value="<?= htmlspecialchars($member['role_or_spec']) ?>" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold">Category Display</label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-layer-group"></i></span>
                        <select name="team_type" class="form-select border-start-0 ps-0 fw-bold text-dark">
                            <option value="Teacher" <?= $member['team_type'] == 'Teacher' ? 'selected' : '' ?>>Teacher / Instructor</option>
                            <option value="Board Member" <?= $member['team_type'] == 'Board Member' ? 'selected' : '' ?>>Board Member</option>
                            <option value="Adviser" <?= $member['team_type'] == 'Adviser' ? 'selected' : '' ?>>Adviser</option>
                        </select>
                    </div>
                </div>
            </div>

            <h6 class="fw-bold mb-4 pb-2 border-bottom text-muted"><i class="fas fa-image me-2"></i> Profile Photo</h6>
            <div class="mb-4">
                <div class="p-3 border-2 rounded-4 bg-light">
                    <label class="form-label fw-bold text-dark mb-2">Replace Photo <small class="text-danger text-capitalize" style="font-size: 10px;">(Leave empty to keep current)</small></label>
                    <input type="file" name="member_image" class="form-control shadow-none border-0 bg-white" accept="image/*">
                </div>
            </div>

            <div class="text-end pt-4 border-top">
                <button type="submit" name="update_teacher" class="btn btn-update w-100 py-3 shadow-sm">
                    <i class="fas fa-save me-2"></i> UPDATE PROFILE DETAILS
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // 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'; ?>