<?php
// =====================================================
// Clean Partner Solutions — Booking Request Handler
// =====================================================
// Place this file in the same folder as index.html (e.g. public_html/)
// React form POSTs multipart/form-data here.

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

$MAX_FILES   = 5;
$MAX_SIZE    = 5 * 1024 * 1024; // 5MB
$ALLOWED     = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];

// ---- CORS / headers --------------------------------
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');

// Convert fatal PHP errors into JSON so the frontend never sees a blank 500
register_shutdown_function(function () {
    $e = error_get_last();
    if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        if (!headers_sent()) {
            http_response_code(500);
            header('Content-Type: application/json; charset=utf-8');
        }
        echo json_encode(['success' => false, 'message' => 'Server error: ' . $e['message']]);
    }
});
set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException($message, 0, $severity, $file, $line);
});

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;
}

// Detect upload exceeding post_max_size — PHP empties $_POST/$_FILES in this case
if (empty($_POST) && empty($_FILES) && (int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0) {
    http_response_code(413);
    echo json_encode([
        'success' => false,
        'message' => 'Files too large. Server post_max_size = ' . ini_get('post_max_size') . ', upload_max_filesize = ' . ini_get('upload_max_filesize') . '. Please use smaller files or raise these limits in php.ini / .htaccess.'
    ]);
    exit;
}

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

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

// ---- Collect & validate ----------------------------
$fullName    = field('fullName');
$email       = field('email');
$phone       = field('phone');
$company     = field('company');
$address     = field('address');
$serviceType = field('serviceType');
$contactTime = field('contactTime');
$notes       = field('notes');

if ($fullName === '')                                   fail('Full name is required.');
if ($email === '' || !filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL)) fail('A valid email is required.');
if ($phone === '')                                      fail('Phone is required.');
if ($address === '')                                    fail('Service address is required.');
if ($serviceType === '')                                fail('Service type is required.');

if (strlen($fullName) > 100)  fail('Name too long.');
if (strlen($email) > 255)     fail('Email too long.');
if (strlen($notes) > 2000)    fail('Notes too long.');

// ---- Attachments -----------------------------------
$attachments = [];
if (!empty($_FILES['attachments']) && is_array($_FILES['attachments']['name'])) {
    $f = $_FILES['attachments'];
    $count = count($f['name']);
    if ($count > $MAX_FILES) fail("Maximum $MAX_FILES files.");

    $finfo = function_exists('finfo_open') ? finfo_open(FILEINFO_MIME_TYPE) : null;

    $uploadErrors = [
        UPLOAD_ERR_INI_SIZE   => 'exceeds upload_max_filesize in php.ini',
        UPLOAD_ERR_FORM_SIZE  => 'exceeds form MAX_FILE_SIZE',
        UPLOAD_ERR_PARTIAL    => 'was only partially uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'missing temp folder on server',
        UPLOAD_ERR_CANT_WRITE => 'failed to write to disk',
        UPLOAD_ERR_EXTENSION  => 'blocked by a PHP extension',
    ];

    for ($i = 0; $i < $count; $i++) {
        $err = $f['error'][$i];
        if ($err === UPLOAD_ERR_NO_FILE) continue;
        if ($err !== UPLOAD_ERR_OK) {
            $reason = $uploadErrors[$err] ?? "upload error code $err";
            fail($f['name'][$i] . ': ' . $reason);
        }
        if ($f['size'][$i] > $MAX_SIZE) fail($f['name'][$i] . ': exceeds 5MB.');
        if (!is_uploaded_file($f['tmp_name'][$i])) fail($f['name'][$i] . ': invalid upload.');

        if ($finfo) {
            $mime = finfo_file($finfo, $f['tmp_name'][$i]);
        } elseif (function_exists('mime_content_type')) {
            $mime = mime_content_type($f['tmp_name'][$i]);
        } else {
            $mime = $f['type'][$i]; // fallback to browser-reported
        }

        if (!in_array($mime, $ALLOWED, true)) fail($f['name'][$i] . ': type "' . $mime . '" not allowed.');

        $data = @file_get_contents($f['tmp_name'][$i]);
        if ($data === false) fail($f['name'][$i] . ': could not read file.');

        $attachments[] = [
            'name' => preg_replace('/[^A-Za-z0-9._-]/', '_', $f['name'][$i]),
            'mime' => $mime,
            'data' => $data,
        ];
    }

    if ($finfo) finfo_close($finfo);
}

// ---- Service label map -----------------------------
$serviceLabels = [
    'office'     => 'Office Cleaning',
    'carpet'     => 'Carpet Cleaning',
    'medical'    => 'Medical Centre',
    'sanitation' => 'Sanitation',
];
$timeLabels = [
    'morning'   => 'Morning (8 – 11 AM)',
    'afternoon' => 'Afternoon (12 – 3 PM)',
    'evening'   => 'Evening (4 – 7 PM)',
    'anytime'   => 'Anytime',
];
$serviceLabel = $serviceLabels[$serviceType] ?? $serviceType;
$timeLabel    = $timeLabels[$contactTime] ?? ($contactTime ?: 'Anytime');

// ---- Build HTML email ------------------------------
$subject = "New booking request — $fullName ($serviceLabel)";

$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="background:#f4f6f8;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;letter-spacing:0.3px;">Clean Partner Solutions</h1>
          <p style="margin:6px 0 0;font-size:14px;opacity:0.9;">New booking request</p>
        </td></tr>
        <tr><td style="padding:28px 32px;">
          <h2 style="margin:0 0 12px;font-size:16px;color:#1e6dd8;">Customer</h2>
          <table width="100%" cellpadding="6" cellspacing="0" style="font-size:14px;border-collapse:collapse;">
            <tr><td style="width:140px;color:#666;">Name</td><td><strong>'.$fullName.'</strong></td></tr>
            <tr><td style="color:#666;">Email</td><td><a href="mailto:'.$email.'" style="color:#1e6dd8;">'.$email.'</a></td></tr>
            <tr><td style="color:#666;">Phone</td><td><a href="tel:'.$phone.'" style="color:#1e6dd8;">'.$phone.'</a></td></tr>
            '.($company ? '<tr><td style="color:#666;">Company</td><td>'.$company.'</td></tr>' : '').'
          </table>

          <h2 style="margin:24px 0 12px;font-size:16px;color:#1e6dd8;">Service</h2>
          <table width="100%" cellpadding="6" cellspacing="0" style="font-size:14px;border-collapse:collapse;">
            <tr><td style="width:140px;color:#666;">Type</td><td><strong>'.$serviceLabel.'</strong></td></tr>
            <tr><td style="color:#666;">Address</td><td>'.$address.'</td></tr>
            <tr><td style="color:#666;">Preferred time</td><td>'.$timeLabel.'</td></tr>
          </table>

          '.($notes ? '
          <h2 style="margin:24px 0 12px;font-size:16px;color:#1e6dd8;">Notes</h2>
          <div style="background:#f4f6f8;border-radius:8px;padding:14px 16px;font-size:14px;line-height:1.5;white-space:pre-wrap;">'.$notes.'</div>
          ' : '').'

          '.(count($attachments) ? '
          <h2 style="margin:24px 0 12px;font-size:16px;color:#1e6dd8;">Attachments ('.count($attachments).')</h2>
          <ul style="margin:0;padding-left:20px;font-size:14px;color:#333;">
            '.implode('', array_map(fn($a) => '<li>'.htmlspecialchars($a['name']).'</li>', $attachments)).'
          </ul>' : '').'

          <p style="margin:28px 0 0;font-size:13px;color:#666;">Reply directly to this email to respond to the customer.</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>';

// ---- Build MIME message ----------------------------
$boundary    = '----=_CPS_'.bin2hex(random_bytes(8));
$altBoundary = '----=_ALT_'.bin2hex(random_bytes(8));

$headers  = "From: $FROM_NAME <$FROM_EMAIL>\r\n";
$headers .= "Reply-To: $fullName <{$_POST['email']}>\r\n";
$headers .= "MIME-Version: 1.0\r\n";

$plain = "New booking request\n\nName: $fullName\nEmail: $email\nPhone: $phone\nCompany: $company\nService: $serviceLabel\nAddress: $address\nPreferred time: $timeLabel\n\nNotes:\n$notes\n";

if (count($attachments) === 0) {
    $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--";
} else {
    $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
    $body  = "--$boundary\r\nContent-Type: multipart/alternative; boundary=\"$altBoundary\"\r\n\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--\r\n";
    foreach ($attachments as $a) {
        $body .= "--$boundary\r\n";
        $body .= "Content-Type: {$a['mime']}; name=\"{$a['name']}\"\r\n";
        $body .= "Content-Disposition: attachment; filename=\"{$a['name']}\"\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($a['data']))."\r\n";
    }
    $body .= "--$boundary--";
}

// ---- Send ------------------------------------------
$ok = @mail($ADMIN_EMAIL, $subject, $body, $headers, "-f$FROM_EMAIL");

if (!$ok) fail('Could not send email. Please try again or contact us directly.', 500);

echo json_encode(['success' => true, 'message' => "Thanks $fullName — we received your booking request and will be in touch shortly."]);
