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

$id = $_GET['id'] ?? null;
if (!$id) { echo "<script>window.location.href='students.php';</script>"; exit; }

$success_msg = ""; $error_msg = "";

// ১. স্টুডেন্টের বর্তমান ডাটা নিয়ে আসা
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) { die("<div class='p-5 text-center fw-bold text-danger'>Student not found!</div>"); }

// ২. স্টুডেন্ট বর্তমানে কোন কোন কোর্সে এনরোল করা আছে তার লিস্ট (ID) আনা
$enroll_stmt = $pdo->prepare("SELECT course_id FROM enrollments WHERE student_id = ?");
$enroll_stmt->execute([$id]);
$current_enrollments = $enroll_stmt->fetchAll(PDO::FETCH_COLUMN); // শুধু ID গুলোর অ্যারে [1, 3, 5]

// ৩. সব অ্যাক্টিভ কোর্সের লিস্ট আনা
$courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);


// ৪. ডাটা আপডেট লজিক
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $status = $_POST['status'];
    $new_password = $_POST['password']; // অপশনাল
    
    // নতুন সিলেক্ট করা কোর্সের অ্যারে
    $selected_courses = $_POST['courses'] ?? []; 

    try {
        $pdo->beginTransaction();

        // ক. বেসিক ইনফো আপডেট
        if (!empty($new_password)) {
            $hashed_pass = password_hash($new_password, PASSWORD_DEFAULT);
            $upd = $pdo->prepare("UPDATE students SET name=?, email=?, phone=?, status=?, password=? WHERE id=?");
            $upd->execute([$name, $email, $phone, $status, $hashed_pass, $id]);
        } else {
            $upd = $pdo->prepare("UPDATE students SET name=?, email=?, phone=?, status=? WHERE id=?");
            $upd->execute([$name, $email, $phone, $status, $id]);
        }

        // খ. এনরোলমেন্ট আপডেট (Smart Logic)
        // যে কোর্সগুলো নতুন অ্যাড করা হয়েছে
        $courses_to_add = array_diff($selected_courses, $current_enrollments);
        // যে কোর্সগুলো আন-চেক (রিমুভ) করা হয়েছে
        $courses_to_remove = array_diff($current_enrollments, $selected_courses);

        // নতুনগুলো Insert করা
        if (!empty($courses_to_add)) {
            $ins_enroll = $pdo->prepare("INSERT INTO enrollments (student_id, course_id, status) VALUES (?, ?, 'active')");
            foreach ($courses_to_add as $c_id) {
                $ins_enroll->execute([$id, $c_id]);
            }
        }

        // আন-চেক করাগুলো Delete করা
        if (!empty($courses_to_remove)) {
            $del_enroll = $pdo->prepare("DELETE FROM enrollments WHERE student_id = ? AND course_id = ?");
            foreach ($courses_to_remove as $c_id) {
                $del_enroll->execute([$id, $c_id]);
            }
        }

        $pdo->commit();
        $success_msg = "Student profile and enrollments updated successfully!";
        
        // রিফ্রেশ ডাটা
        $stmt->execute([$id]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        $enroll_stmt->execute([$id]);
        $current_enrollments = $enroll_stmt->fetchAll(PDO::FETCH_COLUMN);

    } catch (Exception $e) {
        $pdo->rollBack();
        $error_msg = "Update failed: " . $e->getMessage();
    }
}

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

<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: 30px; }
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 35px; border-top: 6px solid var(--theme-green); }
    
    .section-title { font-weight: 800; color: var(--theme-dark); border-left: 4px solid var(--theme-gold); padding-left: 12px; margin-bottom: 25px; font-size: 16px; text-transform: uppercase; letter-spacing: 1px; margin-top: 30px;}
    .form-label { font-weight: 700; color: var(--theme-dark); font-size: 13px; margin-bottom: 8px; }
    .form-control, .form-select { border-radius: 10px; padding: 12px 18px; border: 2px solid #f1f5f9; background: var(--bg-soft); transition: 0.3s; font-size: 14px; font-weight: 500;}
    .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); outline: none; }
    
    /* Custom Course Checkboxes */
    .course-checkbox-card { border: 2px solid #e2e8f0; border-radius: 12px; padding: 15px; cursor: pointer; transition: 0.3s; display: flex; align-items: center; gap: 10px; background: #fff; height: 100%;}
    .course-checkbox-card:hover { border-color: var(--theme-gold); background: rgba(212, 175, 55, 0.05); }
    .form-check-input:checked + .course-checkbox-card { border-color: var(--theme-green); background: rgba(6, 78, 59, 0.05); }
    .form-check-input { width: 20px; height: 20px; accent-color: var(--theme-green); cursor: pointer;}
    .course-title { font-size: 14px; font-weight: 700; color: var(--theme-dark); margin:0;}

    .btn-update { background: var(--theme-green); color: #fff; padding: 14px 45px; border-radius: 50px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }
    .btn-update:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); }

    #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px;}

    @media (max-width: 768px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header > a { width: 100%; justify-content: center; }
        .form-card { padding: 20px !important; }
    }
</style>

<div class="main-content">
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3 shadow-sm" id="sidebarToggle"><i class="fas fa-bars text-dark"></i></button>
            <h4 class="mb-0 fw-bold text-dark"><i class="fas fa-user-edit me-2" style="color: var(--theme-gold);"></i> Edit Student</h4>
        </div>
        <a href="students.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none mt-3 mt-md-0">
            <i class="fas fa-arrow-left me-2"></i> Back to List
        </a>
    </div>

    <div class="row justify-content-center">
        <div class="col-xl-9">
            <?php if($success_msg): ?>
                <div class="alert alert-success border-0 border-start border-4 border-success shadow-sm mb-4 fw-bold p-3 bg-white text-success fade-up">
                    <i class="fas fa-check-circle me-2"></i> <?= $success_msg ?>
                </div>
            <?php endif; ?>
            <?php if($error_msg): ?>
                <div class="alert alert-danger border-0 border-start border-4 border-danger shadow-sm mb-4 fw-bold p-3 bg-white text-danger fade-up">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?= $error_msg ?>
                </div>
            <?php endif; ?>

            <div class="form-card fade-up" style="animation-delay: 0.1s;">
                <form method="POST">
                    
                    <div class="section-title" style="margin-top:0;">1. Personal Information</div>
                    <div class="row g-4 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Full Name *</label>
                            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($student['name']) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Phone Number *</label>
                            <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($student['phone']) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email Address *</label>
                            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($student['email']) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Account Status</label>
                            <select name="status" class="form-select fw-bold">
                                <option value="active" <?= $student['status'] == 'active' ? 'selected' : '' ?> class="text-success">Active</option>
                                <option value="inactive" <?= $student['status'] == 'inactive' ? 'selected' : '' ?> class="text-danger">Inactive / Suspended</option>
                            </select>
                        </div>
                    </div>

                    <div class="section-title">2. Course Enrollments</div>
                    <div class="alert bg-light border text-muted small fw-bold mb-3">
                        <i class="fas fa-info-circle me-1 text-gold"></i> Check the boxes to enroll the student in courses. Uncheck to remove them from a course.
                    </div>
                    <div class="row g-3 mb-4">
                        <?php foreach($courses as $c): 
                            $is_enrolled = in_array($c['id'], $current_enrollments);
                        ?>
                        <div class="col-md-6 col-lg-4">
                            <label class="d-flex align-items-center m-0 w-100 position-relative">
                                <input type="checkbox" name="courses[]" value="<?= $c['id'] ?>" class="form-check-input position-absolute" style="left: 15px; z-index: 2;" <?= $is_enrolled ? 'checked' : '' ?>>
                                <div class="course-checkbox-card w-100" style="padding-left: 45px;">
                                    <p class="course-title"><?= htmlspecialchars($c['title']) ?></p>
                                </div>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="section-title">3. Security Settings</div>
                    <div class="row g-4 mb-2">
                        <div class="col-md-12">
                            <label class="form-label">Change Password <span class="text-muted fw-normal">(Leave blank to keep current password)</span></label>
                            <input type="text" name="password" class="form-control" placeholder="Enter new password if you want to reset...">
                        </div>
                    </div>

                    <div class="text-center mt-5 pt-4 border-top">
                        <button type="submit" class="btn btn-update w-100-mobile">
                            <i class="fas fa-save me-2"></i> Update Student Data
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

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