<?php
require 'vendor/autoload.php';
require_once ('vendor/mpdf/mpdf/src/Mpdf.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Database connection
$servername = "localhost";
$username = "globanmq_membership";
$password = "swTL3s[X#yWl";
$dbname = "globanmq_membership";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
function generateUniqueNumber() {
    $file_path = 'unique_number.txt';

    if (file_exists($file_path)) {
        $current_number = (int) file_get_contents($file_path);
    } else {
        $current_number = 0;
    }

    $current_number++;

    file_put_contents($file_path, $current_number);

    return str_pad($current_number, 6, '0', STR_PAD_LEFT);
}

$organisation = $_POST['organisation'] ?? '';
$address = $_POST['address'] ?? '';
$industry = $_POST['industry'] ?? '';
$gst = $_POST['gst'] ?? '';
$committees = isset($_POST['committees']) ? json_encode($_POST['committees']) : '';

$nominee1 = [
    'name' => $_POST['nominee1_name'] ?? '',
    'designation' => $_POST['nominee1_designation'] ?? '',
    'email' => $_POST['nominee1_email'] ?? '',
    'website' => $_POST['nominee1_website'] ?? '',
    'mobile' => $_POST['nominee1_mobile'] ?? '',
    'phone' => $_POST['nominee1_phone'] ?? '',
];

$nominee2 = [
    'name' => $_POST['nominee2_name'] ?? '',
    'designation' => $_POST['nominee2_designation'] ?? '',
    'email' => $_POST['nominee2_email'] ?? '',
    'website' => $_POST['nominee2_website'] ?? '',
    'mobile' => $_POST['nominee2_mobile'] ?? '',
    'phone' => $_POST['nominee2_phone'] ?? '',
];

$signature_path = '';
// Handle signature upload

if (isset($_POST['signature_option'])) {
    $target_dir = "signature/";

    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    if (isset($_POST['upload_data']) && $_POST['signature_option']!= "canvas") {
        $signature_data = $_POST['upload_data'];
        if (preg_match('/^data:image\/(\w+);base64,/', $signature_data, $type)) {
            $signature_data = substr($signature_data, strpos($signature_data, ',') + 1);
            $type = strtolower($type[1]);

            if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                echo "Invalid image type.";
                exit;
            }

            $signature_data = base64_decode($signature_data);
            if ($signature_data === false) {
                echo "Base64 decode failed.";
                exit;
            }

            $unique_number = generateUniqueNumber();
            $file_name = 'iamai_' . $unique_number . '.' . $type;
            $target_file = $target_dir . $file_name;

            if (file_put_contents($target_file, $signature_data)) {
                $signature_path = $file_name;
            } else {
                echo "Error saving signature.";
                exit;
            }
        } else {
            echo "Invalid signature data.";
            exit;
        }
    } elseif (isset($_POST['signature_data'])) {
        $signature_data = $_POST['signature_data'];
        if (preg_match('/^data:image\/(\w+);base64,/', $signature_data, $type)) {
            $signature_data = substr($signature_data, strpos($signature_data, ',') + 1);
            $type = strtolower($type[1]);

            if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                echo "Invalid image type.";
                exit;
            }

            $signature_data = base64_decode($signature_data);
            if ($signature_data === false) {
                echo "Base64 decode failed.";
                exit;
            }

            $unique_number = generateUniqueNumber();
            $file_name = 'iamai_' . $unique_number . '.' . $type;
            $target_file = $target_dir . $file_name;

            if (file_put_contents($target_file, $signature_data)) {
                $signature_path = $file_name;
            } else {
                echo "Error saving signature.";
                exit;
            }
        } else {
            echo "Invalid signature data.";
            exit;
        }
    }
}


// Insert data into the database
$stmt = $conn->prepare("INSERT INTO membership (organisation, address, industry, gst, committees, signature) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $organisation, $address, $industry, $gst, $committees, $signature_path);

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

    $stmt_nominee1 = $conn->prepare("INSERT INTO nominee (membership_id, name, designation, email, website, mobile, phone) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt_nominee1->bind_param("issssss", $membership_id, $nominee1['name'], $nominee1['designation'], $nominee1['email'], $nominee1['website'], $nominee1['mobile'], $nominee1['phone']);
    
    if ($stmt_nominee1->execute()) {
         $stmt_nominee2 = $conn->prepare("INSERT INTO nominee (membership_id, name, designation, email, website, mobile, phone) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt_nominee2->bind_param("issssss", $membership_id, $nominee2['name'], $nominee2['designation'], $nominee2['email'], $nominee2['website'], $nominee2['mobile'], $nominee2['phone']);
    
        if ($stmt_nominee2->execute()) {
            try {

                $pdf_filename = generatePDF($membership_id, $organisation, $address, $industry, $gst, $committees, $nominee1["name"], $nominee1["designation"], $nominee1["email"], $nominee1["website"], $nominee1["mobile"], $nominee1["phone"], $nominee2["name"], $nominee2["designation"], $nominee2["email"],$nominee2["mobile"], $signature_path);


                $phpmailer = new PHPMailer(true); 
                $phpmailer->isSMTP();
                $phpmailer->Host = 'smtp.gmail.com';
                $phpmailer->SMTPAuth = true;
                $phpmailer->Port = 587;
                $phpmailer->Username = 'awards@fintechcouncil.in';
                $phpmailer->Password = 'fgzairfqsgpulorf';
                $phpmailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                $phpmailer->SMTPDebug = 2;

                $phpmailer->setFrom('awards@fintechcouncil.in', 'IAMAI Registration');
                $phpmailer->addAddress('rakeshg@iamai.in');

                $phpmailer->Subject = 'Membership Form Submission';
                $phpmailer->Body = "Thank you for registering. Please find attached the membership form.";
                $phpmailer->AltBody = 'Thank you for registering.';
                $phpmailer->addAttachment($pdf_filename);

                if (!$phpmailer->send()) {
                    echo 'Mailer Error: ' . $phpmailer->ErrorInfo;
                } else {
                    echo 'Email sent successfully!';
                }
            } catch (Exception $e) {
                echo 'Mail sending failed: ' . $e->getMessage();
            }
        } else {
            echo "Error: " . $stmt_nominee2->error;
        }
    } else {
        echo "Error: " . $stmt_nominee1->error;
    }
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
function generatePDF($membership_id, $organisation, $address, $industry, $gst, $committees, $nominee1_name, $nominee1_designation, $nominee1_email, $nominee1_website, $nominee1_mobile, $nominee1_phone, $nominee2_name, $nominee2_designation, $nominee2_email, $nominee2_mobile, $signature_path)
{

    $pdf = new \Mpdf\Mpdf();

    $pdf->SetTitle('Membership Form');
    $pdf->SetAuthor('Your Organization');
    $pdf->SetCreator('Your Organization');
    $pdf->SetKeywords('Membership, Form, PDF');

    $pdf->AddPage();
    $html = '
    <style>
    body {
        font-family: Arial, sans-serif;
    }
    h1 {
        text-align: center;
        margin-bottom: 20px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th, td {
        padding: 10px;
        border: 1px solid #ddd;
    }
    th {
        background-color: #f2f2f2;
    }
    .section-title {
        font-size: 18px;
        margin-top: 20px;
        margin-bottom: 10px;
    }
    .section {
        margin-bottom: 20px;
    }
    .signature {
        text-align: right;
    }
    .signature img {
        width: 150px;
    }
    .full-width {
        width: 100%;
    }
    .two-column {
        display: flex;
    }
    .two-column > div {
        width: 50%;
        padding: 10px;
    }
    .page-break {
        page-break-before: always;
    }
    .centered-image {
        text-align: center;
        margin-bottom: 20px;
    }
    .border-layout {
        border: 2px solid #000;
        padding: 20px;
    }
</style>

    <div class="border-layout">
        <div class="centered-image">
            <img src="assets/images/iamai-logo.png" alt="IAMAI Logo">
        </div>

        <h1>Member Application Form</h1>

        <div class="section">
            <table>
                <tr>
                    <th>Organisation (Legal Entity Name)</th>
                    <td colspan="3">' . $organisation . '</td>
                </tr>
                <tr>
                    <th>Address</th>
                    <td colspan="3">' . $address . '</td>
                </tr>
                <tr>
                    <th>Type of Industry</th>
                    <td colspan="3">' . $industry . '</td>
                </tr>
                <tr>
                    <th>GST Reg. No.</th>
                    <td colspan="3">' . $gst . '</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">Nominee 1</h2>
            <table>
                <tr>
                    <th>Name</th>
                    <td>' . $nominee1_name . '</td>
                    <th>Designation</th>
                    <td>' . $nominee1_designation . '</td>
                </tr>
                <tr>
                    <th>Email</th>
                    <td>' . $nominee1_email . '</td>
                    <th>Website</th>
                    <td>' . $nominee1_website . '</td>
                </tr>
                <tr>
                    <th>Mobile</th>
                    <td>' . $nominee1_mobile . '</td>
                    <th>Phone</th>
                    <td>' . $nominee1_phone . '</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">Nominee 2</h2>
            <table>
                <tr>
                    <th>Name</th>
                    <td>' . $nominee2_name . '</td>
                    <th>Designation</th>
                    <td>' . $nominee2_designation . '</td>
                </tr>
                <tr>
                    <th>Email</th>
                    <td>' . $nominee2_email . '</td>
                   <th>Mobile</th>
                    <td>' . $nominee2_mobile . '</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">Committees</h2>
            <p>' . nl2br($committees) . '</p>
        </div>

        <div class="section page-break">
            <h2 class="section-title">Membership Fee Structure</h2>
            <table>
                <tr>
                    <th>Turnover/Classification (in INR)</th>
                    <th>Annual Membership Fee (INR)</th>
                    <th>Event Participation Invitations</th>
                    <th>Committees</th>
                </tr>
                <tr>
                    <td>0-5 cr</td>
                    <td>1,50,000</td>
                    <td>35</td>
                    <td>1</td>
                </tr>
                <tr>
                    <td>5-10 cr</td>
                    <td>3,00,000</td>
                    <td>45</td>
                    <td>2</td>
                </tr>
                <tr>
                    <td>10-25 cr</td>
                    <td>5,00,000</td>
                    <td>60</td>
                    <td>3</td>
                </tr>
                <tr>
                    <td>25-50 cr</td>
                    <td>6,00,000</td>
                    <td>75</td>
                    <td>4</td>
                </tr>
                <tr>
                    <td>50-100 cr</td>
                    <td>8,00,000</td>
                    <td>100</td>
                    <td>No-Limit</td>
                </tr>
                <tr>
                    <td>100-500 cr</td>
                    <td>10,00,000</td>
                    <td>125</td>
                    <td>No-Limit</td>
                </tr>
                <tr>
                    <td>500-1000 cr</td>
                    <td>15,00,000</td>
                    <td>150</td>
                    <td>No-Limit</td>
                </tr>
                <tr>
                    <td>1000 cr and above</td>
                    <td>20,00,000</td>
                    <td>175</td>
                    <td>No-Limit</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">Signature</h2>
            <div class="signature">
                <img height=50px src="https://eventsites.iamai.in/InterestForm/Iamai-Member/signature/' . $signature_path . '" alt="Signature">
            </div>
        </div>
    </div>
    ';
    $pdf->WriteHTML($html);


    $pdf_filename = '/home/globanmq/eventsites.iamai.in/InterestForm/Iamai-Member/membership-form/iamai_' . sprintf('%06d', $membership_id) . '.pdf';

    $pdf->Output($pdf_filename, 'F');
    return $pdf_filename;
}

?>