<?php
/**
 * TDL.com.my enquiry handler — SMTP via PHPMailer. PHP 7.x/8.x.
 * AJAX -> JSON ; plain POST -> redirect ?sent=1/0.
 * Set $DEBUG=true temporarily to see the real SMTP error, then set back to false.
 *
 * SETUP (see README / PHP-Contact-Form-Spec):
 *  1. Create a mailbox in cPanel (e.g. info@tdl.com.my) and note its password.
 *  2. cPanel > Email Accounts > Connect Devices gives the exact host/port.
 *  3. Fill in the CONFIG block below. Password MUST be in SINGLE quotes.
 *  4. Upload PHPMailer/src/*.php beside this file (run get-phpmailer.sh or download manually).
 */

// ===================== CONFIG =====================
$DEBUG = false;                                // true = show SMTP error/log (then set back to false)

$SMTP_HOST   = 'mail.tdl.com.my';              // from cPanel > Email Accounts > Connect Devices
$SMTP_PORT   = 465;                            // 465 = SSL ; 587 = TLS
$SMTP_SECURE = 'ssl';                          // 'ssl' for 465, 'tls' for 587
$SMTP_USER   = 'info@tdl.com.my';              // the mailbox you created
$SMTP_PASS   = 'YOUR_MAILBOX_PASSWORD';        // *** SINGLE QUOTES *** (a $ in the password is safe)

$FROM_EMAIL  = 'info@tdl.com.my';              // must be on your own domain (deliverability)
$FROM_NAME   = 'TDL.com.my Website';
$TO_LIST     = array(
    'info@tdl.com.my',                         // add more recipients here if needed
);
$SUBJECT     = 'New enquiry - TDL.com.my';
$REDIRECT    = 'contact-us.html';              // no-JS fallback target
// ==================================================

require __DIR__ . '/PHPMailer/src/Exception.php';
require __DIR__ . '/PHPMailer/src/PHPMailer.php';
require __DIR__ . '/PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function pget($k){ return isset($_POST[$k]) ? $_POST[$k] : ''; }

$is_ajax = false;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])==='xmlhttprequest') $is_ajax=true;
elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'],'application/json')!==false) $is_ajax=true;

function respond($ok,$msg,$is_ajax,$redirect){
  if ($is_ajax){ header('Content-Type: application/json; charset=UTF-8'); echo json_encode(array('success'=>$ok,'message'=>$msg)); }
  else { header('Location: '.$redirect.'?sent='.($ok?'1':'0')); }
  exit;
}

if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD']!=='POST'){ http_response_code(405); respond(false,'Method not allowed.',$is_ajax,$REDIRECT); }
if (pget('botcheck')!==''){ respond(true,'',$is_ajax,$REDIRECT); } // honeypot

function clean_line($v){ if(!is_string($v))$v=''; $v=strip_tags(trim($v)); return str_replace(array("\r","\n","%0a","%0d","%0A","%0D"),' ',$v); }
function clean_block($v){ if(!is_string($v))$v=''; return trim(strip_tags($v)); }

$name    = clean_line(pget('name'));
$phone   = clean_line(pget('phone'));
$email   = trim(pget('email'));
$topic   = clean_line(pget('topic'));
$message = clean_block(pget('message'));

if ($name==='' || $email==='' || !filter_var($email, FILTER_VALIDATE_EMAIL)){ http_response_code(422); respond(false,'Please provide a valid name and email.',$is_ajax,$REDIRECT); }
$email = str_replace(array("\r","\n"),'',$email);

$body  = "New enquiry from the TDL.com.my website:\n\n";
$body .= 'Name:    '.$name."\n";
$body .= 'Phone:   '.$phone."\n";
$body .= 'Email:   '.$email."\n";
$body .= 'Topic:   '.$topic."\n";
$body .= "Message:\n".$message."\n";

$mail = new PHPMailer(true);
$debug_log = '';
if ($DEBUG){ $mail->SMTPDebug = 2; $mail->Debugoutput = function($s,$l) use (&$debug_log){ $debug_log .= $s.' | '; }; }

try {
  $mail->isSMTP();
  $mail->Host       = $SMTP_HOST;
  $mail->SMTPAuth   = true;
  $mail->Username   = $SMTP_USER;
  $mail->Password   = $SMTP_PASS;
  $mail->SMTPSecure = $SMTP_SECURE;   // 'ssl' or 'tls'
  $mail->Port       = $SMTP_PORT;
  $mail->CharSet    = 'UTF-8';
  $mail->setFrom($FROM_EMAIL, $FROM_NAME);
  foreach ($TO_LIST as $to){ $mail->addAddress($to); }
  if (filter_var($email, FILTER_VALIDATE_EMAIL)){ $mail->addReplyTo($email, ($name!==''?$name:'Website Enquiry')); }
  $mail->Subject = $SUBJECT;
  $mail->Body    = $body;
  $mail->send();
  respond(true,'Thank you! Your enquiry has been sent.',$is_ajax,$REDIRECT);
} catch (Exception $e) {
  http_response_code(500);
  if ($DEBUG) respond(false,'DEBUG: '.$mail->ErrorInfo.' || LOG: '.$debug_log,$is_ajax,$REDIRECT);
  respond(false,'Mail could not be sent. Please email info@tdl.com.my.',$is_ajax,$REDIRECT);
}
