<?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_teachers.php';</script>"; exit; }
$id = (int)$_GET['id'];
$msg = '';

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

if (!$teacher) { 
    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> Teacher not found!</div></div>"); 
}

// Update Logic
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_teacher'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $status = $_POST['status'];
    
    try {
        // Check if new password is provided
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $update = $pdo->prepare("UPDATE teachers SET name=?, email=?, phone=?, password=?, status=? WHERE id=?");
            $update->execute([$name, $email, $phone, $password, $status, $id]);
        } else {
            $update = $pdo->prepare("UPDATE teachers SET name=?, email=?, phone=?, status=? WHERE id=?");
            $update->execute([$name, $email, $phone, $status, $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'>Instructor profile updated perfectly.</span></div></div>";
        
        // Refresh data after update
        $stmt->execute([$id]); 
        $teacher = $stmt->fetch(PDO::FETCH_ASSOC); 
    } catch (PDOException $e) {
        $msg = "<div class='alert alert-danger fw-bold rounded-4 border-0 shadow-sm'><i class='fas fa-exclamation-triangle me-2'></i> Database Error! Email might already be in use.</div>";
    }
}
?>

<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 Instructor</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Update login credentials and profile details</p>
            </div>
        </div>
        <a href="manage_teachers.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 ?>

        <form method="POST">
            <h6 class="fw-bold mb-4 pb-2 border-bottom text-muted"><i class="fas fa-user-circle me-2"></i> Basic 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($teacher['name']) ?>" required>
                </div>
            </div>

            <div class="row g-4 mb-5">
                <div class="col-md-6">
                    <label class="form-label fw-bold">Login Email <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-envelope"></i></span>
                        <input type="email" name="email" class="form-control border-start-0 ps-0" value="<?= htmlspecialchars($teacher['email']) ?>" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold">Phone Number</label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-phone-alt"></i></span>
                        <input type="text" name="phone" class="form-control border-start-0 ps-0" value="<?= htmlspecialchars($teacher['phone'] ?? '') ?>">
                    </div>
                </div>
            </div>

            <h6 class="fw-bold mb-4 pb-2 border-bottom text-muted"><i class="fas fa-shield-alt me-2"></i> Security & Access</h6>
            <div class="row g-4 mb-5">
                <div class="col-md-6">
                    <label class="form-label fw-bold d-flex justify-content-between">
                        <span>Reset Password</span>
                        <small class="text-danger text-capitalize" style="font-size: 10px;">(Leave empty to keep current)</small>
                    </label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-lock"></i></span>
                        <input type="password" name="password" class="form-control border-start-0 ps-0" placeholder="Enter new password if forgotten">
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-bold">Account Status</label>
                    <select name="status" class="form-select border-2 fw-bold text-dark">
                        <option value="active" <?= $teacher['status'] == 'active' ? 'selected' : '' ?>>Active (Can Login)</option>
                        <option value="inactive" <?= $teacher['status'] == 'inactive' ? 'selected' : '' ?>>Inactive (Cannot Login)</option>
                    </select>
                </div>
            </div>

            <div class="text-end pt-3 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> SAVE CHANGES
                </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'; ?>