<?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_renew.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']) : '';

$poc1 = [
    'name' => $_POST['poc1_name'] ?? '',
    'designation' => $_POST['poc1_designation'] ?? '',
    'email' => $_POST['poc1_email'] ?? '',
    'website' => $_POST['poc1_website'] ?? '',
    'mobile' => $_POST['poc1_mobile'] ?? '',
    'phone' => $_POST['poc1_phone'] ?? '',
];

$poc2 = [
    'name' => $_POST['poc2_name'] ?? '',
    'designation' => $_POST['poc2_designation'] ?? '',
    'email' => $_POST['poc2_email'] ?? '',
    'website' => $_POST['poc2_website'] ?? '',
    'mobile' => $_POST['poc2_mobile'] ?? '',
    'phone' => $_POST['poc2_phone'] ?? '',
];

$signature_path = '';
// Handle signature upload

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

    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-renew` (organisation, address, industry, gst, committees, signature) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $organisation, $address, $industry, $gst, $committees, $signature_path);
         print_r('test');
if ($stmt->execute()) {
    $membership_id = $stmt->insert_id;

    $stmt_poc1 = $conn->prepare("INSERT INTO poc (membership_id, name, designation, email, website, mobile, phone) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt_poc1->bind_param("issssss", $membership_id, $poc1['name'], $poc1['designation'], $poc1['email'], $poc1['website'], $poc1['mobile'], $poc1['phone']);
    
    
    if ($stmt_poc1->execute()) {
         $stmt_poc2 = $conn->prepare("INSERT INTO poc (membership_id, name, designation, email, website, mobile, phone) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt_poc2->bind_param("issssss", $membership_id, $poc2['name'], $poc2['designation'], $poc2['email'], $poc2['website'], $poc2['mobile'], $poc2['phone']);
    
        if ($stmt_poc2->execute()) {
            try {
       

                $pdf_filename = generatePDF($membership_id, $organisation, $address, $industry, $gst, $committees, $poc1["name"], $poc1["designation"], $poc1["email"], $poc1["website"], $poc1["mobile"], $poc1["phone"], $poc2["name"], $poc2["designation"], $poc2["email"],$poc2["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('sandeepiamai377@gmail.com');

                $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_poc2->error;
        }
    } else {
        echo "Error: " . $stmt_poc1->error;
    }
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
function generatePDF($membership_id, $organisation, $address, $industry, $gst, $committees, $poc1_name, $poc1_designation, $poc1_email, $poc1_website, $poc1_mobile, $poc1_phone, $poc2_name, $poc2_designation, $poc2_email, $poc2_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">poc 1</h2>
            <table>
                <tr>
                    <th>Name</th>
                    <td>' . $poc1_name . '</td>
                    <th>Designation</th>
                    <td>' . $poc1_designation . '</td>
                </tr>
                <tr>
                    <th>Email</th>
                    <td>' . $poc1_email . '</td>
                    <th>Website</th>
                    <td>' . $poc1_website . '</td>
                </tr>
                <tr>
                    <th>Mobile</th>
                    <td>' . $poc1_mobile . '</td>
                    <th>Phone</th>
                    <td>' . $poc1_phone . '</td>
                </tr>
            </table>
        </div>

        <div class="section">
            <h2 class="section-title">poc 2</h2>
            <table>
                <tr>
                    <th>Name</th>
                    <td>' . $poc2_name . '</td>
                    <th>Designation</th>
                    <td>' . $poc2_designation . '</td>
                </tr>
                <tr>
                    <th>Email</th>
                    <td>' . $poc2_email . '</td>
                   <th>Mobile</th>
                    <td>' . $poc2_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/renew/' . $signature_path . '" alt="Signature">
            </div>
        </div>
    </div>
    ';
    $pdf->WriteHTML($html);


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

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

?>