<?php
// Show all errors (development only)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize inputs
    $name    = htmlspecialchars(trim($_POST['name'] ?? ''));
    $email   = htmlspecialchars(trim($_POST['email'] ?? ''));
    $phone   = htmlspecialchars(trim($_POST['phone'] ?? ''));
    $subject = htmlspecialchars(trim($_POST['subject'] ?? ''));
    $message = htmlspecialchars(trim($_POST['message'] ?? ''));
    $formType = isset($_POST['form_type']) ? htmlspecialchars(trim($_POST['form_type'])) : "General";

    // ✅ Validation
    $errors = [];

    if (empty($name) || strlen($name) < 2) {
        $errors[] = "Name is required (min 2 characters).";
    }

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid email is required.";
    }

    if (empty($phone) || !preg_match('/^[0-9\-\+\s\(\)]+$/', $phone)) {
        $errors[] = "Valid phone number is required.";
    }

    if (empty($subject)) {
        $errors[] = "Subject is required.";
    }

    if (empty($message) || strlen($message) < 10) {
        $errors[] = "Message must be at least 10 characters.";
    }

    // If validation fails, return error response
    if (!empty($errors)) {
        echo json_encode([
            "status" => "error",
            "message" => "Validation failed.",
            "errors" => $errors
        ]);
        exit;
    }

    // ✅ Send Mail
    $mail = new PHPMailer(true);

    try {
        // SMTP settings
        $mail->isSMTP();
        $mail->Host       = 'mail.appdemo.space'; 
        $mail->SMTPAuth   = true;
        $mail->Username   = 'no-reply@appdemo.space'; 
        $mail->Password   = '?fT&SUVeOgH6}?T=';   
        $mail->SMTPSecure = 'tls';
        $mail->Port       = 587;

        // From & To
        $mail->setFrom('no-reply@appdemo.space', 'M Tufail');
        $mail->addAddress('clix@appdemo.space');

        // Email content
        $mail->isHTML(false);
        $mail->Subject = "[$formType] New Submission: " . $subject;
        $mail->Body    = "Form: $formType\n\nName: $name\nEmail: $email\nPhone: $phone\n\nMessage:\n$message";

        $mail->send();

        echo json_encode([
            "status" => "success",
            "message" => "Mail sent successfully!"
        ]);
    } catch (Exception $e) {
        echo json_encode([
            "status" => "error",
            "message" => "Mailer Error: " . $mail->ErrorInfo
        ]);
    }
}
