<?php
require_once __DIR__ . '/lib/functions.php';
require_once __DIR__ . '/lib/document-render.php';
mdw_require_login();

global $mdw_documents_file, $mdw_work_email, $mdw_business_name;
if (!isset($mdw_documents_file)) $mdw_documents_file = __DIR__ . '/data/documents.json';
$documents = mdw_read_json($mdw_documents_file, []);
$id = $_GET['id'] ?? ($_POST['id'] ?? '');
$doc = null;
foreach ($documents as $item) {
    if (($item['id'] ?? '') === $id) { $doc = $item; break; }
}
if (!$doc) { mdw_flash('Document not found.', 'error'); header('Location: documents.php'); exit; }

$defaultFrom = $mdw_work_email ?? 'no-reply@' . ($_SERVER['HTTP_HOST'] ?? 'murdockdevworks.com');
$businessName = $mdw_business_name ?? 'Murdock DevWorks';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $to = trim((string)($_POST['to'] ?? ''));
    $from = trim((string)($_POST['from'] ?? $defaultFrom));
    $subject = trim((string)($_POST['subject'] ?? '')) ?: ($businessName . ' - ' . ($doc['title'] ?? 'Document'));
    $message = trim((string)($_POST['message'] ?? ''));

    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        mdw_flash('Please enter a valid recipient email address.', 'error');
    } elseif (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
        mdw_flash('Please enter a valid from email address.', 'error');
    } else {
        $html = '<p>' . nl2br(mdw_h($message ?: 'Please see the document below.')) . '</p>' . mdw_render_document_paper($doc);
        $headers = [];
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $headers[] = 'From: ' . $businessName . ' <' . $from . '>';
        $headers[] = 'Reply-To: ' . $from;
        $headers[] = 'X-Mailer: PHP/' . phpversion();

        if (@mail($to, $subject, $html, implode("\r\n", $headers))) {
            mdw_flash('Document email was sent. If it does not arrive, check hosting email/SPF/DKIM settings.', 'success');
            header('Location: document-view.php?id=' . urlencode($id));
            exit;
        }
        mdw_flash('The server could not send the email. You can still print/save as PDF or download HTML. Email setup may need SMTP or hosting mail configuration.', 'error');
    }
}

mdw_render_header('Email Document');
?>
<section class="panel">
  <h2>Email Document</h2>
  <p class="muted">Send this branded document from the admin area. This uses the server PHP mail function for now.</p>
  <form method="post">
    <input type="hidden" name="id" value="<?php echo mdw_h($id); ?>">
    <label>To / Client Email</label>
    <input type="email" name="to" required placeholder="client@example.com" value="<?php echo mdw_h($_POST['to'] ?? ''); ?>">
    <label>From / Work Email</label>
    <input type="email" name="from" required value="<?php echo mdw_h($_POST['from'] ?? $defaultFrom); ?>">
    <label>Subject</label>
    <input name="subject" value="<?php echo mdw_h($_POST['subject'] ?? ($businessName . ' - ' . ($doc['title'] ?? 'Document'))); ?>">
    <label>Message</label>
    <textarea name="message"><?php echo mdw_h($_POST['message'] ?? "Hello,\n\nPlease see the document below.\n\nThank you,\nMurdock DevWorks"); ?></textarea>
    <p class="row-actions" style="margin-top:18px">
      <button class="button" type="submit">Send Email</button>
      <a class="button ghost" href="document-view.php?id=<?php echo urlencode($id); ?>">Cancel</a>
    </p>
  </form>
</section>
<?php mdw_render_footer(); ?>
