Mini Shell

Direktori : /home/mhcadmin/www/Portal/
Upload File :
Current File : /home/mhcadmin/www/Portal/Re_Register_Students.php

<?php
// Start output buffering at the VERY beginning
ob_start();

session_start();

// Set memory and execution limits
ini_set('memory_limit', '256M');
ini_set('max_execution_time', '300');
set_time_limit(300);

// Error reporting - enable for debugging, disable in production
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'upload_errors.log');

$rootPath = realpath(dirname(__FILE__) . '/..');
require_once $rootPath . '/Portal/config/config.php';
require_once $rootPath . '/Portal/include/auth_validate.php';

// Check authentication
if (!isset($_SESSION['id'])) {
    ob_end_clean();
    header('Location: login.php');
    exit();
}

$User = $_SESSION['id'];

// Fetch user data securely
$stmt = mysqli_prepare($conn, "SELECT Access_Level, Full_Name FROM admin_accounts WHERE id = ?");
if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $User);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $UserAccessName, $StudentName);
    mysqli_stmt_fetch($stmt);
    mysqli_stmt_close($stmt);
}

// File upload configuration
$maxFileSize = 5 * 1024 * 1024; // 5MB
$allowedExtensions = ['csv'];
$uploadDir = "StudentsUpload/";
$maxRecords = 5000;

// ============================================
// EMAIL CONFIGURATION
// ============================================
$domain = 'edgeviewacademy.com';
$emailConfig = [
    'from_email' => 'it@edgeviewacademy.com',
    'from_name' => 'Edgeview Academy Management System',
    'subject_prefix' => 'Student Account Created: ',
    'reply_to' => 'it@edgeviewacademy.com',
    'alternative_from_emails' => [
        'noreply@edgeviewacademy.com',
        'admin@edgeviewacademy.com',
        'support@edgeviewacademy.com'
    ]
];

// ============================================
// EMAIL FUNCTION
// ============================================
function sendStudentCredentialsEmail($toEmail, $fullName, $username, $password, $config) {
    $subject = $config['subject_prefix'] . "Welcome to Edgeview Academy";
    $loginUrl = "https://edgeviewacademy.com/Portal/login";
    
    $htmlMessage = "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Edgeview Academy - Student Account Created</title>
        <style>
            body { font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
            .header { background-color: #1a237e; color: white; padding: 20px; text-align: center; }
            .content { padding: 30px; }
            .credentials-box { background-color: #f5f5f5; border-left: 4px solid #1a237e; padding: 20px; margin: 20px 0; }
            .password { font-family: monospace; background: #e9ecef; padding: 5px 10px; border-radius: 4px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <div>Edgeview Academy - Student Account Created</div>
            </div>
            <div class='content'>
                <p>Dear <strong>$fullName</strong>,</p>
                <p>Your student account has been created:</p>
                <div class='credentials-box'>
                    <p><strong>Username:</strong> <span class='password'>$username</span></p>
                    <p><strong>Password:</strong> <span class='password'>$password</span></p>
                    <p><strong>Login URL:</strong> <a href='$loginUrl'>$loginUrl</a></p>
                </div>
                <p>Best regards,<br>Edgeview Academy</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    // Try multiple from addresses
    $fromEmails = array_merge([$config['from_email']], $config['alternative_from_emails']);
    $lastError = '';
    
    foreach ($fromEmails as $fromEmail) {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: " . $config['from_name'] . " <" . $fromEmail . ">\r\n";
        $headers .= "Reply-To: " . $config['reply_to'] . "\r\n";
        $headers .= "Return-Path: " . $fromEmail . "\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        $sent = @mail($toEmail, $subject, $htmlMessage, $headers, "-f" . $fromEmail);
        
        if ($sent) {
            error_log("✅ Email sent from $fromEmail to $toEmail");
            return ['success' => true, 'message' => "Email sent", 'from_email' => $fromEmail];
        }
        usleep(100000);
    }
    
    return ['success' => false, 'message' => "All email attempts failed"];
}

// ============================================
// HELPER FUNCTIONS FOR CHECKING EXISTING RECORDS
// ============================================

/**
 * Check if student exists in student table
 */
function studentExists($conn, $studentNo) {
    $stmt = mysqli_prepare($conn, "SELECT Student_No FROM student WHERE Student_No = ?");
    mysqli_stmt_bind_param($stmt, "s", $studentNo);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $exists = mysqli_stmt_num_rows($stmt) > 0;
    mysqli_stmt_close($stmt);
    return $exists;
}

/**
 * Update student level
 */
function updateStudentLevel($conn, $studentNo, $newLevel) {
    $stmt = mysqli_prepare($conn, "UPDATE student SET Level = ? WHERE Student_No = ?");
    mysqli_stmt_bind_param($stmt, "ss", $newLevel, $studentNo);
    $result = mysqli_stmt_execute($stmt);
    $affected = mysqli_stmt_affected_rows($stmt);
    mysqli_stmt_close($stmt);
    return $affected > 0;
}

/**
 * Check if bill exists for student with same term and school year
 */
function billExists($conn, $studentNo, $classLevel, $term, $schoolYear) {
    $stmt = mysqli_prepare($conn, 
        "SELECT id FROM bills WHERE Student_No = ? AND Class_Level = ? AND Term = ? AND School_Year = ?"
    );
    mysqli_stmt_bind_param($stmt, "ssss", $studentNo, $classLevel, $term, $schoolYear);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $exists = mysqli_stmt_num_rows($stmt) > 0;
    mysqli_stmt_close($stmt);
    return $exists;
}

/**
 * Check if student has any bills for different term/school year
 */
function hasOtherBills($conn, $studentNo, $currentTerm, $currentSchoolYear) {
    $stmt = mysqli_prepare($conn, 
        "SELECT id FROM bills WHERE Student_No = ? AND (Term != ? OR School_Year != ?)"
    );
    mysqli_stmt_bind_param($stmt, "sss", $studentNo, $currentTerm, $currentSchoolYear);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $exists = mysqli_stmt_num_rows($stmt) > 0;
    mysqli_stmt_close($stmt);
    return $exists;
}

/**
 * Create bill for student
 */
function createBill($conn, $studentNo, $classLevel, $term, $schoolYear, $feeAmount) {
    $stmt = mysqli_prepare($conn,
        "INSERT INTO bills (Student_No, Class_Level, Term, School_Year, Bill_Amount)
         VALUES (?, ?, ?, ?, ?)"
    );
    mysqli_stmt_bind_param($stmt, "ssssi", $studentNo, $classLevel, $term, $schoolYear, $feeAmount);
    $result = mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    return $result;
}

// ============================================
// PROCESS FORM SUBMISSION
// ============================================
$showResults = false;
$results = [
    'processedCount' => 0,
    'failedCount' => 0,
    'existingStudents' => 0,
    'newStudents' => 0,
    'studentsUpdated' => 0,
    'billsCreatedCount' => 0,
    'billsSkippedCount' => 0,
    'emailSentCount' => 0,
    'emailFailedCount' => 0,
    'emailDetails' => [],
    'rows' => [],
    'Grade' => '',
    'SchoolYear' => '',
    'Term' => '',
    'feeAmount' => 0
];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $errors = [];
    
    // Validate inputs
    if (empty($_POST['Grade'])) {
        $errors[] = "Grade/Level is required";
    } else {
        $Grade = mysqli_real_escape_string($conn, $_POST['Grade']);
        $results['Grade'] = $Grade;
    }
    
    if (empty($_POST['year'])) {
        $errors[] = "School Year is required";
    } else {
        $SchoolYear = mysqli_real_escape_string($conn, $_POST['year']);
        $results['SchoolYear'] = $SchoolYear;
    }
    
    if (empty($_POST['Term'])) {
        $errors[] = "Term is required";
    } else {
        $Term = mysqli_real_escape_string($conn, $_POST['Term']);
        $results['Term'] = $Term;
        $TermNumber = intval(str_replace('Term ', '', $Term));
    }
    
    // Validate file upload
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = "Please select a valid CSV file to upload";
    } else {
        $fileName = $_FILES['file']['name'];
        $fileSize = $_FILES['file']['size'];
        $tmpName = $_FILES['file']['tmp_name'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
        if ($fileSize > $maxFileSize) {
            $errors[] = "File size exceeds maximum limit of 5MB";
        }
        
        if ($fileExt !== 'csv') {
            $errors[] = "Invalid file extension. Only .csv files are allowed";
        }
    }
    
    // Fetch fee amount
    if (empty($errors)) {
        $feeColumn = str_replace(' ', '_', $Grade);
        $feeQuery = "SELECT `$feeColumn` FROM fees_settings LIMIT 1";
        $feeResult = mysqli_query($conn, $feeQuery);
        
        if ($feeResult && mysqli_num_rows($feeResult) > 0) {
            $feeRow = mysqli_fetch_assoc($feeResult);
            $feeAmount = floatval($feeRow[$feeColumn]);
            $results['feeAmount'] = $feeAmount;
            
            if ($feeAmount <= 0) {
                $errors[] = "Fee amount not found or invalid for Grade: $Grade";
            }
        } else {
            $errors[] = "Failed to fetch fee settings. Column '$feeColumn' may not exist.";
        }
    }
    
    // Process file if no errors
    if (empty($errors)) {
        // Create upload directory
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fname = date("YmdHis") . '_' . uniqid() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $fileName);
        $targetPath = $uploadDir . $fname;
        
        if (move_uploaded_file($tmpName, $targetPath)) {
            // Start transaction
            mysqli_begin_transaction($conn);
            
            try {
                $processedCount = 0;
                $failedCount = 0;
                $existingStudents = 0;
                $newStudents = 0;
                $studentsUpdated = 0;
                $billsCreatedCount = 0;
                $billsSkippedCount = 0;
                $emailSentCount = 0;
                $emailFailedCount = 0;
                $emailDetails = [];
                $rows = [];
                $isFirstRow = true;
                $rowNumber = 0;
                
                $file = fopen($targetPath, "r");
                if ($file) {
                    while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
                        $rowNumber++;
                        
                        if ($isFirstRow) {
                            $isFirstRow = false;
                            continue;
                        }
                        
                        if ($processedCount >= $maxRecords) {
                            break;
                        }
                        
                        $rowData = [
                            'rowNumber' => $rowNumber,
                            'FullName' => isset($data[0]) ? trim($data[0]) : '',
                            'Student_No' => isset($data[1]) ? trim($data[1]) : '',
                            'email' => isset($data[2]) ? trim($data[2]) : '',
                            'Parent_Phone' => isset($data[3]) ? trim($data[3]) : '',
                            'status' => 'Pending',
                            'statusClass' => '',
                            'plainPassword' => '',
                            'emailStatus' => '',
                            'billStatus' => '',
                            'action' => ''
                        ];
                        
                        if (empty($rowData['FullName']) || empty($rowData['Student_No'])) {
                            $rowData['status'] = 'Missing required fields';
                            $rowData['statusClass'] = 'status-error';
                            $failedCount++;
                            $rows[] = $rowData;
                            continue;
                        }
                        
                        // Check if student already exists
                        $studentExists = studentExists($conn, $rowData['Student_No']);
                        
                        if ($studentExists) {
                            // Student exists - update level
                            $existingStudents++;
                            $updated = updateStudentLevel($conn, $rowData['Student_No'], $Grade);
                            
                            if ($updated) {
                                $studentsUpdated++;
                                $rowData['action'] = "Updated level to $Grade";
                                $rowData['status'] = "Updated";
                                $rowData['statusClass'] = "status-success";
                            } else {
                                $rowData['action'] = "Student exists but level not changed";
                                $rowData['status'] = "Already exists";
                                $rowData['statusClass'] = "status-warning";
                            }
                            
                            // NO EMAIL SENT FOR EXISTING STUDENTS
                            $rowData['emailStatus'] = "No email (existing)";
                            
                        } else {
                            // New student - create account
                            $newStudents++;
                            
                            // Generate password
                            $plainPassword = generateRandomPassword(8);
                            $encryptedPassword = md5($plainPassword);
                            $rowData['plainPassword'] = $plainPassword;
                            
                            // Insert into student table
                            $insertStmt = mysqli_prepare($conn, 
                                "INSERT INTO student (`Full_Name`, Level, Student_No, email, Parent_Phone) 
                                 VALUES (?, ?, ?, ?, ?)");
                            mysqli_stmt_bind_param($insertStmt, "sssss", 
                                $rowData['FullName'], $Grade, $rowData['Student_No'], 
                                $rowData['email'], $rowData['Parent_Phone']);
                            
                            if (mysqli_stmt_execute($insertStmt)) {
                                // Insert into admin_accounts
                                $insertAdminStmt = mysqli_prepare($conn,
                                    "INSERT INTO admin_accounts (`Full_Name`, user_name, passwd, User_Type, Access_Level, email, StudentNo)
                                     VALUES (?, ?, ?, 'Student', 'Student', ?, ?)");
                                mysqli_stmt_bind_param($insertAdminStmt, "sssss",
                                    $rowData['FullName'], $rowData['Student_No'], 
                                    $encryptedPassword, $rowData['email'], $rowData['Student_No']);
                                
                                if (mysqli_stmt_execute($insertAdminStmt)) {
                                    $rowData['action'] = "New student created";
                                    $rowData['status'] = "Created";
                                    $rowData['statusClass'] = "status-success";
                                    
                                    // Send email for NEW students only
                                    if (!empty($rowData['email']) && filter_var($rowData['email'], FILTER_VALIDATE_EMAIL)) {
                                        $emailResult = sendStudentCredentialsEmail(
                                            $rowData['email'], 
                                            $rowData['FullName'], 
                                            $rowData['Student_No'], 
                                            $plainPassword, 
                                            $emailConfig
                                        );
                                        
                                        $emailDetails[] = [
                                            'to' => $rowData['email'],
                                            'name' => $rowData['FullName'],
                                            'status' => $emailResult['success'] ? 'sent' : 'failed',
                                            'message' => $emailResult['message'],
                                            'from_email' => $emailResult['from_email'] ?? 'N/A'
                                        ];
                                        
                                        if ($emailResult['success']) {
                                            $emailSentCount++;
                                            $rowData['emailStatus'] = "✓ Email sent";
                                        } else {
                                            $emailFailedCount++;
                                            $rowData['emailStatus'] = "✗ Email failed";
                                        }
                                    } else {
                                        $rowData['emailStatus'] = "No valid email";
                                    }
                                    
                                } else {
                                    $rowData['status'] = "Admin account failed";
                                    $rowData['statusClass'] = "status-error";
                                    $failedCount++;
                                }
                                mysqli_stmt_close($insertAdminStmt);
                            } else {
                                $rowData['status'] = "Student insert failed";
                                $rowData['statusClass'] = "status-error";
                                $failedCount++;
                            }
                            mysqli_stmt_close($insertStmt);
                        }
                        
                        // ============ BILL PROCESSING ============
                        // Check if bill already exists for this student, term, and school year
                        if (billExists($conn, $rowData['Student_No'], $Grade, $TermNumber, $SchoolYear)) {
                            // Bill already exists - skip
                            $billsSkippedCount++;
                            $rowData['billStatus'] = "Bill already exists for this term";
                        } else {
                            // Check if student has other bills (different term/school year)
                            $hasOtherBills = hasOtherBills($conn, $rowData['Student_No'], $TermNumber, $SchoolYear);
                            
                            if ($hasOtherBills) {
                                // Student has bills for other terms - create new bill for this term
                                if (createBill($conn, $rowData['Student_No'], $Grade, $TermNumber, $SchoolYear, $feeAmount)) {
                                    $billsCreatedCount++;
                                    $rowData['billStatus'] = "New bill created for Term $TermNumber: $feeAmount";
                                } else {
                                    $rowData['billStatus'] = "Bill creation failed";
                                }
                            } else {
                                // First bill for this student - create it
                                if (createBill($conn, $rowData['Student_No'], $Grade, $TermNumber, $SchoolYear, $feeAmount)) {
                                    $billsCreatedCount++;
                                    $rowData['billStatus'] = "First bill created: $feeAmount";
                                } else {
                                    $rowData['billStatus'] = "Bill creation failed";
                                }
                            }
                        }
                        
                        $processedCount++;
                        $rows[] = $rowData;
                    }
                    
                    fclose($file);
                    
                    // Commit transaction
                    mysqli_commit($conn);
                    
                    // Set results
                    $showResults = true;
                    $results['processedCount'] = $processedCount;
                    $results['failedCount'] = $failedCount;
                    $results['existingStudents'] = $existingStudents;
                    $results['newStudents'] = $newStudents;
                    $results['studentsUpdated'] = $studentsUpdated;
                    $results['billsCreatedCount'] = $billsCreatedCount;
                    $results['billsSkippedCount'] = $billsSkippedCount;
                    $results['emailSentCount'] = $emailSentCount;
                    $results['emailFailedCount'] = $emailFailedCount;
                    $results['emailDetails'] = $emailDetails;
                    $results['rows'] = $rows;
                    
                } else {
                    throw new Exception("Failed to open uploaded file");
                }
                
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $errors[] = "Database error: " . $e->getMessage();
            }
            
            // Delete uploaded file
            if (file_exists($targetPath)) {
                unlink($targetPath);
            }
        } else {
            $errors[] = "Failed to move uploaded file";
        }
    }
    
    // Store errors in session if any
    if (!empty($errors)) {
        $_SESSION['errors'] = $errors;
    }
}

// ============================================
// DISPLAY RESULTS (ONLY AFTER ALL PROCESSING)
// ============================================

// Clear any previous output
ob_clean();

// Include header
include_once 'include/AdminHeader.php';
?>

<!DOCTYPE html>
<html>
<head>
    <title>Student Upload Results</title>
    <style>
        .status-success { color: green; font-weight: bold; }
        .status-warning { color: orange; font-weight: bold; }
        .status-error { color: red; font-weight: bold; }
        .status-info { color: blue; font-weight: bold; }
        .summary-box { 
            background-color: #f8f9fa; 
            border: 1px solid #dee2e6; 
            border-radius: 5px; 
            padding: 15px; 
            margin: 10px 0;
            text-align: center;
        }
        .summary-number { 
            font-size: 32px; 
            font-weight: bold; 
            margin-bottom: 5px;
        }
        .email-log { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px; }
        .badge-success { background: #d4edda; color: #155724; padding: 5px 10px; border-radius: 12px; display: inline-block; }
        .badge-danger { background: #f8d7da; color: #721c24; padding: 5px 10px; border-radius: 12px; display: inline-block; }
        .badge-warning { background: #fff3cd; color: #856404; padding: 5px 10px; border-radius: 12px; display: inline-block; }
        .badge-info { background: #d1ecf1; color: #0c5460; padding: 5px 10px; border-radius: 12px; display: inline-block; }
    </style>
</head>
<body>
<div id="page-wrapper">
    <div class="container-fluid">
        
        <?php if (!empty($_SESSION['errors'])): ?>
            <div class="alert alert-danger">
                <strong>Errors:</strong>
                <ul>
                    <?php foreach ($_SESSION['errors'] as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php unset($_SESSION['errors']); ?>
            
            <div class="text-center">
                <a href="AdminPortal.php" class="btn btn-primary btn-lg">
                    <i class="fa fa-arrow-left"></i> Go Back
                </a>
            </div>
            
        <?php elseif ($showResults): ?>
            
            <div class="row">
                <br><br>
                <div class="alert alert-info">
                    <strong>Processing for:</strong> 
                    Grade: <?php echo htmlspecialchars($results['Grade']); ?>, 
                    Year: <?php echo htmlspecialchars($results['SchoolYear']); ?>, 
                    Term: <?php echo htmlspecialchars($results['Term']); ?>, 
                    Fee Amount: <?php echo htmlspecialchars($results['feeAmount']); ?>
                </div>
            </div>
            
            <!-- Summary Cards -->
            <div class="row">
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #28a745;">
                            <?php echo $results['processedCount']; ?>
                        </div>
                        <p>✅ Total Records</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #17a2b8;">
                            <?php echo $results['newStudents']; ?>
                        </div>
                        <p>🆕 New Students</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #ffc107;">
                            <?php echo $results['existingStudents']; ?>
                        </div>
                        <p>👤 Existing Students</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #28a745;">
                            <?php echo $results['studentsUpdated']; ?>
                        </div>
                        <p>📝 Level Updated</p>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #17a2b8;">
                            <?php echo $results['billsCreatedCount']; ?>
                        </div>
                        <p>💰 Bills Created</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #ffc107;">
                            <?php echo $results['billsSkippedCount']; ?>
                        </div>
                        <p>⏭️ Bills Skipped (Exist)</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #28a745;">
                            <?php echo $results['emailSentCount']; ?>
                        </div>
                        <p>📧 Emails Sent (New Only)</p>
                    </div>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="summary-box">
                        <div class="summary-number" style="color: #dc3545;">
                            <?php echo $results['failedCount']; ?>
                        </div>
                        <p>❌ Failed Records</p>
                    </div>
                </div>
            </div>
            
            <!-- Results Table -->
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">📋 Processing Details</h3>
                </div>
                <div class="panel-body">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered table-condensed">
                            <thead>
                                <tr style="background-color:#BAC4CC;">
                                    <th>#</th>
                                    <th>Student Name</th>
                                    <th>Level</th>        
                                    <th>Student No</th>
                                    <th>Email</th>
                                    <th>Parent Phone</th>
                                    <th>Password</th>
                                    <th>Action</th>
                                    <th>Bill Status</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($results['rows'] as $row): ?>
                                <tr>
                                    <td><?php echo $row['rowNumber']; ?></td>
                                    <td><?php echo htmlspecialchars($row['FullName']); ?></td>
                                    <td><?php echo htmlspecialchars($results['Grade']); ?></td>
                                    <td><?php echo htmlspecialchars($row['Student_No']); ?></td>
                                    <td><?php echo htmlspecialchars($row['email']); ?></td>
                                    <td><?php echo htmlspecialchars($row['Parent_Phone']); ?></td>
                                    <td>
                                        <?php if (!empty($row['plainPassword'])): ?>
                                            <code><?php echo htmlspecialchars($row['plainPassword']); ?></code>
                                        <?php else: ?>
                                            <span class="badge-info">Existing</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($row['action'])): ?>
                                            <span class="badge-info"><?php echo $row['action']; ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($row['billStatus']); ?></td>
                                    <td class="<?php echo $row['statusClass']; ?>">
                                        <?php echo htmlspecialchars($row['status']); ?>
                                        <?php if (!empty($row['emailStatus'])): ?>
                                            <br><small><?php echo $row['emailStatus']; ?></small>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Email Details (Only for new students) -->
                    <?php if (!empty($results['emailDetails'])): ?>
                    <div class="email-log">
                        <h4><i class="fa fa-envelope"></i> Email Delivery Report (New Students Only)</h4>
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead>
                                    <tr>
                                        <th>To Email</th>
                                        <th>Student</th>
                                        <th>Status</th>
                                        <th>From Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($results['emailDetails'] as $detail): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($detail['to']); ?></td>
                                        <td><?php echo htmlspecialchars($detail['name']); ?></td>
                                        <td>
                                            <?php if ($detail['status'] == 'sent'): ?>
                                                <span class="badge-success">✅ Sent</span>
                                            <?php else: ?>
                                                <span class="badge-danger">❌ Failed</span>
                                                <br><small><?php echo htmlspecialchars($detail['message']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($detail['from_email']); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Action Buttons -->
                    <hr>
                    <div class="text-center">
                        <a href="student_list.php" class="btn btn-primary btn-lg">
                            <i class="fa fa-users"></i> View All Students
                        </a>
                        <a href="bills_list.php" class="btn btn-warning btn-lg">
                            <i class="fa fa-money"></i> View Bills
                        </a>
                        <a href="AdminPortal.php" class="btn btn-success btn-lg">
                            <i class="fa fa-upload"></i> Upload Another File
                        </a>
                        <button onclick="window.print()" class="btn btn-default btn-lg">
                            <i class="fa fa-print"></i> Print Report
                        </button>
                    </div>
                </div>
            </div>
            
        <?php else: ?>
            <!-- No results to show, redirect to upload page -->
            <?php 
            ob_end_clean();
            header('Location: AdminPortal.php');
            exit();
            ?>
        <?php endif; ?>
        
    </div>
</div>

<?php

/**
 * Generate a random password
 */
function generateRandomPassword($length = 8) {
    $chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$';
    $password = '';
    $charLength = strlen($chars) - 1;
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, $charLength)];
    }
    
    return $password;
}

// End output buffering
ob_end_flush();


require_once $rootPath . '/PortalMM/include/footer.php';

?>