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

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 {
        // Fetch trial details
        $stmt = $pdo->prepare("SELECT t.*, c.title AS course_title FROM free_trials t LEFT JOIN courses c ON t.course_id = c.id WHERE t.id = ?");
        $stmt->execute([$id]);
        $trial = $stmt->fetch();

        if ($trial && $trial['status'] == 'pending') {
            
            if ($action == 'approve') {
                
                // ১. নতুন পাসওয়ার্ড তৈরি
                $plain_pass = substr(str_shuffle("0123456789"), 0, 6);
                $hashed_pass = password_hash($plain_pass, PASSWORD_DEFAULT);

                // ২. Students টেবিলে ট্রায়াল হিসেবে ইনসার্ট করা (is_trial = 1, trial_attended = 0)
                $check = $pdo->prepare("SELECT id FROM students WHERE email = ?");
                $check->execute([$trial['email']]);
                
                if (!$check->fetch()) {
                    $sql = "INSERT INTO students (name, email, phone, password, course_id, course_name, admission_type, status, is_trial, trial_attended) 
                            VALUES (?, ?, ?, ?, ?, ?, 'Free Trial', 'active', 1, 0)";
                    $ins = $pdo->prepare($sql);
                    $ins->execute([
                        $trial['name'], $trial['email'], $trial['phone'], $hashed_pass, 
                        $trial['course_id'], $trial['course_title']
                    ]);
                }

                // ৩. Trial স্ট্যাটাস আপডেট করা
                $pdo->prepare("UPDATE free_trials SET status = 'approved' WHERE id = ?")->execute([$id]);

                // ৪. স্টুডেন্টকে ইমেইল পাঠানো
                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host       = 'smtp.hostinger.com'; 
                    $mail->SMTPAuth   = true;
                    $mail->Username   = 'info@new.ahmadonlineacademy.com'; // আপনার ইমেইল দিন
                    $mail->Password   = 'y2$M$M83w3kP'; // আপনার ইমেইলের পাসওয়ার্ড দিন
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                    $mail->Port       = 465;

                    $mail->setFrom('info@new.ahmadonlineacademy.com', 'Ahmad Academy');
                    $mail->addAddress($trial['email'], $trial['name']);
                    $mail->isHTML(true);
                    $mail->Subject = 'Free Trial Approved - Ahmad Academy';
                    
                    $mail->Body = "
                        <div style='font-family: Arial; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
                            <h2 style='color: #059669;'>Trial Class Approved!</h2>
                            <p>Assalamu Alaikum <b>{$trial['name']}</b>,</p>
                            <p>Your request for a free trial class for <b>{$trial['course_title']}</b> has been approved.</p>
                            <p style='color: red; font-weight: bold;'>You are allowed to take maximum 3 Free Classes. After that, you need to enroll to continue.</p>
                            <div style='background: #f8f9fa; padding: 15px; margin: 20px 0;'>
                                <b>Student Portal Login:</b><br>
                                Email: {$trial['email']}<br>
                                Password: <span style='color: #059669; font-size: 18px; font-weight: bold;'>{$plain_pass}</span>
                            </div>
                            <a href='https://new.ahmadonlineacademy.com/login.php' style='background: #059669; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Login Now</a>
                        </div>";
                    $mail->send();
                } catch (Exception $e) {}

            } elseif ($action == 'reject') {
                // রিজেক্ট করা হলে
                $pdo->prepare("UPDATE free_trials SET status = 'rejected' WHERE id = ?")->execute([$id]);
            }

            header("Location: view_trials.php?msg=success");
            exit;
        }
    } catch (PDOException $e) { 
        die("Error: " . $e->getMessage()); 
    }
}
header("Location: view_trials.php");