<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'includes/PHPMailer/src/Exception.php';
require 'includes/PHPMailer/src/PHPMailer.php';
require 'includes/PHPMailer/src/SMTP.php';

// Server Side Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Common Data
    $name = htmlspecialchars(strip_tags(trim($_POST['agent_name'] ?? $_POST['client_name'] ?? '')));
    $phone = htmlspecialchars(strip_tags(trim($_POST['agent_mobile'] ?? $_POST['client_mobile'] ?? '')));
    $email = filter_var($_POST['agent_email'] ?? $_POST['client_email'] ?? '', FILTER_SANITIZE_EMAIL);
    $state = htmlspecialchars(strip_tags(trim($_POST['agent_state'] ?? $_POST['client_state'] ?? '')));
    $file = $_FILES['agent_id'] ?? $_FILES['client_id'] ?? null;

    // Validation - Required Fields
    if (empty($name) || empty($phone) || empty($email) || empty($state) || !$file) {
        exit("error: All fields are required!");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        exit("error: Invalid email format!");
    }

    // File Upload Validation
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if (!in_array($file['type'], $allowedTypes)) {
        exit("error: Only JPG, PNG, and PDF files are allowed!");
    }

    // Save File to Server
    $uploadDir = 'uploads/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    $filePath = $uploadDir . basename($file['name']);
    move_uploaded_file($file['tmp_name'], $filePath);

    // Determine Form Type
    $formType = isset($_POST['agent_name']) ? "Agent Registration" : "Client Registration";

    // Email Content
    $emailBody = "
    <html>
    <head>
        <title>New $formType Submission</title>
        <style>
            body { font-family: Arial, sans-serif; }
            .container { width: 100%; padding: 20px; background-color: #f4f4f4; }
            .email-box { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0px 3px 10px rgba(0,0,0,0.1); }
            table { width: 100%; border-collapse: collapse; }
            th, td { text-align: left; padding: 10px; border-bottom: 1px solid #ddd; }
            th { background-color: #004e8b; color: white; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='email-box'>
                <h2 style='color:#004e8b;'>New $formType Submission</h2>
                <table>
                    <tr><th>Name</th><td>$name</td></tr>
                    <tr><th>Phone</th><td>$phone</td></tr>
                    <tr><th>Email</th><td>$email</td></tr>
                    <tr><th>State</th><td>$state</td></tr>
                </table>
            </div>
        </div>
    </body>
    </html>";

    // PHPMailer Setup
    $mail = new PHPMailer(true);

     try {
        // SMTP Configuration for cPanel Email
        $mail->isSMTP();
        $mail->Host = 'mail.asadenterprises.in'; 
        $mail->SMTPAuth = true;
        $mail->Username = 'team@asadenterprises.in'; // ✅ Hidden Email
        $mail->Password = 'Team@12345678@'; // ❌ NEVER Share Password Publicly
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->Timeout = 10;


        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        // Email Headers
        $mail->setFrom('team@asadenterprises.in', 'Asad Enterprises');
        $mail->addAddress("info@asadenterprises.in");
        $mail->addReplyTo($email, $name);

        // File Attachment
        $mail->addAttachment($filePath);

        // HTML Email
        $mail->isHTML(true);
        $mail->Subject = "New $formType Submission";
        $mail->Body = $emailBody;

        // Send Email & Redirect
        if ($mail->send()) {
            header("Location: index.php?success=1");
            exit();
        } else {
            exit("error: " . $mail->ErrorInfo);
        }

    } catch (Exception $e) {
        exit("error: " . $mail->ErrorInfo);
    }
} else {
    exit("error: Invalid Request!");
}
?>
