<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

require __DIR__ . '/../PHPMailer-master/src/PHPMailer.php';
require __DIR__ . '/../PHPMailer-master/src/SMTP.php';
require __DIR__ . '/../PHPMailer-master/src/Exception.php';

if ($_SERVER["REQUEST_METHOD"] !== "POST") exit("Invalid request");

// Get POST data
$full_name = trim($_POST['full_name'] ?? '');
$email     = trim($_POST['email'] ?? '');
$phone     = trim($_POST['phone'] ?? '');
$message   = trim($_POST['message'] ?? '');

// Validation
if (!$full_name || !$email || !$phone || !$message) exit("All fields are required");
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) exit("Invalid email format");
if (!preg_match('/^[0-9]{10,15}$/', $phone)) exit("Phone must be 10 to 15 digits");

// Email template
function emailTemplate($title, $content) {
    return "
    <div style='font-family:Arial;max-width:600px;margin:auto;border:1px solid #ddd'>
        <div style='background:#efefef;padding:15px;text-align:center'>
            <img src='https://mbihosting.in/KJSH/landing-page/cardiology/img/logo/kj-somaiya-logo.png' style='max-width:180px;'>
        </div>
        <div style='padding:20px'>
            <h3>{$title}</h3>
            {$content}
        </div>
        <div style='background:#f2f2f2;padding:10px;text-align:center;font-size:12px'>
            © " . date('Y') . " K J Somaiya
        </div>
    </div>";
}

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'mbitestmail2@gmail.com';
    $mail->Password   = 'moyeyehnxzzbtoob';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('mbitestmail2@gmail.com', 'K J Somaiya');
    $mail->isHTML(true);
    $mail->CharSet = "UTF-8";

    // Send to Admin
    $mail->addAddress('smrita@matrixbricks.com');
    $mail->addCC('shweta@matrixbricks.com');

    $adminBody = "
        <p><b>Name:</b> {$full_name}</p>
        <p><b>Email:</b> {$email}</p>
        <p><b>Phone:</b> {$phone}</p>
        <p><b>Message:</b> {$message}</p>
    ";
$department = "Cardiology";
$mail->Subject = "New Enquiry Form - " . $department;
$mail->Body = emailTemplate("New Enquiry Received", $adminBody);
    $mail->send();

    // Send to User
    $mail->clearAddresses();
    $mail->addAddress($email);
    $mail->Subject = "Thank you for contacting K J Somaiya";

    $userBody = "
        <p>Hello <b>{$full_name}</b>,</p>
        <p>Thank you for contacting us. We will get back to you shortly.</p>
        <br>
        <p>Regards,<br><b>K J Somaiya Team</b></p>
    ";
    $mail->Body = emailTemplate("Thank You", $userBody);
    $mail->send();

    // Redirect after submit
    header("Location: thank-you.html");
    exit;

} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}
?>