<?php
ob_start();
session_start();
require 'includes/db.php';

// PHPMailer
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpmailer/src/Exception.php';

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

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: home.php#contact");
    exit;
}

// Sanitize input
$facility_id = intval($_POST['facility_id'] ?? 1); // default 1
$name        = trim($_POST['name'] ?? '');
$email       = trim($_POST['email'] ?? '');
$message     = trim($_POST['message'] ?? '');

// Validate
if (empty($name) || empty($email) || empty($message)) {
    header("Location: home.php?status=fail#contact");
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header("Location: home.php?status=invalid_email#contact");
    exit;
}

// Save to database
try {
    $stmt = $pdo->prepare("INSERT INTO contact_messages (facility_id, name, email, message, status) VALUES (?, ?, ?, ?, 'pending')");
    $stmt->execute([$facility_id, $name, $email, $message]);
} catch (Exception $e) {
    error_log("DB Insert Error: " . $e->getMessage());
    header("Location: home.php?status=fail#contact");
    exit;
}

// Fetch facility info
$stmt = $pdo->prepare("SELECT name, facility_phone, street FROM facility WHERE id = ?");
$stmt->execute([$facility_id]);
$facility = $stmt->fetch(PDO::FETCH_ASSOC);
$facility_name    = $facility['name'] ?? 'THARHON Medical Clinic';
$facility_phone   = $facility['facility_phone'] ?? '';
$facility_address = $facility['street'] ?? '';

// Send email
$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host       = 'mail.tharhonclinic.rw';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'info@tharhonclinic.rw';
    $mail->Password   = 'THARHON@11'; // move to env in production
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('info@tharhonclinic.rw', $facility_name);
    $mail->addAddress('info@tharhonclinic.rw', $facility_name);
    $mail->addReplyTo($email, $name);

    $mail->isHTML(true);
    $mail->Subject = "New Contact Message - {$facility_name}";
    $mail->Body = "
        <h3>New Contact Message for {$facility_name}</h3>
        <p><strong>Facility Phone:</strong> {$facility_phone}</p>
        <p><strong>Facility Address:</strong> {$facility_address}</p>
        <hr>
        <p><strong>Name:</strong> {$name}</p>
        <p><strong>Email:</strong> {$email}</p>
        <p><strong>Message:</strong><br>" . nl2br(htmlspecialchars($message)) . "</p>
        <hr>
        <small>Sent from website contact form</small>
    ";

    $mail->send();
    header("Location: home.php?status=success#contact");
    exit;

} catch (Exception $e) {
    error_log("Email Error: " . $mail->ErrorInfo);
    header("Location: home.php?status=fail#contact");
    exit;
}
?>