<?php
/**
 * DWSK - Order Now submission handler
 * ---------------------------------------------------------------
 * Accepts multipart/form-data POST from the Order Now form, validates
 * everything server-side, stores uploaded documents securely, emails
 * the operations team + an acknowledgement to the client, and returns
 * a JSON response consumed by the website's JavaScript.
 *
 * 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);
    }

    // ---- Anti-spam: honeypot -------------------------------------------------
    if (is_spam_honeypot()) {
        // Pretend success so bots don't learn the honeypot was detected.
        json_response(true, 'Thank you for your order. Your documents have been submitted successfully. We will review your request and contact you shortly.');
    }

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

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

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

    // ---- Collect + validate fields ---------------------------------------------
    $fullName     = clean_text($_POST['full_name'] ?? '', 200);
    $email        = clean_text($_POST['email'] ?? '', 200);
    $whatsapp     = clean_text($_POST['whatsapp'] ?? '', 50);
    $country      = clean_text($_POST['country'] ?? '', 100);
    $service      = clean_text($_POST['service'] ?? '', 200);
    $deadline     = clean_text($_POST['deadline'] ?? '', 50);
    $projectTitle = clean_text($_POST['project_title'] ?? '', 300);
    $instructions = clean_text($_POST['instructions'] ?? '', 5000);
    $payment      = clean_text($_POST['payment_method'] ?? '', 50);

    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.');
    }

    // ---- Files (optional for orders, but validate whatever is provided) --------
    $filesResult = collect_uploaded_files('documents');
    if (!$filesResult['ok']) {
        json_response(false, $filesResult['error']);
    }

    $storedFiles = store_uploaded_files($filesResult['files'], UPLOAD_DIR_ORDERS);

    // ---- Generate unique reference ---------------------------------------------
    $reference = generate_submission_id('ORD');

    // ---- Build admin notification email -----------------------------------------
    $fileListHtml = '';
    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>';
    } else {
        $fileListHtml = '<p><em>No documents were attached.</em></p>';
    }

    $adminBody = "
        <p><strong>Order Reference:</strong> " . e($reference) . "</p>
        <p><strong>Full Name:</strong> " . e($fullName) . "</p>
        <p><strong>Email:</strong> " . e($email) . "</p>
        <p><strong>WhatsApp:</strong> " . e($whatsapp) . "</p>
        <p><strong>Country:</strong> " . e($country) . "</p>
        <p><strong>Service Needed:</strong> " . e($service) . "</p>
        <p><strong>Deadline:</strong> " . e($deadline) . "</p>
        <p><strong>Project Title:</strong> " . e($projectTitle) . "</p>
        <p><strong>Instructions:</strong><br>" . nl2br(e($instructions)) . "</p>
        <p><strong>Preferred Payment Method:</strong> " . e($payment) . "</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 Order Request — ' . $reference, $adminBody);

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

    $adminSent = send_branded_email(
        ADMIN_EMAIL_ORDERS,
        'New Order Request - ' . $reference,
        $adminHtml,
        $attachmentsForAdmin,
        $email
    );

    // ---- Build client acknowledgement email ---------------------------------
    $clientBody = "
        <p>Thank you for choosing " . e(SITE_NAME) . ".</p>
        <p>Your order has been received successfully.</p>
        <p><strong>Order Reference:</strong> " . e($reference) . "</p>
        <p>Our team will review your requirements and contact you shortly with a quotation or the next steps.</p>
    ";
    $clientHtml = dwsk_email_template('Order Received — Thank You', $clientBody);
    $clientSent = send_branded_email($email, 'Your Order Confirmation - ' . $reference, $clientHtml);

    // ---- Log submission (flat file, no database / no SQL-injection surface) ---
    log_submission(LOG_FILE_ORDERS, [
        '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 your order. Your documents have been submitted successfully. We will review your request and contact you shortly.', [
        'reference' => $reference,
    ]);

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