<?php
session_start();

include_once("config.php");
// Utility functions
/**
 * Sanitizes a string.
 *
 * @param string $data The string to sanitize.
 * @return string The sanitized string.
 */
function sanitizeString(string $data): string
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
  
/**
 * Validates an email address.
 *
 * @param string $email The email address to validate.
 * @return bool True if the address is valid, false otherwise.
 */
function validateEmail(string $email): bool
{
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// Initialize response array


// Form processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // 1. Collect and sanitize form data
    $name = sanitizeString($_POST["name"] ?? '');
    $phone = sanitizeString($_POST["phone"] ?? '');
    $email = sanitizeString($_POST["email"] ?? '');
    $service = sanitizeString($_POST["service"] ?? '');
    $date = sanitizeString($_POST["date"] ?? '');
    $time = sanitizeString($_POST["time"] ?? '');
    $message = sanitizeString($_POST["message"] ?? '');
    $policy = isset($_POST["policy"]); // Checkbox, so we only care if it's checked
    $captcha = strtolower(($_POST["captcha"] ?? ''));
  
    // 2. Captcha validation 
    if (isset($_SESSION["captcha_hash"])) {
        $captchaValue = $_SESSION["captcha_hash"];
    } else {
        $captchaValue = null;
    }
  
    $result = validCaptcha($captcha, [], $salt);

    if (count($result)>0){
        echo json_encode($result);
        exit;
    }

    unset($_SESSION["captcha"]);
    $result = [
    'code' => 'ok',
    'errors' => []
    ];
    if (!validateEmail($email)) {
        $result['errors'][] = "Invalid email address: ".$email;
    }
//Here you can include any condition before send email, like 
//verify taht date & time are avalaible for a booking.
    
  
    // 4. If there are errors, prepare the response
    if (!empty($result['errors'])) {
        $result['code'] = 'data';
    } else {
        // 5. Construct email body
        $body = "New contact form submission:\n\n";
        $body .= "Name: " . $name . "\n";
        $body .= "Phone: " . $phone . "\n";
        $body .= "Email: " . $email . "\n";
        $body .= "Service: " . $service . "\n";
        $body .= "Date: " . $date . "\n";
        $body .= "Time: " . $time . "\n";
        $body .= "Message: " . $message . "\n";

        // 6. Email headers (IMPORTANT!)
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/plain; charset=UTF-8',
            'From: ' . $senderEmail,
            'Reply-To: ' . $email, // Use the user's email as Reply-To
            'X-Mailer: PHP/' . phpversion()
        ];

        // 7. Send the email
        if (!mail($destinationEmail, $subject, $body, implode("\r\n", $headers))) {
            $result['code'] = 'data';
            $result['errors'][] = "Error sending the form. Please try again later.";
        }
    }

    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

function validCaptcha($captcha, $result, $salt){
  global $maxAttempts;
  // Limit attempts
  if (!isset($_SESSION['captcha_attempts'])) {
      $_SESSION['captcha_attempts'] = 0;
  }
  $_SESSION['captcha_attempts']++;  

  if ($_SESSION['captcha_attempts'] > $maxAttempts) {
      $result['code'] = 'captcha';
      $result['errors'][] = "Too many failed attempts. Please try again later.";
      return $result;
  }

  // Verify Captcha exists
  if (!isset($_SESSION["captcha_hash"])) {
      $result['code'] = 'captcha';
      $result['errors'][] = "Captcha not found. Please refresh the page.";
      return $result;
  }

  
  $captcha = trim($captcha);
  $captchaHash = hash('sha256', $captcha . $salt);

  if ($_SESSION['captcha_hash'] !== $captchaHash) {
      $result['code'] = 'captcha';
      $result['errors'][] = "Incorrect captcha.";
      return $result;
  } else {
      unset($_SESSION['captcha_attempts']); // Reinit counter ii fvalid captcha
  }
  unset($_SESSION["captcha_hash"]); // Eliminate hash after validate
 return $result;
  }

?>
