<?php
// service-request.php — submits to servicedesk@ibs.com.na via authenticated SMTP.
require_once '/home/swkibs/etc/mail-config.php';

// Compatibility aliases for Forge-deployed handlers using the old MAIL_* names.
if (!defined('MAIL_SMTP_HOST') && defined('IBS_SMTP_HOST')) {
    define('MAIL_SMTP_HOST', IBS_SMTP_HOST);
    define('MAIL_SMTP_PORT', IBS_SMTP_PORT);
    define('MAIL_SMTP_USER', IBS_SMTP_USER);
    define('MAIL_SMTP_PASS', IBS_SMTP_PASS);
}
require_once __DIR__ . '/form-reference.php';
require_once __DIR__ . '/PHPMailer/src/Exception.php';
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';

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

function e($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function enforceRateLimit($formName, $maxRequests = 5, $windowSeconds = 600) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $ipHash = hash('sha256', $ip);
    $dir = __DIR__ . '/rate-limit';

    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }

    $file = $dir . '/' . $formName . '-' . $ipHash . '.json';
    $now = time();
    $attempts = [];

    if (is_file($file)) {
        $attempts = json_decode(file_get_contents($file), true);

        if (!is_array($attempts)) {
            $attempts = [];
        }
    }

    $attempts = array_filter($attempts, function ($timestamp) use ($now, $windowSeconds) {
        return ($now - (int)$timestamp) < $windowSeconds;
    });

    if (count($attempts) >= $maxRequests) {
        http_response_code(429);
        exit('Too many submissions. Please wait a few minutes and try again.');
    }

    $attempts[] = $now;

    file_put_contents($file, json_encode(array_values($attempts)), LOCK_EX);
}

function verifyTurnstile($token) {
    if ($token === '') {
        return false;
    }

    $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'secret' => TURNSTILE_SECRET_KEY,
            'response' => $token,
            'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);

    $response = curl_exec($ch);

    if ($response === false) {
        curl_close($ch);
        return false;
    }

    curl_close($ch);

    $result = json_decode($response, true);

    return !empty($result['success']);
}

$website = trim($_POST['website'] ?? '');

if ($website !== '') {
    http_response_code(204);
    exit;
}

$turnstileToken = trim($_POST['cf-turnstile-response'] ?? '');

if (!verifyTurnstile($turnstileToken)) {
    http_response_code(400);
    exit('Verification failed. Please go back and try again.');
}

enforceRateLimit('service-request');

$name          		= trim($_POST['name'] ?? '');
$company       		= trim($_POST['company'] ?? '');
$contact       		= trim($_POST['contact'] ?? '');
$email         		= trim($_POST['email'] ?? '');
$model_number  		= trim($_POST['model_number'] ?? '');
$serial_number 		= trim($_POST['serial_number'] ?? '');
$problem_type  		= trim($_POST['problem_type'] ?? '');
$problem_other 		= trim($_POST['problem_other'] ?? '');
$chatbot_summary    = trim($_POST['chatbot_summary'] ?? '');
$chatbot_transcript = trim($_POST['chatbot_transcript'] ?? '');

if (in_array($problem_type, ['Other', 'Error Code'], true) && $problem_other === '') {
    http_response_code(400);
    exit('Please provide a description for Other or Error Code.');
}

if ($problem_other !== '') {
    $problem_type .= ' - ' . $problem_other;
}

$chatbot_summary = substr($chatbot_summary, 0, 2000);
$chatbot_transcript = substr($chatbot_transcript, 0, 4000);

$reference     = getNextReference('SR');

$mail = new PHPMailer(true);
$ok = false;
$err = '';

try {
    $mail->isSMTP();
    $mail->Host       = MAIL_SMTP_HOST;
    $mail->Port       = MAIL_SMTP_PORT;
    $mail->SMTPAuth   = true;
    $mail->Username   = MAIL_SMTP_USER;
    $mail->Password   = MAIL_SMTP_PASS;
    $mail->SMTPSecure = defined('IBS_SMTP_SECURE') ? IBS_SMTP_SECURE : PHPMailer::ENCRYPTION_STARTTLS;

    $mail->setFrom(MAIL_SMTP_USER, 'IBS Website Forms');
    $mail->addAddress('servicedesk@ibs.com.na');

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $mail->addReplyTo($email, $name);
    }

    $mail->Subject = "New website service request - $reference";
    $mail->isHTML(true);

    $mail->Body = '
<!doctype html>
<html>
<body style="margin:0;padding:0;background:#f4f6f8;font-family:Arial,sans-serif;color:#1f2933;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f8;padding:24px 0;">
    <tr>
      <td align="center">
        <table width="620" cellpadding="0" cellspacing="0" style="background:#ffffff;border:1px solid #d9e2ec;border-radius:8px;overflow:hidden;">
          <tr>
            <td style="padding:0;background:#000000;">
              <img src="https://www.ibs.com.na/images/emailhead.png"
                   alt="Independent Business Systems"
                   width="620"
                   style="display:block;width:100%;max-width:620px;height:auto;border:0;">
            </td>
          </tr>
          <tr>
            <td style="background:#0f4c81;color:#ffffff;padding:18px 24px;">
              <h2 style="margin:0;font-size:22px;">You received a new Service Request</h2>
              <p style="margin:6px 0 0;font-size:14px;">Submitted via the IBS website Service Request Page</p>
            </td>
          </tr>
          <tr>
            <td style="padding:24px;">
              <p style="margin:0 0 16px;font-size:15px;">
                A new service request has been submitted. The reference number is:
              </p>

              <p style="margin:0 0 22px;">
                <span style="display:inline-block;background:#e6f0f8;color:#0f4c81;padding:8px 12px;border-radius:4px;font-weight:bold;font-size:16px;">
                  ' . e($reference) . '
                </span>
              </p>

              <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-size:14px;">
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;width:210px;">Name</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($name) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Company</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($company) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Contact</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($contact) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Email</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($email) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Model Number</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($model_number) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Serial Number</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($serial_number) . '</td></tr>
                <tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Nature of Problem</td><td style="padding:10px;border-bottom:1px solid #edf2f7;">' . e($problem_type) . '</td></tr>
				<tr><td style="padding:10px;border-bottom:1px solid #edf2f7;font-weight:bold;">Digital Assistant Summary</td><td style="padding:10px;border-bottom:1px solid #edf2f7;white-space:pre-line;">' . e($chatbot_summary) . '</td></tr>
				<tr><td style="padding:10px;font-weight:bold;">Digital Assistant Transcript</td><td style="padding:10px;white-space:pre-line;">' . e($chatbot_transcript) . '</td></tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="padding:0;background:#000000;">
              <img src="https://www.ibs.com.na/images/email-footer.png"
                   alt="IBS contact details and Kyocera authorized partner"
                   width="620"
                   style="display:block;width:100%;max-width:620px;height:auto;border:0;">
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>';

    $mail->AltBody = "New Service Request Received VIA Webform\n\n"
        . "Reference Number: $reference\n"
        . "Name: $name\n"
        . "Company: $company\n"
        . "Contact: $contact\n"
        . "Email: $email\n"
        . "Model Number: $model_number\n"
		. "Serial Number: $serial_number\n"
		. "Nature of Problem: $problem_type\n"
		. "Digital Assistant Summary:\n$chatbot_summary\n\n"
		. "Digital Assistant Transcript:\n$chatbot_transcript\n";

    $mail->send();

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $reply = new PHPMailer(true);
        $reply->isSMTP();
        $reply->Host       = MAIL_SMTP_HOST;
        $reply->Port       = MAIL_SMTP_PORT;
        $reply->SMTPAuth   = true;
        $reply->Username   = MAIL_SMTP_USER;
        $reply->Password   = MAIL_SMTP_PASS;
        $reply->SMTPSecure = defined('IBS_SMTP_SECURE') ? IBS_SMTP_SECURE : PHPMailer::ENCRYPTION_STARTTLS;

        $reply->setFrom(MAIL_SMTP_USER, 'IBS Service Desk');
        $reply->addAddress($email, $name);

        $reply->Subject = "IBS service request received - $reference";
        $reply->isHTML(true);

        $reply->Body = '
<!doctype html>
<html>
<body style="margin:0;padding:0;background:#f4f6f8;font-family:Arial,sans-serif;color:#1f2933;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f8;padding:24px 0;">
    <tr>
      <td align="center">
        <table width="620" cellpadding="0" cellspacing="0" style="background:#ffffff;border:1px solid #d9e2ec;border-radius:8px;overflow:hidden;">
          <tr>
            <td style="padding:0;background:#000000;">
              <img src="https://www.ibs.com.na/images/emailhead.png"
                   alt="Independent Business Systems"
                   width="620"
                   style="display:block;width:100%;max-width:620px;height:auto;border:0;">
            </td>
          </tr>
          <tr>
            <td style="background:#0f4c81;color:#ffffff;padding:18px 24px;">
              <h2 style="margin:0;font-size:22px;">Your service request has been received</h2>
              <p style="margin:6px 0 0;font-size:14px;">Thank you for contacting IBS</p>
            </td>
          </tr>
          <tr>
            <td style="padding:24px;font-size:15px;line-height:1.55;">
              <p style="margin:0 0 14px;">Dear ' . e($name) . ',</p>

              <p style="margin:0 0 14px;">
                Thank you for submitting a service request to IBS. Our service desk has received your request and will attend to it as soon as possible.
              </p>

              <p style="margin:20px 0;">
                <span style="display:inline-block;background:#e6f0f8;color:#0f4c81;padding:10px 14px;border-radius:4px;font-weight:bold;">
                  Reference Number: ' . e($reference) . '
                </span>
              </p>

              <p style="margin:0 0 18px;">
                Please keep this reference number for any follow-up queries.
              </p>

              <p style="margin:0;">
                Kind regards,<br>
                <strong>IBS Service Desk</strong>
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding:0;background:#000000;">
              <img src="https://www.ibs.com.na/images/email-footer.png"
                   alt="IBS contact details and Kyocera authorized partner"
                   width="620"
                   style="display:block;width:100%;max-width:620px;height:auto;border:0;">
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>';

        $reply->AltBody = "Dear $name,\n\n"
            . "Thank you for submitting a service request to IBS.\n\n"
            . "Your reference number is: $reference\n\n"
            . "Our service desk has received your request and will attend to it as soon as possible.\n\n"
            . "Kind regards,\n"
            . "IBS Service Desk";

        $reply->send();
    }

    $ok = true;
} catch (Exception $e) {
    $err = $mail->ErrorInfo;
    error_log("service-request PHPMailer error: $err");
}

file_put_contents(
    __DIR__ . '/service-request.log',
    date("Y-m-d H:i:s") . " | $reference | $name | $company | $email | $model_number | $serial_number | $problem_type | chatbot=" . str_replace(["\r", "\n", "|"], [' ', ' ', '/'], $chatbot_summary) . " | mail=" . ($ok ? "OK" : "FAIL: $err") . "\n",
    FILE_APPEND
);

header("Location: /thank-you");
exit;
