<?php
require 'db_config.php';

include "../phpqrcode-master/lib/qrlib.php";

// Ensure the qrcodes directory exists and is writable
if (!file_exists('qrcodes')) {
    mkdir('qrcodes', 0755, true);
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $participant_type = $_POST['participant_type'];
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $payment_status = isset($_POST['payment_status']) ? $_POST['payment_status'] : '';
    $commitment_status = isset($_POST['commitment_status']) ? $_POST['commitment_status'] : '';
    $hotel = $_POST['hotel'];
    $institution = isset($_POST['institution']) ? $_POST['institution'] : '';
    $membership_type = isset($_POST['membership_type']) ? $_POST['membership_type'] : '';

    // Insert data into the database
    $stmt = $conn->prepare("INSERT INTO users (participant_type, fullname, email, phone, payment_status, commitment_status, hotel, institution, membership_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssssss", $participant_type, $fullname, $email, $phone, $payment_status, $commitment_status, $hotel, $institution, $membership_type);

    if ($stmt->execute()) {
        // Get the inserted record's ID
        $user_id = $stmt->insert_id;

        // Generate QR code
        $qr_data = "http://localhost/1/mips/php/edit_user.php?id=" . $user_id;

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

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

        header("Location: qrcodes.php?id=$user_id");
        exit();
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>
