<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in and has admin permission
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Get teacher ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    $error_message = 'ভুল শিক্ষক আইডি';
}

// Ensure 'designation' column exists in teachers table
try {
    $pdo->query("SELECT designation FROM teachers LIMIT 1");
} catch (Exception $e) {
    try { $pdo->exec("ALTER TABLE teachers ADD COLUMN designation VARCHAR(150) NULL AFTER last_name"); } catch (Exception $e2) { /* ignore */ }
}

// Load teacher
$teacher = null;
if (!$error_message) {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE id = ?");
    $stmt->execute([$id]);
    $teacher = $stmt->fetch();
    if (!$teacher) {
        $error_message = 'শিক্ষক পাওয়া যায়নি';
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && !$error_message) {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $date_of_birth = $_POST['date_of_birth'] ?? null; // YYYY-MM-DD
    $gender = $_POST['gender'] ?? null;
    $qualification = trim($_POST['qualification'] ?? '');
    $experience_years = (int)($_POST['experience_years'] ?? 0);
    $joining_date = $_POST['joining_date'] ?? null; // YYYY-MM-DD
    $salary = (float)($_POST['salary'] ?? 0);
    $status = $_POST['status'] ?? 'active';
    $designation = trim($_POST['designation'] ?? '');

    if (empty($first_name) || empty($last_name)) {
        $error_message = 'প্রথম নাম ও শেষ নাম আবশ্যক';
    } else {
        try {
            $pdo->beginTransaction();

            // Validate email format if provided
            if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new Exception('ইমেইল ঠিকানা সঠিক নয়');
            }

            // Check email uniqueness in teachers (exclude current)
            if (!empty($email)) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM teachers WHERE email = ? AND email IS NOT NULL AND email != '' AND id <> ?");
                $stmt->execute([$email, $id]);
                if ($stmt->fetchColumn() > 0) {
                    throw new Exception('এই ইমেইল ঠিকানা ইতিমধ্যে অন্য শিক্ষকের জন্য ব্যবহৃত হয়েছে');
                }
            }

            // Check email uniqueness in users (exclude linked user if exists)
            if (!empty($email)) {
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND email IS NOT NULL AND email != ''" . ($teacher['user_id'] ? " AND id <> ?" : ""));
                $params = [$email];
                if ($teacher['user_id']) { $params[] = $teacher['user_id']; }
                $stmt->execute($params);
                if ($stmt->fetchColumn() > 0) {
                    throw new Exception('এই ইমেইল ঠিকানা ইতিমধ্যে ব্যবহৃত হয়েছে');
                }
            }

            // Handle photo upload (optional)
            $photo_path = $teacher['photo'];
            if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
                $upload_dir_rel = 'uploads/teachers/';
                $upload_dir = '../' . $upload_dir_rel;
                if (!is_dir($upload_dir)) { @mkdir($upload_dir, 0777, true); }
                $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION) ?: 'jpg';
                $filename = ($teacher['employee_id'] ?: ('T' . $id)) . '.' . strtolower($ext);
                $dest_fs = $upload_dir . $filename; // filesystem
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $dest_fs)) {
                    $photo_path = $upload_dir_rel . $filename; // path stored in DB (web path)
                }
            }

            // Update teacher
            $stmt = $pdo->prepare("UPDATE teachers SET first_name = ?, last_name = ?, designation = ?, email = ?, phone = ?, address = ?, date_of_birth = ?, gender = ?, qualification = ?, experience_years = ?, joining_date = ?, salary = ?, photo = ?, status = ? WHERE id = ?");
            $stmt->execute([
                $first_name,
                $last_name,
                ($designation ?: null),
                $email ?: null,
                $phone ?: null,
                $address ?: null,
                $date_of_birth ?: null,
                $gender ?: null,
                $qualification ?: null,
                $experience_years,
                $joining_date ?: null,
                $salary,
                $photo_path,
                $status,
                $id
            ]);

            // Optionally sync users.email if linked
            if ($teacher['user_id']) {
                try {
                    if (!empty($email)) {
                        $u = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
                        $u->execute([$email, $teacher['user_id']]);
                    } else {
                        // if email cleared, set users.email NULL
                        $u = $pdo->prepare("UPDATE users SET email = NULL WHERE id = ?");
                        $u->execute([$teacher['user_id']]);
                    }
                } catch (Exception $e) {
                    // Ignore user email sync issues to not block teacher update
                }
            }

            $pdo->commit();
            $success_message = 'শিক্ষকের তথ্য সফলভাবে আপডেট হয়েছে।';

            // Reload teacher data
            $stmt = $pdo->prepare("SELECT * FROM teachers WHERE id = ?");
            $stmt->execute([$id]);
            $teacher = $stmt->fetch();
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>শিক্ষক সম্পাদনা - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="<?php echo ($_SESSION['user_role'] == 'teacher') ? 'dashboard.php' : '../index.php'; ?>">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="list.php">
                    <i class="fas fa-arrow-left"></i> শিক্ষক তালিকা
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-user-edit"></i> শিক্ষক সম্পাদনা</h5>
                        <?php if ($teacher): ?>
                        <span class="text-muted">Employee ID: <strong><?php echo htmlspecialchars($teacher['employee_id']); ?></strong></span>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($teacher): ?>
                        <form method="POST" action="" enctype="multipart/form-data" class="needs-validation" novalidate>
                            <div class="row">
                                <!-- Personal Information -->
                                <div class="col-md-6">
                                    <h6 class="text-primary mb-3"><i class="fas fa-user"></i> ব্যক্তিগত তথ্য</h6>

                                    <div class="mb-3">
                                        <label class="form-label">প্রথম নাম <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($teacher['first_name']); ?>" required>
                                        <div class="invalid-feedback">প্রথম নাম প্রয়োজন</div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">শেষ নাম <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="last_name" value="<?php echo htmlspecialchars($teacher['last_name']); ?>" required>
                                        <div class="invalid-feedback">শেষ নাম প্রয়োজন</div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">ইমেইল</label>
                                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($teacher['email']); ?>">
                                        <div class="form-text">ফাঁকা রাখলে ইমেইল মুছে যাবে</div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">পদবী</label>
                                        <input type="text" class="form-control" name="designation" value="<?php echo htmlspecialchars($teacher['designation'] ?? ''); ?>" placeholder="যেমন: সহকারী শিক্ষক, প্রভাষক">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">ফোন নম্বর</label>
                                        <input type="tel" class="form-control" name="phone" value="<?php echo htmlspecialchars($teacher['phone']); ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">জন্ম তারিখ</label>
                                        <input type="date" class="form-control" name="date_of_birth" value="<?php echo htmlspecialchars($teacher['date_of_birth']); ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">লিঙ্গ</label>
                                        <select class="form-select" name="gender">
                                            <option value="" <?php echo empty($teacher['gender']) ? 'selected' : ''; ?>>নির্বাচন করুন</option>
                                            <option value="male" <?php echo ($teacher['gender'] == 'male') ? 'selected' : ''; ?>>পুরুষ</option>
                                            <option value="female" <?php echo ($teacher['gender'] == 'female') ? 'selected' : ''; ?>>মহিলা</option>
                                            <option value="other" <?php echo ($teacher['gender'] == 'other') ? 'selected' : ''; ?>>অন্যান্য</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">ঠিকানা</label>
                                        <textarea class="form-control" name="address" rows="3"><?php echo htmlspecialchars($teacher['address']); ?></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">ছবি</label><br>
                                        <?php if (!empty($teacher['photo'])): ?>
                                            <img src="../<?php echo $teacher['photo']; ?>" alt="Photo" class="mb-2" style="height:60px;border-radius:6px;">
                                        <?php endif; ?>
                                        <input type="file" class="form-control" name="photo" accept="image/*">
                                        <div class="form-text">JPG, PNG বা GIF, সর্বোচ্চ ৫ MB</div>
                                    </div>
                                </div>

                                <!-- Professional Information -->
                                <div class="col-md-6">
                                    <h6 class="text-primary mb-3"><i class="fas fa-briefcase"></i> পেশাগত তথ্য</h6>

                                    <div class="mb-3">
                                        <label class="form-label">শিক্ষাগত যোগ্যতা</label>
                                        <input type="text" class="form-control" name="qualification" value="<?php echo htmlspecialchars($teacher['qualification']); ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">অভিজ্ঞতা (বছর)</label>
                                        <input type="number" class="form-control" name="experience_years" min="0" max="50" value="<?php echo (int)$teacher['experience_years']; ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">যোগদান তারিখ</label>
                                        <input type="date" class="form-control" name="joining_date" value="<?php echo htmlspecialchars($teacher['joining_date']); ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">বেতন</label>
                                        <input type="number" class="form-control" name="salary" step="1" value="<?php echo (float)$teacher['salary']; ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">অবস্থা</label>
                                        <select class="form-select" name="status">
                                            <option value="active" <?php echo ($teacher['status'] == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                            <option value="inactive" <?php echo ($teacher['status'] == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> সংরক্ষণ করুন
                                </button>
                                <a href="list.php" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> বাতিল
                                </a>
                            </div>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    // Bootstrap validation
    (function(){
        'use strict';
        var forms = document.querySelectorAll('.needs-validation');
        Array.prototype.slice.call(forms).forEach(function(form){
            form.addEventListener('submit', function(event){
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    })();
    </script>
</body>
</html>