<?php
require_once (dirname(__DIR__, 2) . '/init.php');

$db = new DB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $languages = languages('data');
    $lang_ref_id = bin2hex(random_bytes(32));
    $lang_is_default = lang_is_default('lang_code');

    // CSRF geçici olarak devre dışı (frontend için)
    // $csrf_ok = ($_POST['csrf_token_fronted'] ?? null) ? csrf_token_fronted($_POST['csrf_token_fronted'])[0] : true;
    // if (!$csrf_ok) { echo json_encode(['status'=>'error','message'=>'CSRF']); exit; }

    // Form alanları
    $name = m_u_p('name');
    $email = m_u_p('email');
    $text = m_u_p('text');
        $title = m_u_p('title');
    $model = m_u_p('model') ?: 'feedback';
        $status = m_u_p('status');
    if ($status === null || $status === '') { $status = 1; }
    $description = m_u_p('description') ?? null;
    $content = m_u_p('content') ?? ($text ?? null);
    $image = m_u_p('image') ?? null;
    $icon = m_u_p('icon') ?? null;
    $images = m_u_p('images') ?? null;

    // Başlık yoksa otomatik üret
    if (empty($title)) {
        if (!empty($name)) {
            $title = 'Mesaj - ' . $name;
        } elseif (!empty($email)) {
            $title = 'Mesaj - ' . $email;
        } elseif (!empty($text)) {
            $title = mb_substr(trim($text), 0, 60);
        } else {
            $title = 'İletişim Formu';
        }
    }

    // Minimum doğrulama: en az e-posta veya metin olmalı
        if (empty($title)) {
        echo json_encode(['status' => 'error', 'message' => 'Lütfen başlık giriniz.']);
        exit;
    }

    // featuresData normalize ve alanları türet
    $featuresData = null;
    $decodedFeatures = null;
    if (isset($_POST['featuresData']) && is_string($_POST['featuresData']) && $_POST['featuresData'] !== '') {
        $decoded = json_decode($_POST['featuresData'], true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $decodedFeatures = is_array($decoded) ? $decoded : [];
            // E-posta/ad/metin alanları featuresData içindeyse çıkar
            if (empty($email)) { $email = $decodedFeatures['email'] ?? $decodedFeatures['mail'] ?? null; }
            if (empty($name)) { $name = $decodedFeatures['name'] ?? $decodedFeatures['ad'] ?? null; }
            if (empty($text)) { $text = $decodedFeatures['text'] ?? $decodedFeatures['message'] ?? null; }
            // İçeriği de text ile doldur
            if (empty($content) && !empty($text)) { $content = $text; }
            $featuresData = json_encode($decodedFeatures, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        } else {
            $featuresData = trim(strip_tags($_POST['featuresData']));
        }
    }

    $data = [
        'lang'        => m_get_session('lang') ?: $lang_is_default,
        'lang_ref_id' => $lang_ref_id,
        'module_type' => $model,
        'title'       => $title,
        'description' => $description,
        'content'     => $content,
        'image'       => $image,
        'icon'        => $icon,
        'images'      => $images,
        'features'    => $featuresData,
        'status'      => $status,
        'sort'        => '0',
        'created_at'  => $db->now(),
        'updated_at'  => $db->now(),
    ];

    $insertId = $db->table('posts')->insert($data);
    if ($insertId === false) {
        echo json_encode(['status' => 'error', 'message' => 'Insert başarısız', 'db_error' => $db->error()]);
        exit;
    }

    // Mail bildirimi (ayarlar general_settings üzerinden)
    try {
        $smtpHost = general_settings('smtp_host', $lang_is_default);
        $smtpPort = general_settings('smtp_port', $lang_is_default) ?: 587;
        $smtpUser = general_settings('smtp_user', $lang_is_default);
        $smtpPass = general_settings('smtp_pass', $lang_is_default);
        $smtpSecure = general_settings('smtp_secure', $lang_is_default) ?: 'tls';
        $mailFrom = general_settings('mail_from', $lang_is_default) ?: $smtpUser;
        $mailFromName = general_settings('mail_from_name', $lang_is_default) ?: 'Web Formu';
        // Admin alıcısı öncelikli
        $mailAdmin = general_settings('mail_admin', $lang_is_default);
        $mailTo = $mailAdmin ?: ($mailFrom ?: $smtpUser);

        if ($smtpHost && $smtpUser && $smtpPass) {
            require_once ROOT_FOLDER.'/includes/m_lib/plugins/PHPMailer/class.phpmailer.php';
            require_once ROOT_FOLDER.'/includes/m_lib/plugins/PHPMailer/class.smtp.php';
            // Logo adresi (ayar -> media -> varsayılan)
            $logoSetting = general_settings('mail_logo', $lang_is_default)
                ?: general_settings('site_logo', $lang_is_default)
                ?: general_settings('logo', $lang_is_default);
            if (!empty($logoSetting)) {
                $logoUrl = image($logoSetting);
            } else {
                $logoUrl = DOMAIN.'/media/logo.webp';
            }
            $mailer = new PHPMailer();
            $mailer->isSMTP();
            $mailer->Host = $smtpHost;
            $mailer->Port = (int)$smtpPort;
            $mailer->SMTPAuth = true;
            $mailer->SMTPSecure = $smtpSecure;
            $mailer->Username = $smtpUser;
            $mailer->Password = $smtpPass;
            $mailer->CharSet = 'UTF-8';

            $mailer->setFrom($mailFrom, $mailFromName);
            if (!empty($email)) { $mailer->addReplyTo($email, $name ?: $email); }
            $mailer->addAddress($mailTo, 'Bildirim');

            $mailer->Subject = 'Yeni form bildirimi: ' . $title;
            // Admin mail içeriği (HTML)
            $safeTitle = htmlspecialchars((string)$title, ENT_QUOTES, 'UTF-8');
            $safeName = htmlspecialchars((string)($name ?? ''), ENT_QUOTES, 'UTF-8');
            $safeEmail = htmlspecialchars((string)($email ?? ''), ENT_QUOTES, 'UTF-8');
            $safeText = nl2br(htmlspecialchars((string)($text ?? ''), ENT_QUOTES, 'UTF-8'));
            $featuresPretty = '';
            if (!empty($featuresData)) {
                $decodedF = json_decode($featuresData, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decodedF)) {
                    $featuresPretty .= '<table style="width:100%;border-collapse:collapse">';
                    foreach ($decodedF as $k=>$v) {
                        $k2 = htmlspecialchars((string)$k, ENT_QUOTES, 'UTF-8');
                        $v2 = htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
                        $featuresPretty .= '<tr><td style="border:1px solid #eee;padding:6px;width:30%">'.$k2.'</td><td style="border:1px solid #eee;padding:6px">'.$v2.'</td></tr>';
                    }
                    $featuresPretty .= '</table>';
                }
            }
            $mailer->isHTML(true);
            $mailer->Body = "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><style>
                .mail-wrap{max-width:700px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #eee}
                .mail-header{padding:14px 20px;background:#0b1220}
                .mail-header img{display:block;max-height:38px}
                .mail-body{padding:20px;color:#0b0b0b;font-family:system-ui,-apple-system,'Segoe UI',Roboto,Ubuntu,'Helvetica Neue',Arial}
                .kv{margin:0 0 10px}
                .kv b{display:inline-block;min-width:110px}
                .panel{background:#f8fafc;border:1px solid #e5e7eb;border-radius:8px;padding:12px}
                table{width:100%;border-collapse:collapse;margin-top:10px}
                td{border:1px solid #eee;padding:8px}
              </style></head><body style=\"background:#f3f4f6;padding:18px\">
                <div class='mail-wrap'>
                  <div class='mail-header'><img src='{$logoUrl}' alt='Logo'></div>
                  <div class='mail-body'>
                    <h3 style='margin:0 0 12px'>Yeni Form Bildirimi</h3>
                    <p class='kv'><b>Başlık:</b> {$safeTitle}</p>
                    <p class='kv'><b>Ad Soyad:</b> {$safeName}</p>
                    <p class='kv'><b>E‑posta:</b> {$safeEmail}</p>
                    <div class='panel'><b>Mesaj:</b><br>{$safeText}</div>
                    ".($featuresPretty?"<h4 style='margin:18px 0 8px'>Ek Alanlar</h4>{$featuresPretty}":'')."
                  </div>
                </div>
              </body></html>";
            try { 
                if (!$mailer->send()) {
                    // error_log('Form mail (admin) gönderilemedi: ' . $mailer->ErrorInfo);
                }
            } catch (Exception $ignored) { /* mail hatasını yut */ }

            // Kullanıcıya teyit maili (email mevcutsa)
            if (!empty($email)) {
                $userMailer = new PHPMailer();
                $userMailer->isSMTP();
                $userMailer->Host = $smtpHost;
                $userMailer->Port = (int)$smtpPort;
                $userMailer->SMTPAuth = true;
                $userMailer->SMTPSecure = $smtpSecure;
                $userMailer->Username = $smtpUser;
                $userMailer->Password = $smtpPass;
                $userMailer->CharSet = 'UTF-8';

                $userMailer->setFrom($mailFrom, $mailFromName);
                $userMailer->addAddress($email, $name ?: $email);
                if (!empty($mailTo)) { $userMailer->addReplyTo($mailTo, $mailFromName); }
                $userMailer->Subject = 'Talebiniz alındı: ' . $title;

                // Basit HTML şablon
                $safeTitle = htmlspecialchars((string)$title, ENT_QUOTES, 'UTF-8');
                $safeName = htmlspecialchars((string)($name ?? ''), ENT_QUOTES, 'UTF-8');
                $safeText = nl2br(htmlspecialchars((string)($text ?? ''), ENT_QUOTES, 'UTF-8'));
                $safeDomain = htmlspecialchars(DOMAIN, ENT_QUOTES, 'UTF-8');
                $userBody = "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><style>
                    .mail-wrap{max-width:700px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #eee}
                    .mail-header{padding:14px 20px;background:#0b1220}
                    .mail-header img{display:block;max-height:38px}
                    .mail-body{padding:20px;color:#0b0b0b;font-family:system-ui,-apple-system,'Segoe UI',Roboto,Ubuntu,'Helvetica Neue',Arial}
                    .mail-footer{padding:14px 20px;background:#f9fafb;color:#374151;font-size:12px}
                    .btn{display:inline-block;background:#0b1220;color:#fff !important;text-decoration:none;padding:10px 14px;border-radius:8px}
                    .muted{color:#6b7280;font-size:13px}
                </style></head><body style=\"background:#f3f4f6;padding:18px\">
                  <div class='mail-wrap'>
                    <div class='mail-header'><img src='{$logoUrl}' alt='Logo'></div>
                    <div class='mail-body'>
                      <p>Merhaba {$safeName},</p>
                      <p>Talebiniz tarafımıza ulaştı. En kısa sürede sizinle iletişime geçeceğiz.</p>
                      <p class='muted'>Başlık:</p>
                      <p><strong>{$safeTitle}</strong></p>
                      <p class='muted'>Mesajınız:</p>
                      <div style='background:#f9fafb;border:1px solid #eee;border-radius:8px;padding:12px'>{$safeText}</div>
                      <p style='margin-top:18px'>Dilerseniz aşağıdaki bağlantıdan bize doğrudan ulaşabilirsiniz.</p>
                      <p><a class='btn' href='{$safeDomain}' target='_blank' rel='noopener'>Web sitemizi ziyaret edin</a></p>
                    </div>
                    <div class='mail-footer'>Bu e‑posta otomatik olarak gönderilmiştir. Lütfen bu mesaja yanıt vermeyiniz.</div>
                  </div>
                </body></html>";

                $userMailer->isHTML(true);
                $userMailer->Body = $userBody;
                try { if (!$userMailer->send()) { /* error_log('Kullanıcı maili gönderilemedi: '.$userMailer->ErrorInfo); */ } } catch (Exception $ignored) {}
            }
        }
    } catch (Exception $ignored) { /* ayarlar yoksa mail atlama */ }

    echo json_encode(['status' => 'success', 'message' => 'Mesajınız kaydedildi.', 'id' => $insertId]);
    exit;
}

http_response_code(405);
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => 'Yalnızca POST istekleri kabul edilir.']);
