<?php

require_once __DIR__ . '/app/helpers.php';
require_once __DIR__ . '/app/analytics.php';
require_once __DIR__ . '/app/public-layout.php';

sparrow_record_analytics_event(
    'page_view',
    'page',
    null,
    'Contact',
    '',
    '/contact.php'
);

$business_name = sparrow_public_setting('business_name', 'Sparrow & Seed Creations');
$contact_email = trim(sparrow_public_setting('contact_email'));
$contact_phone = trim(sparrow_public_setting('contact_phone'));
$business_address = trim(sparrow_public_setting('business_address'));

$success = ($_GET['sent'] ?? '') === '1';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $preferred = trim($_POST['preferred_contact'] ?? 'Email');
    $honeypot = trim($_POST['website'] ?? '');
    $agreement_checked = !empty($_POST['contact_agreement']);

    $allowed_subjects = [
        'General Question',
        'Existing Order',
        'Product Question',
        'Website Issue',
        'Other',
    ];

    $allowed_contact_methods = [
        'Email',
        'Phone',
    ];

    if ($honeypot !== '') {
        /*
         * Silently accept suspected bot submissions
         * without saving them.
         */
        header('Location: ' . sparrow_url('/contact.php?sent=1'));
        exit;
    }

    if (
        $name === ''
        || $email === ''
        || $subject === ''
        || $message === ''
    ) {
        $error = 'Please complete all required fields.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } elseif (!in_array($subject, $allowed_subjects, true)) {
        $error = 'Please select a valid subject.';
    } elseif (!in_array($preferred, $allowed_contact_methods, true)) {
        $error = 'Please select a valid contact method.';
    } elseif ($preferred === 'Phone' && $phone === '') {
        $error = 'Please enter a phone number if you prefer to be contacted by phone.';
    } elseif (!$agreement_checked) {
        $error = 'Please confirm that this form is for a general question.';
    } else {
        try {
            $stmt = sparrow_db()->prepare("
                INSERT INTO contact_messages (
                    name,
                    email,
                    phone,
                    subject,
                    message,
                    preferred_contact,
                    status
                ) VALUES (
                    :name,
                    :email,
                    :phone,
                    :subject,
                    :message,
                    :preferred_contact,
                    'New'
                )
            ");

            $stmt->execute([
                ':name' => substr($name, 0, 150),
                ':email' => substr($email, 0, 190),
                ':phone' => $phone !== ''
                    ? substr($phone, 0, 50)
                    : null,
                ':subject' => substr($subject, 0, 100),
                ':message' => $message,
                ':preferred_contact' => $preferred,
            ]);

            /*
             * Redirect after saving to prevent a browser refresh
             * from submitting the message twice.
             */
            header('Location: ' . sparrow_url('/contact.php?sent=1'));
            exit;
        } catch (Throwable $e) {
            error_log('Contact message could not be saved: ' . $e->getMessage());

            $error = 'Your message could not be sent right now. Please try again shortly.';
        }
    }
}

$contact_css = <<<'CSS'

.contact-page h2,
.contact-page h3{
    color:var(--sparrow-purple-dark);
}

.contact-page-section{
    margin-top:24px;
}

.contact-card{
    background:var(--sparrow-card);
    border:1px solid var(--sparrow-border);
    border-radius:22px;
    padding:24px;
    box-shadow:0 8px 30px rgba(70,35,60,.06);
}

.contact-card p{
    color:var(--sparrow-muted);
    line-height:1.7;
}

.contact-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:18px;
}

.contact-form{
    display:grid;
    gap:18px;
    margin-top:18px;
}

.contact-form label{
    display:block;
    font-weight:600;
    color:var(--sparrow-purple-dark);
    margin-bottom:6px;
}

.contact-form input,
.contact-form select,
.contact-form textarea{

    width:100%;
    padding:12px;
    border:1px solid var(--sparrow-border);
    border-radius:12px;
    font:inherit;
    box-sizing:border-box;
}

.contact-form textarea{
    resize:vertical;
    min-height:180px;
}

.contact-radio{
    display:flex;
    gap:20px;
}

.contact-radio label{
    font-weight:normal;
}

.contact-checkbox{
    display:flex;
    gap:10px;
    align-items:flex-start;
}

.contact-checkbox input{
    width:auto;
    margin-top:4px;
}

.contact-success{
    background:#eef8ef;
    border:1px solid #9ad59f;
    color:#2d6a33;
    padding:14px;
    border-radius:12px;
}

.contact-error{
    background:#fff3f3;
    border:1px solid #e3aaaa;
    color:#a32626;
    padding:14px;
    border-radius:12px;
}

@media(max-width:800px){

    .contact-grid{
        grid-template-columns:1fr;
    }

}

.contact-honeypot {
    position:absolute;
    left:-9999px;
    width:1px;
    height:1px;
    overflow:hidden;
}

CSS;

sparrow_public_header('Contact','contact',$contact_css);

?>

<div class="contact-page">

<section class="public-card public-hero">

<h1>Contact <?php echo sparrow_escape($business_name); ?></h1>

<p>
I'd love to hear from you! Whether you have a question about a product,
an existing order, or simply want to say hello,
feel free to send me a message.
</p>

</section>

<section class="contact-page-section">

<div class="contact-card">

<h2>Looking for a Custom Order?</h2>

<p>
If you're wanting to request a custom tumbler, shirt,
or other personalized item, please use the
<a href="<?php echo sparrow_escape(sparrow_url('/order.php')); ?>"><strong>Custom Order Request</strong></a> form instead.
That form helps me gather everything needed to prepare a quote.
</p>

</div>

</section>

<?php if ($contact_email !== '' || $contact_phone !== '' || $business_address !== ''): ?>
<section class="contact-page-section">
<div class="contact-card">
<h2>Contact Information</h2>

<?php if ($contact_email !== ''): ?>
<p><strong>Email:</strong> <a href="mailto:<?php echo sparrow_escape($contact_email); ?>"><?php echo sparrow_escape($contact_email); ?></a></p>
<?php endif; ?>

<?php if ($contact_phone !== ''): ?>
<p><strong>Phone:</strong> <?php echo sparrow_escape($contact_phone); ?></p>
<?php endif; ?>

<?php if ($business_address !== ''): ?>
<p><strong>Mailing Address:</strong><br><?php echo nl2br(sparrow_escape($business_address)); ?></p>
<?php endif; ?>
</div>
</section>
<?php endif; ?>

<section class="contact-page-section">

<div class="contact-card">

<h2>Send a Message</h2>

<?php if($success): ?>

<div class="contact-success">

Thank you for your message! I'll get back with you as soon as I can.

</div>

<?php endif; ?>

<?php if($error): ?>

<div class="contact-error">

<?php echo sparrow_escape($error); ?>

</div>

<?php endif; ?>

<form method="post" class="contact-form">

<div class="contact-honeypot" aria-hidden="true">
    <label for="website">Leave this field empty</label>
    <input
        type="text"
        id="website"
        name="website"
        tabindex="-1"
        autocomplete="off"
    >
</div>

<div class="contact-grid">

<div>

<label>Name *</label>

<input
type="text"
name="name"
required
value="<?php echo sparrow_escape($_POST['name'] ?? ''); ?>">

</div>

<div>

<label>Email Address *</label>

<input
type="email"
name="email"
required
value="<?php echo sparrow_escape($_POST['email'] ?? ''); ?>">

</div>

</div>

<div class="contact-grid">

<div>

<label>Phone Number</label>

<input
type="text"
name="phone"
value="<?php echo sparrow_escape($_POST['phone'] ?? ''); ?>">

</div>

<div>

<label>Subject *</label>

<select name="subject" required>

<option value="">Select One...</option>

<?php

$options = [
'General Question',
'Existing Order',
'Product Question',
'Website Issue',
'Other'
];

$current = $_POST['subject'] ?? '';

foreach($options as $option):

?>

<option
value="<?php echo sparrow_escape($option); ?>"
<?php echo $current === $option ? 'selected' : ''; ?>>

<?php echo sparrow_escape($option); ?>

</option>

<?php endforeach; ?>

</select>

</div>

</div>

<div>

<label>Message *</label>

<textarea
name="message"
required><?php echo sparrow_escape($_POST['message'] ?? ''); ?></textarea>

</div>

<div>

<label>Preferred Contact Method</label>

<div class="contact-radio">

<label>

<input
type="radio"
name="preferred_contact"
value="Email"
<?php echo (($_POST['preferred_contact'] ?? 'Email') === 'Email') ? 'checked' : ''; ?>>

 Email

</label>

<label>

<input
type="radio"
name="preferred_contact"
value="Phone"
<?php echo (($_POST['preferred_contact'] ?? '') === 'Phone') ? 'checked' : ''; ?>>

 Phone

</label>

</div>

</div>

<div class="contact-checkbox">

<input
type="checkbox"
name="contact_agreement"
value="1"
required
<?php echo !empty($_POST['contact_agreement']) ? 'checked' : ''; ?>>

<div>

I understand this form is for general questions.
For custom products, I should use the Custom Order Request form.

</div>

</div>

<p>

<button
type="submit"
class="button">

Send Message

</button>

</p>

</form>

</div>

</section>

</div>

<?php sparrow_public_footer(); ?>
