<?php
// =====================================================
// Clean Partner Solutions — Contact Message Handler
// =====================================================

$ADMIN_EMAIL = 'fahimicircles@gmail.com, info@cleanpartnersolutions.com, liberationlinksolution@gmail.com';
$FROM_EMAIL  = 'info@cleanpartnersolutions.com';
$FROM_NAME   = 'Clean Partner Solutions Website';
$BRAND_PHONE = '0430 655 053';
$BRAND_ADDR  = '13/3 Heath St, East Brisbane, QLD 4169';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

function sanitize_input($data) {
    $data = trim((string)$data);
    $data = stripslashes($data);
    return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
function fail($msg, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'message' => $msg]);
    exit;
}

// Accept JSON or form-encoded
$ctype = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($ctype, 'application/json') !== false) {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true) ?: [];
} else {
    $data = $_POST;
}

// Honeypot
if (!empty($data['website'])) {
    echo json_encode(['success' => true, 'message' => 'Thanks!']);
    exit;
}

$rawEmail = $data['email'] ?? '';
$name     = sanitize_input($data['name'] ?? '');
$email    = sanitize_input($rawEmail);
$message  = sanitize_input($data['message'] ?? '');

if ($name === '')    fail('Name is required.');
if (!filter_var($rawEmail, FILTER_VALIDATE_EMAIL)) fail('A valid email is required.');
if ($message === '') fail('Message is required.');

if (strlen($name) > 100)     fail('Name too long.');
if (strlen($email) > 255)    fail('Email too long.');
if (strlen($message) > 2000) fail('Message too long.');

$subject = "New website message — $name";

$html = '
<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;background:#f4f6f8;color:#1a1a1a;">
  <table width="100%" cellpadding="0" cellspacing="0" style="padding:24px 0;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.06);">
        <tr><td style="background:linear-gradient(135deg,#1e6dd8,#3b8aef);padding:28px 32px;color:#ffffff;">
          <h1 style="margin:0;font-size:22px;">Clean Partner Solutions</h1>
          <p style="margin:6px 0 0;font-size:14px;opacity:0.9;">New contact message</p>
        </td></tr>
        <tr><td style="padding:28px 32px;">
          <table width="100%" cellpadding="6" cellspacing="0" style="font-size:14px;">
            <tr><td style="width:120px;color:#666;">Name</td><td><strong>'.$name.'</strong></td></tr>
            <tr><td style="color:#666;">Email</td><td><a href="mailto:'.$email.'" style="color:#1e6dd8;">'.$email.'</a></td></tr>
          </table>
          <h2 style="margin:24px 0 12px;font-size:16px;color:#1e6dd8;">Message</h2>
          <div style="background:#f4f6f8;border-radius:8px;padding:14px 16px;font-size:14px;line-height:1.6;white-space:pre-wrap;">'.$message.'</div>
          <p style="margin:28px 0 0;font-size:13px;color:#666;">Reply directly to this email to respond.</p>
        </td></tr>
        <tr><td style="background:#f4f6f8;padding:18px 32px;font-size:12px;color:#666;text-align:center;">
          '.$BRAND_PHONE.' &middot; '.$ADMIN_EMAIL.'<br/>'.$BRAND_ADDR.'
        </td></tr>
      </table>
    </td></tr>
  </table>
</body></html>';

$plain = "New website message\n\nName: $name\nEmail: $email\n\nMessage:\n$message\n";

$altBoundary = '----=_ALT_'.bin2hex(random_bytes(8));
$headers  = "From: $FROM_NAME <$FROM_EMAIL>\r\n";
$headers .= "Reply-To: $name <$rawEmail>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=\"$altBoundary\"\r\n";

$body  = "--$altBoundary\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n$plain\r\n";
$body .= "--$altBoundary\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n$html\r\n";
$body .= "--$altBoundary--";

$ok = @mail($ADMIN_EMAIL, $subject, $body, $headers, "-f$FROM_EMAIL");
if (!$ok) fail('Could not send message. Please try again or email us directly.', 500);

echo json_encode(['success' => true, 'message' => "Thanks $name — we received your message and will reply soon."]);
