/*!
Theme Name: Eduvalt
Theme URI: https://ifingerstudio.com/eduvalt/
Author: johanspond
Author URI: https://themeforest.net/user/johanspond/
Description: Eduvalt - Online Courses & Education WordPress Theme
Version: 2.0.2
License: GNU General Public License v2 or later
License URI: LICENSE
Text Domain: eduvalt
Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
*/ 

<?php
// Create certificate verification table
function create_certificate_table() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'certificates';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        certificate_id varchar(50) NOT NULL UNIQUE,
        recipient_name varchar(255) NOT NULL,
        course_name varchar(255) NOT NULL,
        issue_date date NOT NULL,
        issuer_name varchar(255) NOT NULL,
        certificate_hash varchar(64) NOT NULL,
        status varchar(20) DEFAULT 'active',
        created_at timestamp DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY certificate_id (certificate_id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Run this function when theme is activated
add_action('after_setup_theme', 'create_certificate_table');

// Function to generate unique certificate ID
function generate_certificate_id() {
    return 'CERT-' . date('Y') . '-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
}

// Function to add new certificate
function add_certificate($recipient_name, $course_name, $issuer_name) {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'certificates';
    $certificate_id = generate_certificate_id();
    $certificate_hash = hash('sha256', $certificate_id . $recipient_name . $course_name . date('Y-m-d'));
    
    $result = $wpdb->insert(
        $table_name,
        array(
            'certificate_id' => $certificate_id,
            'recipient_name' => $recipient_name,
            'course_name' => $course_name,
            'issue_date' => date('Y-m-d'),
            'issuer_name' => $issuer_name,
            'certificate_hash' => $certificate_hash
        )
    );
    
    if ($result) {
        return $certificate_id;
    }
    return false;
}

// Function to verify certificate
function verify_certificate($certificate_id) {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'certificates';
    
    $certificate = $wpdb->get_row(
        $wpdb->prepare("SELECT * FROM $table_name WHERE certificate_id = %s AND status = 'active'", $certificate_id)
    );
    
    return $certificate;
}
?>

<?php
// Add admin menu for certificate management
function certificate_admin_menu() {
    add_menu_page(
        'Certificate Manager',
        'Certificates',
        'manage_options',
        'certificate-manager',
        'certificate_admin_page',
        'dashicons-awards',
        30
    );
}
add_action('admin_menu', 'certificate_admin_menu');

// Admin page HTML
function certificate_admin_page() {
    if (isset($_POST['add_certificate'])) {
        $recipient = sanitize_text_field($_POST['recipient_name']);
        $course = sanitize_text_field($_POST['course_name']);
        $issuer = sanitize_text_field($_POST['issuer_name']);
        
        $cert_id = add_certificate($recipient, $course, $issuer);
        
        if ($cert_id) {
            echo '<div class="notice notice-success"><p>Certificate created successfully! ID: ' . $cert_id . '</p></div>';
        } else {
            echo '<div class="notice notice-error"><p>Failed to create certificate.</p></div>';
        }
    }
    
    ?>
    <div class="wrap">
        <h1>Certificate Manager</h1>
        
        <div class="card">
            <h2>Add New Certificate</h2>
            <form method="post" action="">
                <table class="form-table">
                    <tr>
                        <th scope="row">Recipient Name</th>
                        <td><input type="text" name="recipient_name" required class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row">Course/Program Name</th>
                        <td><input type="text" name="course_name" required class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row">Issuer Name</th>
                        <td><input type="text" name="issuer_name" required class="regular-text" /></td>
                    </tr>
                </table>
                <?php submit_button('Add Certificate', 'primary', 'add_certificate'); ?>
            </form>
        </div>
        
        <div class="card">
            <h2>Recent Certificates</h2>
            <?php
            global $wpdb;
            $table_name = $wpdb->prefix . 'certificates';
            $certificates = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 10");
            
            if ($certificates) {
                echo '<table class="wp-list-table widefat fixed striped">';
                echo '<thead><tr><th>Certificate ID</th><th>Recipient</th><th>Course</th><th>Issue Date</th><th>QR Code</th></tr></thead>';
                echo '<tbody>';
                
                foreach ($certificates as $cert) {
                    $qr_url = home_url('/certificate-qr/') . $cert->certificate_id;
                    echo '<tr>';
                    echo '<td>' . $cert->certificate_id . '</td>';
                    echo '<td>' . $cert->recipient_name . '</td>';
                    echo '<td>' . $cert->course_name . '</td>';
                    echo '<td>' . $cert->issue_date . '</td>';
                    echo '<td><a href="' . $qr_url . '" target="_blank">Generate QR</a></td>';
                    echo '</tr>';
                }
                
                echo '</tbody></table>';
            } else {
                echo '<p>No certificates found.</p>';
            }
            ?>
        </div>
    </div>
    <?php
}
?>

<?php
// Handle QR code generation requests
function handle_qr_code_request() {
    if (strpos($_SERVER['REQUEST_URI'], '/certificate-qr/') !== false) {
        $path_parts = explode('/certificate-qr/', $_SERVER['REQUEST_URI']);
        if (count($path_parts) > 1) {
            $certificate_id = sanitize_text_field($path_parts[1]);
            generate_qr_code($certificate_id);
            exit;
        }
    }
}
add_action('init', 'handle_qr_code_request');

// Generate QR code using Google Charts API
function generate_qr_code($certificate_id) {
    // Verify certificate exists
    $certificate = verify_certificate($certificate_id);
    
    if (!$certificate) {
        header('HTTP/1.0 404 Not Found');
        echo 'Certificate not found';
        return;
    }
    
    // Create verification URL
    $verify_url = home_url('/verify-certificate/') . $certificate_id;
    
    // Generate QR code using Google Charts API
    $qr_api_url = 'https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=' . urlencode($verify_url);
    
    header('Content-Type: image/png');
    
    // Get QR code image
    $qr_image = file_get_contents($qr_api_url);
    
    if ($qr_image) {
        echo $qr_image;
    } else {
        // Fallback: create simple QR code HTML
        header('Content-Type: text/html');
        echo '<div style="text-align:center; padding:20px;">';
        echo '<h3>QR Code for Certificate: ' . $certificate_id . '</h3>';
        echo '<img src="' . $qr_api_url . '" alt="QR Code">';
        echo '<p>Verification URL: <a href="' . $verify_url . '">' . $verify_url . '</a></p>';
        echo '</div>';
    }
}

// Alternative QR code generator using QR Server API
function generate_qr_code_alternative($certificate_id) {
    $certificate = verify_certificate($certificate_id);
    
    if (!$certificate) {
        header('HTTP/1.0 404 Not Found');
        echo 'Certificate not found';
        return;
    }
    
    $verify_url = home_url('/verify-certificate/') . $certificate_id;
    
    // Using QR Server API (free alternative)
    $qr_api_url = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($verify_url);
    
    header('Content-Type: image/png');
    
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'user_agent' => 'Mozilla/5.0 (compatible; WordPress QR Generator)'
        ]
    ]);
    
    $qr_image = file_get_contents($qr_api_url, false, $context);
    
    if ($qr_image) {
        echo $qr_image;
    } else {
        // Fallback HTML
        header('Content-Type: text/html');
        echo '<div style="text-align:center; padding:20px; font-family:Arial;">';
        echo '<h3>Certificate QR Code</h3>';
        echo '<p>Certificate ID: ' . $certificate_id . '</p>';
        echo '<img src="' . $qr_api_url . '" alt="QR Code" style="border:1px solid #ccc;">';
        echo '<p style="margin-top:20px;"><strong>Verification URL:</strong><br>';
        echo '<a href="' . $verify_url . '">' . $verify_url . '</a></p>';
        echo '</div>';
    }
}
?>

<?php
// Handle certificate verification requests
function handle_verification_request() {
    if (strpos($_SERVER['REQUEST_URI'], '/verify-certificate/') !== false) {
        $path_parts = explode('/verify-certificate/', $_SERVER['REQUEST_URI']);
        if (count($path_parts) > 1) {
            $certificate_id = sanitize_text_field($path_parts[1]);
            show_verification_page($certificate_id);
            exit;
        }
    }
}
add_action('init', 'handle_verification_request');

// Display verification page
function show_verification_page($certificate_id) {
    $certificate = verify_certificate($certificate_id);
    
    get_header();
    ?>
    
    <div style="max-width: 800px; margin: 40px auto; padding: 20px; font-family: Arial, sans-serif;">
        <div style="text-align: center; margin-bottom: 30px;">
            <h1 style="color: #2c3e50; margin-bottom: 10px;">Certificate Verification</h1>
            <hr style="width: 100px; border: 2px solid #3498db; margin: 20px auto;">
        </div>
        
        <?php if ($certificate): ?>
            <div style="background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 30px; margin: 20px 0;">
                <div style="text-align: center; margin-bottom: 20px;">
                    <div style="display: inline-block; background: #28a745; color: white; padding: 10px 20px; border-radius: 5px; font-weight: bold;">
                        ✓ VERIFIED CERTIFICATE
                    </div>
                </div>
                
                <table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
                    <tr style="border-bottom: 1px solid #dee2e6;">
                        <td style="padding: 15px; font-weight: bold; color: #495057; width: 30%;">Certificate ID:</td>
                        <td style="padding: 15px; color: #212529;"><?php echo esc_html($certificate->certificate_id); ?></td>
                    </tr>
                    <tr style="border-bottom: 1px solid #dee2e6;">
                        <td style="padding: 15px; font-weight: bold; color: #495057;">Recipient:</td>
                        <td style="padding: 15px; color: #212529; font-size: 18px; font-weight: bold;"><?php echo esc_html($certificate->recipient_name); ?></td>
                    </tr>
                    <tr style="border-bottom: 1px solid #dee2e6;">
                        <td style="padding: 15px; font-weight: bold; color: #495057;">Course/Program:</td>
                        <td style="padding: 15px; color: #212529;"><?php echo esc_html($certificate->course_name); ?></td>
                    </tr>
                    <tr style="border-bottom: 1px solid #dee2e6;">
                        <td style="padding: 15px; font-weight: bold; color: #495057;">Issuer:</td>
                        <td style="padding: 15px; color: #212529;"><?php echo esc_html($certificate->issuer_name); ?></td>
                    </tr>
                    <tr style="border-bottom: 1px solid #dee2e6;">
                        <td style="padding: 15px; font-weight: bold; color: #495057;">Issue Date:</td>
                        <td style="padding: 15px; color: #212529;"><?php echo date('F j, Y', strtotime($certificate->issue_date)); ?></td>
                    </tr>
                    <tr>
                        <td style="padding: 15px; font-weight: bold; color: #495057;">Verification Hash:</td>
                        <td style="padding: 15px; color: #6c757d; font-family: monospace; font-size: 12px; word-break: break-all;"><?php echo esc_html(substr($certificate->certificate_hash, 0, 16)); ?>...</td>
                    </tr>
                </table>
                
                <div style="text-align: center; margin-top: 30px; padding: 20px; background: #e7f3ff; border-radius: 5px;">
                    <p style="margin: 0; color: #0066cc; font-weight: bold;">
                        This certificate has been verified as authentic and valid.
                    </p>
                    <p style="margin: 10px 0 0 0; color: #666; font-size: 14px;">
                        Verified on <?php echo date('F j, Y \a\t g:i A'); ?>
                    </p>
                </div>
            </div>
            
        <?php else: ?>
            <div style="background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 30px; text-align: center;">
                <div style="color: #721c24; font-size: 24px; margin-bottom: 15px;">❌</div>
                <h2 style="color: #721c24; margin-bottom: 15px;">Certificate Not Found</h2>
                <p style="color: #721c24; margin-bottom: 20px;">
                    The certificate ID "<?php echo esc_html($certificate_id); ?>" could not be verified.
                </p>
                <p style="color: #856404; font-size: 14px;">
                    This could mean the certificate ID is incorrect, the certificate has been revoked, 
                    or it was not issued by this organization.
                </p>
            </div>
        <?php endif; ?>
        
        <div style="text-align: center; margin-top: 40px;">
            <a href="<?php echo home_url(); ?>" style="display: inline-block; background: #007cba; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; font-weight: bold;">
                ← Back to Homepage
            </a>
        </div>
    </div>
    
    <?php
    get_footer();
}

// Add verification shortcode for use in pages/posts
function certificate_verification_shortcode($atts) {
    $atts = shortcode_atts(array(
        'certificate_id' => ''
    ), $atts);
    
    if (!empty($atts['certificate_id'])) {
        $certificate = verify_certificate($atts['certificate_id']);
        
        if ($certificate) {
            return '<div class="certificate-verified">Certificate ' . $atts['certificate_id'] . ' is valid for ' . $certificate->recipient_name . '</div>';
        } else {
            return '<div class="certificate-invalid">Certificate ' . $atts['certificate_id'] . ' could not be verified.</div>';
        }
    }
    
    return '<div class="certificate-error">No certificate ID provided.</div>';
}
add_shortcode('verify_certificate', 'certificate_verification_shortcode');
?>