<?php
// echo 6; die;
session_start();

// echo 5; die;

require 'contactfunctions2021.php';
date_default_timezone_set('America/New_York');
$date = date("F j, Y, g:i a");

$failed_submit_url = '../contact.php';
if ( !empty($_POST['honeypot']) ) {
    header("location: {$failed_submit_url}?error=Sorry, something went wrong");
    exit();
}
// echo 0; die;
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($_POST['honeypot'])) {
    // echo 1; die;

    $message = $_POST['additional-details'];

    $name_pattern = "/^[a-zA-Z-' ]+$/";

    // Check if first name is valid
    if (!preg_match($name_pattern, $_POST['first-name'])) {
        // die('Invalid first name format.');
        header("location: {$failed_submit_url}?error=Invalid first name format");
        exit();
    }

    // Check if last name is valid
    if (!preg_match($name_pattern, $_POST['last-name'])) {
        // die('Invalid last name format.');
        header("location: {$failed_submit_url}?error=Invalid last name format");
        exit();
    }

    // if (preg_match('/^(\d)(?:\1{9}|-(?:\1{3}-){2}\1{4})$/', $_POST['cell-phone'])) {
    //     // All digits are the same; show an error message or handle the error.
    //     header("location: {$failed_submit_url}?error=Invalid phone number format");
    //     exit();
    // }
    $phoneNumber = $_POST['cell-phone'];
    $phoneNumber = str_replace('-', '', $phoneNumber); // Remove hyphens
    $firstDigit = $phoneNumber[0];
    
    if (preg_match('/^[0-9]*$/', $phoneNumber) && !preg_match('/^' . $firstDigit . '+$/', $phoneNumber)) {
        // Phone number is valid and does not consist of all the same digits; continue with your logic.
        // echo 'correct';
    } else {
        // All digits are the same; show an error message or handle the error.
        header("location: {$failed_submit_url}?error=Invalid phone number format");
        exit();
    }
    
    if (!preg_match('/^(?!0)(\d{10}|\d{3}-\d{3}-\d{4})$/', $_POST['cell-phone'])) {
    // if (!preg_match('/^(\d{10}|\d{3}-\d{3}-\d{4})$/', $_POST['cell-phone'])) {
        // die('Invalid phone number format.');
        header("location: {$failed_submit_url}?error=Invalid phone number format");
        exit();
    }
    // else{
    //     echo $_POST['cell-phone'];
    // }

    // Validate e-mail
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // die('Invalid email format.');
        header("location: {$failed_submit_url}?error=Invalid email format");
        exit();
    }

    if( !empty($message) ){
// echo 1; 
// die;
        // Check for URL patterns
        if (preg_match('/(http|https|ftp|ftps)\:\/\/|(www\.)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/', $message)) {
            // die('Submission rejected: URL detected');
            header("location: {$failed_submit_url}?error=Submission rejected: URL detected");
            exit();
        }
        // Define the special characters you want to check for
        $specialChars = "/[#\^£$%&*()}{@#~?><>,|=+¬-]/";
        if (preg_match($specialChars, $message)) {
            // die('Submission rejected: Special characters detected in the message.');
            header("location: {$failed_submit_url}?error=Special characters detected in the message");
            exit();
        }
    }
    // echo 2; die; 

    // $to = 'ewa@webmastersdesktop.com'; // Replace with your email address
    $recipients = [
        // "marketing@raptormedia.co",
        "remik@webmastersdesktop.com",
        "martin@mqcmi.com",
        "marcel@mqcmi.com"
    ];
    $to = implode(',', $recipients);
    // $to = 'test@test.com'; // Replace with your email address
    $subject = 'New Quote Request';

    // Collect form data
    $firstName = $_POST['first-name'];
    $lastName = $_POST['last-name'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $zip = $_POST['zip'];
    $cellPhone = $_POST['cell-phone'];
    $homeowner = $_POST['homeowner'];
    $repairNeeds = isset($_POST['repair-needs']) ? implode(', ', $_POST['repair-needs']) : 'None';
    $panelsReplaced = $_POST['panels-replaced'];
    $additionalDetails = $_POST['additional-details'];

    // Construct email body
    $message = "First Name: $firstName\n";
    $message .= "Last Name: $lastName\n";
    $message .= "Address: $address\n";
    $message .= "City: $city\n";
    $message .= "ZIP: $zip\n";
    $message .= "Email: $email\n";
    $message .= "Cell Phone: $cellPhone\n";
    $message .= "Is Homeowner?: $homeowner\n";
    $message .= "Repair Needs: $repairNeeds\n";
    $message .= "Panels Replaced: $panelsReplaced\n";
    $message .= "Additional Details: $additionalDetails";

    // Send the email
    $headers = 'From: webmaster@example.com' . "\r\n";  // Replace with your "from" email address
    $headers .= 'MIME-Version: 1.0' . "\r\n";

    if (mail($to, $subject, $message, $headers)) {
        $url =  '../contact.php?success=1';
          header("location: $url");
        exit();
        // echo 'Email sent successfully!';
    } else {
        $url =  '../contact.php?error=Sorry, something went wrong';
        header("location: $url");
        exit();

        // echo 'Failed to send email.';
    }
}
?>
