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

// Include PHPMailer library
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

if (isset($_GET['id']) && isset($_GET['action'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];

    try {
        if ($action == 'approved') {
            // Fetch applicant details and course name
            $stmt = $pdo->prepare("SELECT a.*, c.title AS course_title FROM admissions a JOIN courses c ON a.course_id = c.id WHERE a.id = ?");
            $stmt->execute([$id]);
            $lead = $stmt->fetch();

            if ($lead && $lead['status'] != 'approved') {
                
                // Transaction শুরু করা হলো যাতে কোনো একটি ফেইল করলে পুরো প্রসেস বাতিল হয়
                $pdo->beginTransaction();

                // 1. চেক করা হচ্ছে এই ইমেইলে আগে থেকেই কোনো স্টুডেন্ট অ্যাকাউন্ট আছে কি না
                $check = $pdo->prepare("SELECT id FROM students WHERE email = ?");
                $check->execute([$lead['email']]);
                $existing_student = $check->fetch();

                $plain_pass = substr(str_shuffle("0123456789"), 0, 6);
                $hashed_pass = password_hash($plain_pass, PASSWORD_DEFAULT);
                $student_id = null;

                if (!$existing_student) {
                    // নতুন স্টুডেন্ট তৈরি (এখানে course_id বাদ দেওয়া হয়েছে)
                    $sql = "INSERT INTO students (
                        admission_id, name, email, phone, guardian_phone, 
                        password, admission_type, father_husband_name, mother_name, 
                        permanent_address, present_address, edu_ssc, edu_hsc, profile_photo, status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')";
                    
                    $ins = $pdo->prepare($sql);
                    $ins->execute([
                        $id, $lead['student_name'], $lead['email'], $lead['phone'], $lead['guardian_phone'],
                        $hashed_pass, $lead['admission_type'], $lead['father_husband_name'], $lead['mother_name'], 
                        $lead['permanent_address'], $lead['present_address'], $lead['edu_ssc'], $lead['edu_hsc'], $lead['student_photo']
                    ]);
                    $student_id = $pdo->lastInsertId(); // নতুন তৈরি হওয়া স্টুডেন্টের আইডি
                } else {
                    // পুরানো স্টুডেন্ট হলে শুধু তথ্য আপডেট হবে
                    $student_id = $existing_student['id'];
                    $upd_std = $pdo->prepare("UPDATE students SET admission_id = ?, phone = ?, status = 'active' WHERE id = ?");
                    $upd_std->execute([$id, $lead['phone'], $student_id]);
                }

                // 2. Enrollments টেবিলে ডাটা ইনসার্ট করা (নতুন লজিক)
                // চেক করা হচ্ছে এই স্টুডেন্ট আগে থেকেই এই কোর্সে এনরোল করা আছে কি না
                $check_enroll = $pdo->prepare("SELECT id FROM enrollments WHERE student_id = ? AND course_id = ?");
                $check_enroll->execute([$student_id, $lead['course_id']]);
                
                if (!$check_enroll->fetch()) {
                    $enroll_sql = "INSERT INTO enrollments (student_id, course_id, status) VALUES (?, ?, 'active')";
                    $pdo->prepare($enroll_sql)->execute([$student_id, $lead['course_id']]);
                }

                // 3. Admission স্ট্যাটাস আপডেট
                $upd = $pdo->prepare("UPDATE admissions SET status = 'approved', payment_status = 'verified' WHERE id = ?");
                $upd->execute([$id]);

                $pdo->commit(); // সব ঠিক থাকলে সেভ করো

                // --- SMTP Email Sending Process ---
                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host       = 'smtp.hostinger.com'; 
                    $mail->SMTPAuth   = true;
                    $mail->Username   = 'info@ahmadonlineacademy.com'; 
                    $mail->Password   = 'y2$M$M83w3kP'; 
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
                    $mail->Port       = 465;
                    $mail->CharSet    = 'UTF-8';

                    $mail->setFrom('info@new.ahmadonlineacademy.com', 'Ahmad Academy');
                    $mail->addAddress($lead['email'], $lead['student_name']);

                    $mail->isHTML(true);
                    $mail->Subject = 'Admission Approved - Ahmad Academy';
                    
                    // ইমেইল বডি
                    $mail->Body = "
                        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: auto; border: 1px solid #e2e8f0; padding: 30px; border-radius: 12px; background-color: #ffffff;'>
                            <div style='text-align: center; margin-bottom: 20px;'>
                                <h2 style='color: #064e3b; margin-bottom: 5px;'>Congratulations, {$lead['student_name']}!</h2>
                                <p style='color: #64748b; font-size: 15px; margin-top: 0;'>Your Islamic learning journey begins here.</p>
                            </div>
                            
                            <p style='color: #334155; font-size: 15px; line-height: 1.6;'>We are delighted to inform you that your admission application for the <b>{$lead['course_title']}</b> has been successfully <strong style='color: #064e3b;'>approved</strong>.</p>
                            
                            <div style='background: #f8fafc; padding: 20px; border-radius: 10px; border-left: 4px solid #d4af37; margin: 25px 0;'>
                                <p style='margin: 0 0 10px 0; color: #022c22; font-weight: bold; text-transform: uppercase; font-size: 13px; letter-spacing: 1px;'>Your Login Credentials</p>
                                <p style='margin: 5px 0; color: #334155;'><strong>Email:</strong> {$lead['email']}</p>
                                " . (!$existing_student ? "<p style='margin: 5px 0; color: #334155;'><strong>Password:</strong> <span style='color: #064e3b; font-size: 18px; font-weight: 800; letter-spacing: 2px;'>{$plain_pass}</span></p>" : "<p style='margin: 5px 0; color: #334155;'><strong>Password:</strong> <span>Your existing account password</span></p>") . "
                            </div>

                            <p style='text-align: center; margin-top: 35px;'>
                                <a href='https://ahmadonlineacademy.com/login' style='background: #064e3b; color: #ffffff; padding: 14px 30px; text-decoration: none; border-radius: 50px; font-weight: bold; display: inline-block; box-shadow: 0 4px 10px rgba(6,78,59,0.2);'>Go to Student Portal</a>
                            </p>
                        </div>";

                    $mail->send();
                } catch (Exception $e) {}

                header("Location: view_admissions.php?msg=accepted");
                exit;
            }
        } elseif ($action == 'delete') {
            $stmt = $pdo->prepare("SELECT student_photo, payment_screenshot FROM admissions WHERE id = ?");
            $stmt->execute([$id]);
            $files = $stmt->fetch();
            
            if($files) {
                if(!empty($files['student_photo'])) @unlink('../' . $files['student_photo']);
                if(!empty($files['payment_screenshot'])) @unlink('../' . $files['payment_screenshot']);
            }

            $pdo->prepare("DELETE FROM admissions WHERE id = ?")->execute([$id]);
            header("Location: view_admissions.php?msg=deleted");
            exit;
        }
    } catch (PDOException $e) { 
        $pdo->rollBack(); // এরর হলে কোনো ডাটাই সেভ হবে না
        die("Sync Error: " . $e->getMessage()); 
    }
}
header("Location: view_admissions.php");