<?php
require 'db_config.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Include PHPMailer library
require 'PHPMailer/vendor/autoload.php';

include "../phpqrcode-master/lib/qrlib.php";
require('fpdf/fpdf.php');

if (!file_exists('qrcodes')) {
    mkdir('qrcodes', 0755, true);
}

if (!file_exists('pdfs')) {
    mkdir('pdfs', 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $participant_type = $_POST['participant_type'];
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $payment_status = $_POST['payment_status'];
    $commitment_status = isset($_POST['commitment_status']) ? $_POST['commitment_status'] : null;
    $hotel = $_POST['hotel'];
    $institution = $_POST['institution'];
    $membership_type = $_POST['membership_type'];
    $meals_allocated = $_POST['meals_allocated'];

    $meals_remaining = $meals_allocated; // Assuming 2 meals per day

    $stmt = $conn->prepare("INSERT INTO users (participant_type, fullname, email, phone, payment_status, commitment_status, hotel, institution, membership_type, meals_allocated, meals_remaining) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssssii", $participant_type, $fullname, $email, $phone, $payment_status, $commitment_status, $hotel, $institution, $membership_type, $meals_allocated, $meals_remaining);

    if ($stmt->execute()) {
        $user_id = $stmt->insert_id;

        // Generate QR Code
        $qr_data = $user_id;
        $qr_filename = 'qrcodes/user_' . $user_id . '.png';
        QRcode::png($qr_data, $qr_filename);

        // Save QR Code to the database
        $stmt = $conn->prepare("UPDATE users SET qr_code = ? WHERE id = ?");
        $stmt->bind_param("si", $qr_filename, $user_id);
        $stmt->execute();

        // Generate PDF with QR Code
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 10, 'QR Code for ' . $fullname, 0, 1, 'C'); // Center the title

         // Calculate the center position for the QR code
        $pageWidth = $pdf->GetPageWidth();
        $imageWidth = 50; // QR code width
        $imageX = ($pageWidth - $imageWidth) / 2; // Center the image horizontally

        $pdf->Image($qr_filename, $imageX, 50, $imageWidth, $imageWidth);
        $pdf_filename = 'pdfs/qr_code_' . $fullname . '.pdf';
        $pdf->Output($pdf_filename, 'F');

        // Prepare to send email with PHPMailer
        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
            $mail->SMTPAuth = true;
            $mail->Username = ''; // SMTP username
            $mail->Password = ''; // SMTP password
            $mail->SMTPSecure = 'tls'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
            $mail->Port = 587;

            // Recipients
            $mail->setFrom('deanmagombo@gmail.com', 'Mips');
            $mail->addAddress($email, $fullname);

            // Attachments
            $mail->addAttachment($pdf_filename); // Attach the generated PDF

            // Content
            $mail->isHTML(true);
            $mail->Subject = 'Your QR Code for the Event';
            $mail->Body = '<p>Dear ' . htmlspecialchars($fullname) . ',</p>
                           <p>Thank you for registering for the event. Please find your QR code attached in the PDF. You will need this to check in at the event.</p>
                           <p>Best regards,<br>Mips Team</p>';

            $mail->send();
            echo 'Message has been sent';
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }

        // Display confirmation and buttons
        echo "<div style='text-align:center;'>";
        echo "<button style='display:inline-block; padding:10px 20px; background-color:#007bff; color:#fff; text-decoration:none; border:none; border-radius:5px; margin:5px; font-family: Arial, sans-serif; font-weight: bold;' onclick=\"window.location.href='index.php'\">Register</button>";
        echo "<button style='display:inline-block; padding:10px 20px; background-color:#28a745; color:#fff; text-decoration:none; border:none; border-radius:5px; margin:5px; font-family: Arial, sans-serif; font-weight: bold;' onclick=\"window.location.href='users.php'\">View Participants</button>";
        echo "<button style='display:inline-block; padding:10px 20px; background-color:#dc3545; color:#fff; text-decoration:none; border:none; border-radius:5px; margin:5px; font-family: Arial, sans-serif; font-weight: bold;' onclick=\"window.location.href='generate_pdf.php?id=" . htmlspecialchars($user_id) . "'\">Generate PDF</button>";
        echo "</div>";
        echo "<div style='text-align:center;'><h2>QR Code for $fullname</h2>";
        echo "<br><img src='$qr_filename' alt='QR Code'></div>";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>
