<?php
require_once '../../config/config.php';
require_once '../../includes/auth.php';

requireCompanyLogin();
ensureFeatureAndPaymentTables();

$companyId = (int)($_SESSION['company_id'] ?? 0);
$serviceId = (int)($_POST['service_id'] ?? 0);
$csrf = $_POST['csrf_token'] ?? '';

if (!$serviceId || !verifyCSRFToken($csrf)) {
    setFlashMessage('error', 'Geçersiz istek.');
    redirect('index.php');
}

// Hizmet firma sahibi mi?
$stmt = $pdo->prepare("SELECT id, title FROM services WHERE id = ? AND company_id = ?");
$stmt->execute([$serviceId, $companyId]);
$service = $stmt->fetch();

if (!$service) {
    setFlashMessage('error', 'Hizmet bulunamadı.');
    redirect('index.php');
}

try {
    // Daha önce talep var mı?
    $stmt = $pdo->prepare("SELECT status FROM service_feature_requests WHERE company_id = ? AND service_id = ?");
    $stmt->execute([$companyId, $serviceId]);
    $existing = $stmt->fetch();

    if ($existing && $existing['status'] === 'approved') {
        setFlashMessage('success', 'Bu hizmet zaten ana sayfada gösterim için onaylı.');
        redirect('index.php');
    }

    if ($existing) {
        $stmt = $pdo->prepare("UPDATE service_feature_requests SET status='pending', requested_at=NOW(), admin_note=NULL WHERE company_id=? AND service_id=?");
        $stmt->execute([$companyId, $serviceId]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO service_feature_requests (company_id, service_id, status) VALUES (?, ?, 'pending')");
        $stmt->execute([$companyId, $serviceId]);
    }

    // Banka bilgilerini settings'ten çek
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN (
        'payment_bank_name','payment_account_name','payment_iban','payment_branch','payment_note','featured_service_price'
    )");
    $s = [];
    while ($row = $stmt->fetch()) {
        $s[$row['setting_key']] = $row['setting_value'];
    }

    $price = $s['featured_service_price'] ?? '200';
    $msg = "Talebiniz alındı: \"{$service['title']}\".\n\n"
        . "Ödemenizi aşağıdaki banka bilgilerine gönderin, ardından Ödeme Bildirimi yapın.\n"
        . "Ücret: {$price} TL / 15 gün\n\n"
        . "Banka: " . ($s['payment_bank_name'] ?? '-') . "\n"
        . "Hesap Sahibi: " . ($s['payment_account_name'] ?? '-') . "\n"
        . "IBAN: " . ($s['payment_iban'] ?? '-') . "\n"
        . "Şube/Hesap: " . ($s['payment_branch'] ?? '-') . "\n";

    if (!empty($s['payment_note'])) {
        $msg .= "\nNot: " . $s['payment_note'];
    }

    // Kalıcı bilgilendirme (kullanıcı kapatana kadar)
    $_SESSION['sticky_notice'] = [
        'type' => 'success',
        'message' => $msg,
        'link_text' => 'Ücretli Hizmetler sayfasına git',
        'link_url' => SITE_URL . '/company/paid-services.php'
    ];
} catch (PDOException $e) {
    setFlashMessage('error', 'Talep oluşturulurken hata oluştu.');
}

redirect('index.php');


