Mini Shell

Direktori : /home/mhcadmin/public_html/Portal/
Upload File :
Current File : /home/mhcadmin/public_html/Portal/Notice_Upload.php

<?php
session_start();

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

// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering
ob_start();

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

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

$User = $_SESSION['id'];

// Fetch user data
$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 = "NoticesUpload/";
$maxRecords = 5000;

// ============================================
// DATABASE TABLE NAME
// ============================================
define('NOTICES_TABLE', 'notices');

// ============================================
// EMAIL CONFIGURATION - EXACT COPY FROM YOUR WORKING SYSTEM
// ============================================
$domain = 'edgeviewacademy.com'; // Your domain
$emailConfig = [
    'from_email' => 'it@edgeviewacademy.com', // Your actual email that works
    'from_name' => 'Edgeview Academy Management System',
    'subject_prefix' => 'Notice: ',
    'reply_to' => 'it@edgeviewacademy.com',
    // Additional from addresses to try if needed
    'alternative_from_emails' => [
        'noreply@edgeviewacademy.com',
        'admin@edgeviewacademy.com',
        'support@edgeviewacademy.com'
    ]
];

// ============================================
// EMAIL FUNCTION - EXACT COPY FROM YOUR WORKING SYSTEM
// ============================================
function sendNoticeEmail($toEmail, $fullName, $heading, $message, $config) {
    $subject = $config['subject_prefix'] . $heading;
    $loginUrl = "https://edgeviewacademy.com/Portal/login";
    
    // HTML email content - styled like your working system
    $htmlMessage = "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>Edgeview Academy - Notice: $heading</title>
        <style>
            body { font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
            .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
            .header { background-color: #1a237e; color: white; padding: 20px; text-align: center; }
            .logo { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
            .content { padding: 30px; }
            .notice-box { background-color: #f5f5f5; border-left: 4px solid #1a237e; padding: 20px; margin: 20px 0; border-radius: 4px; }
            .notice-heading { color: #1a237e; font-size: 20px; margin-top: 0; }
            .button { display: inline-block; background-color: #1a237e; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold; margin: 20px 0; }
            .footer { background-color: #f5f5f5; padding: 20px; text-align: center; color: #666; font-size: 12px; border-top: 1px solid #ddd; }
            .important { background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <div class='logo'>Edgeview Academy</div>
                <div>Official Notice</div>
            </div>
            
            <div class='content'>
                <p>Dear <strong>$fullName</strong>,</p>
                
                <p>Please find below an important notice from the school administration:</p>
                
                <div class='notice-box'>
                    <h3 class='notice-heading'>" . htmlspecialchars($heading) . "</h3>
                    <p>" . nl2br(htmlspecialchars($message)) . "</p>
                </div>
                
                <div class='important'>
                    <h4 style='color: #856404; margin-top: 0;'>📌 Important:</h4>
                    <p>This is an official communication from Edgeview Academy. Please read the notice carefully.</p>
                </div>
                
                <div style='text-align: center;'>
                    <a href='$loginUrl' class='button'>Access Your Student Portal</a>
                </div>
                
                <p>Best regards,<br>
                <strong>Edgeview Academy Administration</strong><br>
                <em>Educate for Excellence</em></p>
            </div>
            
            <div class='footer'>
                <p>This is an automated message from Edgeview Academy IT Department.</p>
                <p>For assistance, please contact: IT Department - it@edgeviewacademy.com</p>
                <p>© " . date('Y') . " Edgeview Academy. All rights reserved.</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 for HTML email - EXACT SAME AS WORKING SYSTEM
        $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();
        $headers .= "X-Priority: 1 (Highest)\r\n";
        $headers .= "X-MSMail-Priority: High\r\n";
        $headers .= "Importance: High\r\n";
        
        // Try to send with error suppression
        $sent = @mail($toEmail, $subject, $htmlMessage, $headers, "-f" . $fromEmail);
        
        if ($sent) {
            error_log("✅ Notice email sent successfully from $fromEmail to $toEmail");
            return [
                'success' => true,
                'message' => "Email sent from $fromEmail",
                'from_email' => $fromEmail
            ];
        } else {
            $lastError = error_get_last();
            error_log("❌ Failed to send notice email from $fromEmail to $toEmail: " . ($lastError['message'] ?? 'Unknown error'));
        }
        
        usleep(100000); // 0.1 second delay
    }
    
    // All attempts failed
    return [
        'success' => false,
        'message' => "Email failed: " . ($lastError['message'] ?? 'All from addresses failed'),
        'from_email' => $config['from_email'],
        'error' => $lastError
    ];
}

// ============================================
// FIX TABLE STRUCTURE
// ============================================
function fixTableStructure($conn) {
    $table = NOTICES_TABLE;
    
    // Check if table exists
    $checkTable = mysqli_query($conn, "SHOW TABLES LIKE '$table'");
    if (mysqli_num_rows($checkTable) == 0) {
        // Create table with all required columns
        $query = "CREATE TABLE $table (
            id INT AUTO_INCREMENT PRIMARY KEY,
            Student_No VARCHAR(50) NOT NULL,
            Full_Name VARCHAR(100) NOT NULL,
            Level VARCHAR(50) DEFAULT NULL,
            Email VARCHAR(100) DEFAULT NULL,
            Heading VARCHAR(255) NOT NULL,
            Message TEXT NOT NULL,
            Status VARCHAR(20) DEFAULT 'pending',
            Email_Sent_Date DATETIME DEFAULT NULL,
            Email_Details TEXT DEFAULT NULL,
            Created_By INT(11) DEFAULT NULL,
            Date_Created DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_student (Student_No),
            INDEX idx_status (Status),
            INDEX idx_created (Date_Created)
        ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci";
        
        mysqli_query($conn, $query);
        error_log("✅ Created table $table");
    } else {
        // Add missing columns if they don't exist
        $columns = [
            'Full_Name' => "ALTER TABLE $table ADD COLUMN Full_Name VARCHAR(100) NOT NULL AFTER Student_No",
            'Level' => "ALTER TABLE $table ADD COLUMN Level VARCHAR(50) DEFAULT NULL AFTER Full_Name",
            'Email_Sent_Date' => "ALTER TABLE $table ADD COLUMN Email_Sent_Date DATETIME DEFAULT NULL AFTER Status",
            'Email_Details' => "ALTER TABLE $table ADD COLUMN Email_Details TEXT DEFAULT NULL AFTER Email_Sent_Date"
        ];
        
        foreach ($columns as $column => $alter_query) {
            $checkColumn = mysqli_query($conn, "SHOW COLUMNS FROM $table LIKE '$column'");
            if (mysqli_num_rows($checkColumn) == 0) {
                mysqli_query($conn, $alter_query);
                error_log("✅ Added column $column to $table");
            }
        }
    }
    return true;
}

// Fix the table structure
fixTableStructure($conn);

// ============================================
// NOTICE DATABASE FUNCTIONS
// ============================================

function saveToNoticesTable($conn, $studentNo, $fullName, $level, $email, $heading, $message, $createdBy) {
    $table = NOTICES_TABLE;
    
    $query = "INSERT INTO $table (Student_No, Full_Name, Level, Email, Heading, Message, Status, Created_By, Date_Created) 
              VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NOW())";
    
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ssssssi", $studentNo, $fullName, $level, $email, $heading, $message, $createdBy);
        $result = mysqli_stmt_execute($stmt);
        $insertId = mysqli_stmt_insert_id($stmt);
        mysqli_stmt_close($stmt);
        
        if ($result) {
            error_log("✅ Notice saved: ID $insertId for student $studentNo");
            return $insertId;
        } else {
            error_log("❌ MySQL Error: " . mysqli_error($conn));
        }
    }
    return false;
}

function updateNoticeStatus($conn, $studentNo, $heading, $status, $emailDetails = '') {
    $table = NOTICES_TABLE;
    
    $query = "UPDATE $table SET 
              Status = ?, 
              Email_Sent_Date = IF(? IN ('sent', 'delivered'), NOW(), Email_Sent_Date),
              Email_Details = ?
              WHERE Student_No = ? AND Heading = ? 
              ORDER BY Date_Created DESC LIMIT 1";
    
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "sssss", $status, $status, $emailDetails, $studentNo, $heading);
        $result = mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
        return $result;
    }
    return false;
}

function noticeExists($conn, $studentNo, $heading) {
    $table = NOTICES_TABLE;
    
    $query = "SELECT id FROM $table WHERE Student_No = ? AND Heading = ? ORDER BY Date_Created DESC LIMIT 1";
    $stmt = mysqli_prepare($conn, $query);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ss", $studentNo, $heading);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        $exists = mysqli_stmt_num_rows($stmt) > 0;
        mysqli_stmt_close($stmt);
        return $exists;
    }
    return false;
}

// ============================================
// CSV VALIDATION - FOR YOUR EXACT CSV FORMAT
// ============================================

function validateCSVRow($data) {
    $errors = [];
    
    // Check if we have at least 4 columns
    if (count($data) < 4) {
        $errors[] = "CSV must have 4 columns: Student_No, Full Name, Level, Email";
        return [
            'is_valid' => false,
            'errors' => $errors,
            'student_no' => '',
            'full_name' => '',
            'level' => '',
            'email' => ''
        ];
    }
    
    // Extract data - YOUR EXACT COLUMN POSITIONS
    $studentNo = isset($data[0]) ? trim($data[0]) : '';
    $fullName = isset($data[1]) ? trim($data[1]) : '';
    $level = isset($data[2]) ? trim($data[2]) : '';
    $email = isset($data[3]) ? trim($data[3]) : '';
    
    // Required fields
    if (empty($studentNo)) {
        $errors[] = "Student Number is required (Column 1)";
    }
    
    if (empty($fullName)) {
        $errors[] = "Full Name is required (Column 2)";
    }
    
    // Email validation (required for sending email)
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format: " . $email;
    }
    
    return [
        'is_valid' => empty($errors),
        'errors' => $errors,
        'student_no' => $studentNo,
        'full_name' => $fullName,
        'level' => $level,
        'email' => $email
    ];
}

// ============================================
// MAIN PROCESSING LOGIC
// ============================================

$errors = [];
$processingResults = [];
$processedCount = 0;
$failedCount = 0;
$emailSentCount = 0;
$emailFailedCount = 0;
$sendEmail = false;
$saveToDatabase = false;
$Heading = '';
$Message = '';
$emailDetails = []; // For tracking email results

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    
    // Get form data
    if (empty($_POST['Heading'])) {
        $errors[] = "Notice Heading is required";
    } else {
        $Heading = mysqli_real_escape_string($conn, trim($_POST['Heading']));
    }
    
    if (empty($_POST['Message'])) {
        $errors[] = "Message is required";
    } else {
        $Message = mysqli_real_escape_string($conn, trim($_POST['Message']));
    }
    
    $sendEmail = isset($_POST['Send_Email']) && $_POST['Send_Email'] == 'yes';
    $saveToDatabase = isset($_POST['Save_Notice']) && $_POST['Save_Notice'] == 'yes';
    
    // Validate file
    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 (!in_array($fileExt, $allowedExtensions)) {
            $errors[] = "Only CSV files are allowed";
        }
    }
    
    // Process if no errors
    if (empty($errors)) {
        // Create upload directory if it doesn't exist
        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)) {
            
            if ($saveToDatabase) {
                mysqli_begin_transaction($conn);
            }
            
            try {
                $isFirstRow = true;
                $file = fopen($targetPath, "r");
                
                if ($file !== FALSE) {
                    $rowNumber = 0;
                    $dataRows = 0;
                    
                    while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
                        $rowNumber++;
                        
                        // Skip empty rows
                        if (empty(array_filter($data))) {
                            continue;
                        }
                        
                        // Skip first row (headers)
                        if ($isFirstRow) {
                            $isFirstRow = false;
                            continue;
                        }
                        
                        $dataRows++;
                        
                        if ($processedCount >= $maxRecords) {
                            $errors[] = "Processing limited to first $maxRecords records.";
                            break;
                        }
                        
                        // Validate the row
                        $validation = validateCSVRow($data);
                        
                        if ($validation['is_valid']) {
                            $Student_No = mysqli_real_escape_string($conn, $validation['student_no']);
                            $Full_Name = mysqli_real_escape_string($conn, $validation['full_name']);
                            $Level = mysqli_real_escape_string($conn, $validation['level']);
                            $Email = mysqli_real_escape_string($conn, $validation['email']);
                            
                            $status = "Success";
                            $statusClass = "status-success";
                            $actions = [];
                            $noticeId = null;
                            
                            // Save to database
                            if ($saveToDatabase) {
                                if (noticeExists($conn, $Student_No, $Heading)) {
                                    $status = "Duplicate Notice";
                                    $statusClass = "status-warning";
                                    $actions[] = "⚠️ Already exists";
                                    $failedCount++;
                                } else {
                                    $processedCount++;
                                    
                                    $noticeId = saveToNoticesTable(
                                        $conn, 
                                        $Student_No, 
                                        $Full_Name, 
                                        $Level, 
                                        $Email, 
                                        $Heading, 
                                        $Message, 
                                        $User
                                    );
                                    
                                    if ($noticeId) {
                                        $actions[] = "💾 Saved (ID: $noticeId)";
                                    } else {
                                        $actions[] = "❌ Save failed";
                                        $statusClass = "status-warning";
                                        $failedCount++;
                                    }
                                }
                            } else {
                                $processedCount++;
                            }
                            
                            // Send email using EXACT SAME FUNCTION as your working system
                            if ($sendEmail && !empty($Email)) {
                                if (filter_var($Email, FILTER_VALIDATE_EMAIL)) {
                                    $emailResult = sendNoticeEmail($Email, $Full_Name, $Heading, $Message, $emailConfig);
                                    
                                    // Track email details
                                    $emailDetails[] = [
                                        'to' => $Email,
                                        'name' => $Full_Name,
                                        'status' => $emailResult['success'] ? 'sent' : 'failed',
                                        'message' => $emailResult['message'],
                                        'from_email' => $emailResult['from_email'] ?? 'N/A'
                                    ];
                                    
                                    if ($emailResult['success']) {
                                        $emailSentCount++;
                                        $actions[] = "📧 Sent";
                                        
                                        if ($saveToDatabase && $noticeId) {
                                            updateNoticeStatus($conn, $Student_No, $Heading, 'sent', $emailResult['message']);
                                        }
                                    } else {
                                        $emailFailedCount++;
                                        $actions[] = "✗ Email failed";
                                        $statusClass = "status-warning";
                                        $status = "Success (Email failed)";
                                        
                                        if ($saveToDatabase && $noticeId) {
                                            updateNoticeStatus($conn, $Student_No, $Heading, 'failed', $emailResult['message']);
                                        }
                                    }
                                } else {
                                    $actions[] = "📧 Invalid email";
                                    $statusClass = "status-warning";
                                }
                            } elseif ($sendEmail && empty($Email)) {
                                $actions[] = "📧 No email";
                                $statusClass = "status-warning";
                            }
                            
                            // Store result
                            $processingResults[] = [
                                'rowNumber' => $dataRows,
                                'Student_No' => $validation['student_no'],
                                'Full_Name' => $validation['full_name'],
                                'Level' => $validation['level'],
                                'Email' => $validation['email'],
                                'status' => $status,
                                'statusClass' => $statusClass,
                                'actions' => implode(' | ', $actions)
                            ];
                            
                        } else {
                            $failedCount++;
                            $processingResults[] = [
                                'rowNumber' => $dataRows,
                                'Student_No' => $data[0] ?? 'N/A',
                                'Full_Name' => $data[1] ?? 'N/A',
                                'Level' => $data[2] ?? 'N/A',
                                'Email' => $data[3] ?? 'N/A',
                                'status' => 'Invalid: ' . implode(', ', $validation['errors']),
                                'statusClass' => 'status-error',
                                'actions' => '❌ Validation failed'
                            ];
                        }
                    }
                    
                    fclose($file);
                    
                    if ($saveToDatabase) {
                        mysqli_commit($conn);
                    }
                    
                    $_SESSION['success'] = "✅ Processing completed! Processed: $processedCount, Failed: $failedCount, Emails Sent: $emailSentCount, Emails Failed: $emailFailedCount";
                    $_SESSION['email_details'] = $emailDetails;
                    
                } else {
                    throw new Exception("Failed to open uploaded file");
                }
                
            } catch (Exception $e) {
                if ($saveToDatabase) {
                    mysqli_rollback($conn);
                }
                $errors[] = "Processing failed: " . $e->getMessage();
            }
            
            // Delete uploaded file
            if (file_exists($targetPath)) {
                unlink($targetPath);
            }
            
        } else {
            $errors[] = "Failed to move uploaded file. Please check directory permissions.";
        }
    }
    
    if (!empty($errors)) {
        $_SESSION['errors'] = $errors;
    }
}

// ============================================
// DISPLAY RESULTS
// ============================================
ob_clean();
include_once 'include/AdminHeader.php';

// Get email details from session
$emailDetails = $_SESSION['email_details'] ?? [];
unset($_SESSION['email_details']);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notice Upload Results - Edgeview Academy</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body { font-family: 'Arial', sans-serif; background: #f8f9fa; }
        .status-success { color: #28a745; font-weight: bold; }
        .status-warning { color: #ffc107; font-weight: bold; }
        .status-error { color: #dc3545; font-weight: bold; }
        .summary-box { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; text-align: center; margin: 10px 0; }
        .summary-number { font-size: 42px; font-weight: bold; }
        .table { background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
        .table thead th { background: #1a237e; color: white; border: none; }
        .btn { border-radius: 50px; padding: 12px 30px; margin: 5px; }
        .btn-primary { background: #1a237e; border: none; }
        .btn-primary:hover { background: #0d1b5e; }
        .level-badge { background: #17a2b8; color: white; padding: 3px 8px; border-radius: 4px; font-size: 12px; }
        .notice-preview { background: #1a237e; color: white; padding: 25px; border-radius: 10px; margin: 20px 0; }
        .error-message { background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
        .success-message { background: #d4edda; border: 1px solid #c3e6cb; color: #155724; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
        .email-log { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px; }
        .badge-success { background: #d4edda; color: #155724; padding: 5px 10px; border-radius: 12px; }
        .badge-danger { background: #f8d7da; color: #721c24; padding: 5px 10px; border-radius: 12px; }
    </style>
</head>
<body>
<div id="page-wrapper">
    <div class="container-fluid">
        <br><br><br>
        
        <?php if (!empty($errors)): ?>
            <div class="error-message">
                <h4><i class="fas fa-exclamation-triangle"></i> Errors:</h4>
                <ul class="mb-0">
                    <?php foreach($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['success'])): ?>
            <div class="success-message">
                <h4><i class="fas fa-check-circle"></i> Success!</h4>
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($Heading) && !empty($Message)): ?>
        <div class="notice-preview">
            <h3><i class="fas fa-file-alt"></i> Notice Sent</h3>
            <h4><?php echo htmlspecialchars($Heading); ?></h4>
            <p><?php echo nl2br(htmlspecialchars($Message)); ?></p>
        </div>
        <?php endif; ?>
        
        <?php if (!empty($processingResults)): ?>
        <div class="row">
            <div class="col-md-12">
                <h3><i class="fas fa-table"></i> Processing Results</h3>
                <p><strong>Total records processed:</strong> <?php echo count($processingResults); ?></p>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Student No</th>
                                <th>Full Name</th>
                                <th>Level</th>
                                <th>Email</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($processingResults as $result): ?>
                            <tr>
                                <td><?php echo $result['rowNumber']; ?></td>
                                <td><strong><?php echo htmlspecialchars($result['Student_No']); ?></strong></td>
                                <td><?php echo htmlspecialchars($result['Full_Name']); ?></td>
                                <td>
                                    <?php if (!empty($result['Level'])): ?>
                                        <span class="level-badge"><?php echo htmlspecialchars($result['Level']); ?></span>
                                    <?php else: ?>N/A<?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($result['Email']); ?></td>
                                <td class="<?php echo $result['statusClass']; ?>">
                                    <strong><?php echo htmlspecialchars($result['status']); ?></strong>
                                </td>
                                <td><?php echo $result['actions']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if (!empty($emailDetails)): ?>
        <div class="row">
            <div class="col-md-12">
                <div class="email-log">
                    <h4><i class="fas fa-envelope"></i> Email Delivery Report</h4>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>To Email</th>
                                    <th>Student</th>
                                    <th>Status</th>
                                    <th>From Address</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($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>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-12 text-center">
                <a href="Notices.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-upload"></i> Upload Another Notice
                </a>
                <a href="Notices.php" class="btn btn-success btn-lg">
                    <i class="fas fa-list"></i> View All Notices
                </a>
                <a href="?debug=1" class="btn btn-info btn-lg">
                    <i class="fas fa-bug"></i> Debug Info
                </a>
            </div>
        </div>
        
        <?php if (isset($_GET['debug'])): ?>
        <div style="margin-top: 30px; padding: 20px; background: #f8f9fa; border-radius: 10px;">
            <h4>Debug Information:</h4>
            <pre>
Email Configuration:
From Email: <?php echo $emailConfig['from_email']; ?>
From Name: <?php echo $emailConfig['from_name']; ?>
Reply-To: <?php echo $emailConfig['reply_to']; ?>

Processing Stats:
Processed: <?php echo $processedCount; ?>
Failed: <?php echo $failedCount; ?>
Emails Sent: <?php echo $emailSentCount; ?>
Emails Failed: <?php echo $emailFailedCount; ?>

PHP Version: <?php echo phpversion(); ?>
Server: <?php echo $_SERVER['SERVER_NAME']; ?>
            </pre>
        </div>
        <?php endif; ?>
        
    </div>
</div>
</body>
</html>
<?php
ob_end_flush();
?>