<?php

/**
 * TFCS Contact Form Handler
 * Uses PHPMailer + Gmail SMTP to send emails
 * Saves enquiries to MySQL database
 */

// ── SECURITY HEADERS ─────────────────────────────────────────────────────────
header('Content-Type: application/json; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

// ── LOAD PHPMAILER ────────────────────────────────────────────────────────────
// Adjust path if your vendor folder is in a different location
$vendorPath = __DIR__ . '/vendor/autoload.php';
if (!file_exists($vendorPath)) {
    // Try one level up
    $vendorPath = __DIR__ . '/vendor/autoload.php';
}
if (file_exists($vendorPath)) {
    require_once $vendorPath;
}

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

// ── LOAD .ENV ─────────────────────────────────────────────────────────────────
$envPath = __DIR__ . '/admin/.env';
if (file_exists($envPath)) {
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (str_starts_with(trim($line), '#')) continue;
        if (!str_contains($line, '=')) continue;
        [$key, $value] = explode('=', $line, 2);
        $_ENV[trim($key)] = trim(trim($value), '"\'');
    }
}

// ── ONLY ALLOW POST + AJAX ────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}
if (
    !isset($_SERVER['HTTP_X_REQUESTED_WITH']) ||
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'
) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Forbidden.']);
    exit;
}

// ── RATE LIMITING ─────────────────────────────────────────────────────────────
session_start();
$now = time();
if (isset($_SESSION['last_contact_submit']) && ($now - $_SESSION['last_contact_submit']) < 30) {
    http_response_code(429);
    echo json_encode(['success' => false, 'message' => 'Please wait before submitting again.']);
    exit;
}

// ── PARSE JSON BODY ───────────────────────────────────────────────────────────
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!$data || !is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request data.']);
    exit;
}

// ── SANITISE ──────────────────────────────────────────────────────────────────
function clean(string $value, int $maxLen = 500): string
{
    $value = trim($value);
    $value = strip_tags($value);
    $value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    return mb_substr($value, 0, $maxLen);
}

// ── HONEYPOT ──────────────────────────────────────────────────────────────────
if (!empty($data['website'])) {
    echo json_encode(['success' => true]);
    exit;
}

// ── EXTRACT & SANITISE FIELDS ─────────────────────────────────────────────────
$fullName = clean($data['full_name'] ?? '', 80);
$phone    = clean($data['phone']     ?? '', 20);
$email    = clean($data['email']     ?? '', 120);
$location = clean($data['location']  ?? '', 80);
$subject  = clean($data['subject']   ?? '', 60);
$message  = clean($data['message']   ?? '', 1000);
$ipAddr   = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

// ── VALIDATE ──────────────────────────────────────────────────────────────────
$errors = [];
if (mb_strlen($fullName) < 2)
    $errors[] = 'Full name is required.';
if (mb_strlen(preg_replace('/[\s\+\-\(\)]/', '', $phone)) < 7)
    $errors[] = 'A valid phone number is required.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    $errors[] = 'A valid email address is required.';
$allowedSubjects = ['membership', 'milk', 'feeds', 'sha', 'loans', 'training', 'other'];
if (!in_array($subject, $allowedSubjects, true))
    $errors[] = 'Please select a valid subject.';
if (mb_strlen($message) < 10)
    $errors[] = 'Message must be at least 10 characters.';

if (!empty($errors)) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => implode(' ', $errors)]);
    exit;
}

// ── SUBJECT LABELS ────────────────────────────────────────────────────────────
$subjectLabels = [
    'membership' => 'Membership Registration',
    'milk'       => 'Milk Collection / Pricing',
    'feeds'      => 'Ranges Animal Feeds',
    'sha'        => 'SHA Payments',
    'loans'      => 'Loan Guaranteeing',
    'training'   => 'Training & Events',
    'other'      => 'Other Enquiry',
];
$subjectLabel = $subjectLabels[$subject] ?? 'General Enquiry';

// ── DATABASE CONFIG ───────────────────────────────────────────────────────────
define('DB_HOST', $_ENV['DB_HOST'] ?? 'localhost');
define('DB_NAME', $_ENV['DB_NAME'] ?? 'tulagafc_website');
define('DB_USER', $_ENV['DB_USER'] ?? 'root');
define('DB_PASS', $_ENV['DB_PASS'] ?? '');

// ── SAVE TO DATABASE ──────────────────────────────────────────────────────────
$saved = false;
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false
        ]
    );

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS enquiries (
            id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            full_name  VARCHAR(80)  NOT NULL,
            phone      VARCHAR(20)  NOT NULL,
            email      VARCHAR(120) NOT NULL,
            location   VARCHAR(80)  DEFAULT '',
            subject    VARCHAR(80)  NOT NULL,
            message    TEXT         NOT NULL,
            ip_address VARCHAR(45)  DEFAULT '',
            status     ENUM('unread','read','replied') DEFAULT 'unread',
            created_at DATETIME     DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");

    $stmt = $pdo->prepare("
        INSERT INTO enquiries (full_name, phone, email, location, subject, message, ip_address)
        VALUES (:full_name, :phone, :email, :location, :subject, :message, :ip_address)
    ");
    $stmt->execute([
        ':full_name'  => $fullName,
        ':phone'      => $phone,
        ':email'      => $email,
        ':location'   => $location,
        ':subject'    => $subjectLabel,
        ':message'    => $message,
        ':ip_address' => $ipAddr,
    ]);
    $saved = true;
} catch (PDOException $e) {
    error_log('[TFCS DB Error] ' . $e->getMessage());
}

// ── SMTP CONFIG FROM .ENV ─────────────────────────────────────────────────────
$smtpHost = $_ENV['SMTP_HOST'] ?? 'smtp.gmail.com';
$smtpPort = (int)($_ENV['SMTP_PORT'] ?? 587);
$smtpUser = $_ENV['SMTP_USER'] ?? 'tulagafc@gmail.com';
$smtpPass = $_ENV['SMTP_PASS'] ?? '';
$smtpFrom = $_ENV['SMTP_FROM'] ?? 'tulagafc@gmail.com';
$smtpName = $_ENV['SMTP_NAME'] ?? 'Tulaga Farmers Co-operative Society';

// ── SEND EMAIL VIA PHPMAILER ──────────────────────────────────────────────────
$emailSent = false;

if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    try {
        $mail = new PHPMailer(true);

        // Server settings
        $mail->isSMTP();
        $mail->Host       = $smtpHost;
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtpUser;
        $mail->Password   = $smtpPass;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $smtpPort;
        $mail->CharSet    = 'UTF-8';

        // ── Main email to TFCS ────────────────────────────────────────────────
        $mail->setFrom($smtpFrom, $smtpName);
        $mail->addReplyTo($email, $fullName);
        $mail->addAddress('tulagafc@gmail.com', 'TFCS Admin');
        $mail->Subject = '[TFCS Enquiry] ' . $subjectLabel . ' from ' . $fullName;

        // HTML body
        $mail->isHTML(true);
        $mail->Body = "
        <div style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
          <div style='background:#1a3d2b;padding:24px 32px;border-radius:8px 8px 0 0;'>
            <h2 style='color:#e8b96f;margin:0;font-size:1.2rem;'>New Enquiry — TFCS Website</h2>
          </div>
          <div style='background:#f7f3ec;padding:28px 32px;border:1px solid #e0d9ce;'>
            <table style='width:100%;border-collapse:collapse;font-size:0.92rem;'>
              <tr><td style='padding:8px 0;color:#7a7a7a;width:100px;'>Name</td><td style='padding:8px 0;font-weight:600;color:#1a3d2b;'>{$fullName}</td></tr>
              <tr><td style='padding:8px 0;color:#7a7a7a;'>Phone</td><td style='padding:8px 0;font-weight:600;color:#1a3d2b;'>{$phone}</td></tr>
              <tr><td style='padding:8px 0;color:#7a7a7a;'>Email</td><td style='padding:8px 0;font-weight:600;color:#1a3d2b;'><a href='mailto:{$email}' style='color:#2d6a4f;'>{$email}</a></td></tr>
              <tr><td style='padding:8px 0;color:#7a7a7a;'>Location</td><td style='padding:8px 0;color:#1a3d2b;'>" . ($location ?: 'Not provided') . "</td></tr>
              <tr><td style='padding:8px 0;color:#7a7a7a;'>Subject</td><td style='padding:8px 0;font-weight:600;color:#c9963a;'>{$subjectLabel}</td></tr>
            </table>
            <div style='margin-top:20px;padding:16px;background:#fff;border-radius:8px;border-left:4px solid #2d6a4f;'>
              <p style='color:#7a7a7a;font-size:0.8rem;margin-bottom:6px;text-transform:uppercase;letter-spacing:0.05em;'>Message</p>
              <p style='color:#1c1c1c;line-height:1.7;margin:0;'>" . nl2br(htmlspecialchars($message)) . "</p>
            </div>
            <div style='margin-top:20px;padding:14px;background:#e8f5e9;border-radius:8px;font-size:0.82rem;color:#4a4a4a;'>
              <strong>Submitted:</strong> " . date('d M Y, H:i:s T') . " &nbsp;|&nbsp;
              <strong>IP:</strong> {$ipAddr}
            </div>
            <div style='margin-top:16px;text-align:center;'>
              <a href='http://localhost/Tulagafs_Website/admin/' style='display:inline-block;padding:10px 24px;background:#1a3d2b;color:#fff;border-radius:20px;font-size:0.85rem;text-decoration:none;'>View in Admin Panel</a>
            </div>
          </div>
          <div style='background:#0f2a1c;padding:16px 32px;border-radius:0 0 8px 8px;text-align:center;'>
            <p style='color:rgba(255,255,255,0.4);font-size:0.75rem;margin:0;'>Tulaga Farmers Co-operative Society Ltd &middot; Engineer Town, Nyandarua County</p>
          </div>
        </div>";

        // Plain text fallback
        $mail->AltBody = "New TFCS Enquiry\n\nName: {$fullName}\nPhone: {$phone}\nEmail: {$email}\nLocation: " . ($location ?: 'Not provided') . "\nSubject: {$subjectLabel}\n\nMessage:\n{$message}\n\nSubmitted: " . date('d M Y H:i:s') . "\nIP: {$ipAddr}";

        $mail->send();
        $emailSent = true;

        // ── Auto-reply to sender ──────────────────────────────────────────────
        $mail->clearAddresses();
        $mail->clearReplyTos();
        $mail->addAddress($email, $fullName);
        $mail->Subject = 'Thank you for contacting TFCS';

        $mail->Body = "
        <div style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
          <div style='background:#1a3d2b;padding:24px 32px;border-radius:8px 8px 0 0;'>
            <h2 style='color:#e8b96f;margin:0;font-size:1.2rem;'>Thank You for Reaching Out!</h2>
          </div>
          <div style='background:#f7f3ec;padding:28px 32px;border:1px solid #e0d9ce;'>
            <p style='color:#1c1c1c;font-size:0.95rem;line-height:1.7;'>Dear <strong>{$fullName}</strong>,</p>
            <p style='color:#4a4a4a;font-size:0.92rem;line-height:1.8;margin-top:12px;'>
              Thank you for contacting <strong>Tulaga Farmers Co-operative Society Ltd</strong>.
              We have received your enquiry about <strong style='color:#c9963a;'>{$subjectLabel}</strong>
              and will get back to you within <strong>24 hours</strong>.
            </p>
            <div style='margin:24px 0;padding:16px;background:#fff;border-radius:8px;border-left:4px solid #c9963a;'>
              <p style='color:#7a7a7a;font-size:0.8rem;margin-bottom:8px;text-transform:uppercase;letter-spacing:0.05em;'>For Urgent Assistance</p>
              <p style='margin:4px 0;font-size:0.9rem;'><strong>📞</strong> <a href='tel:+254712096437' style='color:#2d6a4f;'>+254 712 096 437</a></p>
              <p style='margin:4px 0;font-size:0.9rem;'><strong>📞</strong> <a href='tel:+254708667787' style='color:#2d6a4f;'>+254 708 667 787</a></p>
              <p style='margin:8px 0 0;font-size:0.82rem;color:#7a7a7a;'>Mon–Fri: 8:00 AM – 5:00 PM &nbsp;|&nbsp; Sat: 8:00 AM – 1:00 PM</p>
            </div>
            <p style='color:#4a4a4a;font-size:0.88rem;line-height:1.7;'>
              Warm regards,<br>
              <strong style='color:#1a3d2b;'>Tulaga Farmers Co-operative Society Ltd</strong><br>
              Engineer Town, Nyandarua County<br>
              <a href='mailto:tulagafc@gmail.com' style='color:#2d6a4f;'>tulagafc@gmail.com</a> &nbsp;&nbsp;
            </p>
          </div>
          <div style='background:#0f2a1c;padding:16px 32px;border-radius:0 0 8px 8px;text-align:center;'>
            <p style='color:rgba(255,255,255,0.4);font-size:0.75rem;margin:0;'>Tulaga Farmers Co-operative Society Ltd &middot; Engineer Town, Nyandarua County</p>
          </div>
        </div>";

        $mail->AltBody = "Dear {$fullName},\n\nThank you for contacting TFCS. We received your enquiry about \"{$subjectLabel}\" and will respond within 24 hours.\n\nFor urgent help:\n+254 712 096 437\n+254 708 667 787\n\nWarm regards,\nTulaga Farmers Co-operative Society Ltd\ntulagafc@gmail.com";

        $mail->send();
    } catch (Exception $e) {
        error_log('[TFCS Mail Error] ' . $e->getMessage());
        $emailSent = false;
    }
} else {
    // PHPMailer not installed — fallback to PHP mail()
    error_log('[TFCS] PHPMailer not found. Using fallback mail().');
    $headers   = "From: TFCS Website <tulagafc@gmail.com>\r\nReply-To: {$fullName} <{$email}>\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n";
    $emailSent = @mail('tulagafc@gmail.com', '[TFCS Enquiry] ' . $subjectLabel . ' from ' . $fullName, "Name: {$fullName}\nPhone: {$phone}\nEmail: {$email}\nSubject: {$subjectLabel}\n\nMessage:\n{$message}", $headers);
}

// ── RESPOND ───────────────────────────────────────────────────────────────────
if ($saved || $emailSent) {
    $_SESSION['last_contact_submit'] = $now;
    echo json_encode([
        'success' => true,
        'message' => 'Your message has been sent successfully.'
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Could not send your message at this time. Please call us on +254 712 096 437.'
    ]);
}
