<?php
/**
 * DWSK - Contact / Get a Quote submission handler
 * ---------------------------------------------------------------
 * Same pattern as submit_order.php / submit_application.php, used by
 * the Contact Us page (which also serves as the "Get Free Quote" form).
 * Added so the site keeps working end-to-end after Formspree was
 * removed — this form previously shared the Formspree endpoint too.
 *
 * PHP 8.2+ / Truehost cPanel compatible.
 */

define('DWSK_APP', true);

require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/helpers.php';
require_once __DIR__ . '/includes/mailer.php';

header('X-Content-Type-Options: nosniff');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(false, 'Invalid request method.', [], 405);
    }

    if (is_spam_honeypot()) {
        json_response(true, 'Thank you for reaching out to Dynamic Writing Services-Kenya. We have successfully received your message and any attached documents. Our team will get back to you shortly with a response or quotation.');
    }

    $ip = client_ip();
    if (!rate_limit_allow($ip)) {
        json_response(false, 'Too many submissions detected. Please wait a moment and try again.', [], 429);
    }

    $csrfToken = $_POST['csrf_token'] ?? '';
    if (!verify_csrf_token($csrfToken)) {
        json_response(false, 'Your session has expired. Please refresh the page and try again.', [], 419);
    }

    if (RECAPTCHA_ENABLED && !recaptcha_passes($_POST['recaptcha_token'] ?? null)) {
        json_response(false, 'Verification failed. Please try again.', [], 400);
    }

    $fullName = clean_text($_POST['full_name'] ?? '', 200);
    $email    = clean_text($_POST['email'] ?? '', 200);
    $phone    = clean_text($_POST['phone'] ?? '', 50);
    $country  = clean_text($_POST['country'] ?? '', 100);
    $service  = clean_text($_POST['service'] ?? '', 200);
    $message  = clean_text($_POST['message'] ?? '', 5000);

    if ($fullName === '') {
        json_response(false, 'Please enter your full name.');
    }
    if ($email === '') {
        json_response(false, 'Please enter your email address.');
    }
    if (!is_valid_email($email)) {
        json_response(false, 'Invalid email address.');
    }

    // Contact/quote attachments stored in the orders folder (reference documents,
    // not a formal order yet) — kept separate from careers CVs.
    $filesResult = collect_uploaded_files('documents');
    if (!$filesResult['ok']) {
        json_response(false, $filesResult['error']);
    }
    $storedFiles = store_uploaded_files($filesResult['files'], UPLOAD_DIR_ORDERS);

    $reference = generate_submission_id('QRY');

    $fileListHtml = '<p><em>No documents were attached.</em></p>';
    if (!empty($storedFiles)) {
        $items = array_map(fn($f) => '<li>' . e($f['original_name']) . '</li>', $storedFiles);
        $fileListHtml = '<p><strong>Attached documents:</strong></p><ul>' . implode('', $items) . '</ul>';
    }

    $adminBody = "
        <p><strong>Enquiry Reference:</strong> " . e($reference) . "</p>
        <p><strong>Full Name:</strong> " . e($fullName) . "</p>
        <p><strong>Email:</strong> " . e($email) . "</p>
        <p><strong>Phone:</strong> " . e($phone) . "</p>
        <p><strong>Country:</strong> " . e($country) . "</p>
        <p><strong>Service Needed:</strong> " . e($service) . "</p>
        <p><strong>Message:</strong><br>" . nl2br(e($message)) . "</p>
        {$fileListHtml}
        <p style='color:#64748B;font-size:12.5px;'>Submitted " . e(date('Y-m-d H:i:s')) . " from IP " . e($ip) . "</p>
    ";
    $adminHtml = dwsk_email_template('New Website Enquiry — ' . $reference, $adminBody);

    $attachmentsForAdmin = array_map(fn($f) => ['path' => $f['stored_path'], 'name' => $f['original_name']], $storedFiles);

    $adminSent = send_branded_email(
        ADMIN_EMAIL_CONTACT,
        'Website Contact / Quote Request - ' . $fullName . ' (' . $reference . ')',
        $adminHtml,
        $attachmentsForAdmin,
        $email
    );

    $clientBody = "
        <p>Thank you for reaching out to " . e(SITE_NAME) . ".</p>
        <p><strong>Reference:</strong> " . e($reference) . "</p>
        <p>We have successfully received your message and any attached documents.</p>
        <p>Our team will get back to you shortly with a response or quotation.</p>
    ";
    $clientHtml = dwsk_email_template('We\'ve Received Your Message', $clientBody);
    $clientSent = send_branded_email($email, 'We Received Your Message - ' . $reference, $clientHtml);

    log_submission(LOG_FILE_CONTACT, [
        'reference' => $reference,
        'ip'        => $ip,
        'full_name' => $fullName,
        'email'     => $email,
        'service'   => $service,
        'files'     => array_map(fn($f) => $f['stored_name'], $storedFiles),
        'admin_email_sent'  => $adminSent,
        'client_email_sent' => $clientSent,
    ]);

    json_response(true, 'Thank you for reaching out to Dynamic Writing Services-Kenya. We have successfully received your message and any attached documents. Our team will get back to you shortly with a response or quotation.', [
        'reference' => $reference,
    ]);

} catch (\Throwable $e) {
    log_error('submit_contact', $e);
    json_response(false, 'Submission failed. Please try again later.', [], 500);
}
