<?php
header('Content-Type: application/json');

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

require __DIR__ . '/phpmailer/src/Exception.php';
require __DIR__ . '/phpmailer/src/PHPMailer.php';
require __DIR__ . '/phpmailer/src/SMTP.php';

include 'includes/db.php';

/* fetch enquiry email */
$settings = mysqli_fetch_assoc(
    mysqli_query($conn,"SELECT enquiry_email FROM site_settings ORDER BY id DESC LIMIT 1")
);

$name    = $_POST['name'] ?? '';
$email   = $_POST['email'] ?? '';
$phone   = $_POST['phone'] ?? '';
$subject = $_POST['subject'] ?? '';
$message = $_POST['message'] ?? '';

if($name=='' || $email=='' || $subject=='' || $message==''){
    echo json_encode(["status"=>"error","message"=>"Fill all fields"]);
    exit;
}

/* insert DB */
$stmt = $conn->prepare(
  "INSERT INTO contact_messages (name,email,phone,subject,message) VALUES (?,?,?,?,?)"
);
$stmt->bind_param("sssss",$name,$email,$phone,$subject,$message);
$stmt->execute();
$stmt->close();

/* mail */
$mail = new PHPMailer(true);

$mail->isSMTP();
$mail->Host = 'smtp.zoho.com';
$mail->SMTPAuth = true;
$mail->Username = 'enquiry@ugra.in';
$mail->Password = 'Trubiz@4321';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

$mail->setFrom('enquiry@ugra.in', 'Website Contact');
$mail->addAddress($settings['enquiry_email']);
$mail->addReplyTo($email, $name);

$mail->isHTML(true);
$mail->Subject = "New Enquiry: $subject";
$mail->Body = "
<b>Name:</b> $name<br>
<b>Email:</b> $email<br>
<b>Phone:</b> $phone<br>
<b>Message:</b>$message
";

try {
    $mail->send();
    echo json_encode(["status"=>"success","message"=>"Message sent successfully"]);
} catch (Exception $e) {
    echo json_encode(["status"=>"error","message"=>$mail->ErrorInfo]);
}

$conn->close();
