<style>
    /* Modern Yıldız Oylama Sistemi */
    .rating-wrapper { display: inline-flex; flex-direction: row-reverse; justify-content: flex-end; align-items: center; }
    .rating-wrapper input { display: none; }
    .rating-wrapper label { cursor: pointer; width: 25px; font-size: 20px; color: #ccc; transition: color 0.2s; margin: 0; padding: 0; line-height: 1; }
    .rating-wrapper label:before { content: '\f005'; font-family: "Font Awesome 5 Free"; font-weight: 900; }
    /* Hover ve Seçili Durumlar */
    .rating-wrapper input:checked ~ label,
    .rating-wrapper label:hover,
    .rating-wrapper label:hover ~ label { color: #f39c12; }
    /* Form Gizleme/Gösterme Animasyonu */
    #yform { transition: all 0.3s ease; }
</style>

<?php
// Güvenlik: ID'yi integer'a çevir
$clean_id = (int)$id; 

// SQL Injection Korumalı Sorgu (Prepared Statement)
$stmt = $conn->prepare("SELECT s3 FROM genel WHERE ne='yorum' AND s1=? AND s4=1");
$stmt->bind_param("i", $clean_id);
$stmt->execute();
$result = $stmt->get_result();
$total_comment = $result->num_rows;

$cs3 = 0;
while($row = $result->fetch_assoc()){
    $cs3 += $row["s3"];
}
$stmt->close();

// Ortalama Puan Hesabı
$avg_rating = ($total_comment > 0) ? round($cs3 / $total_comment, 1) : 0;
?>

<div class="v3-row">
    <div class="v3-col-md-12">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
            <h3 style="margin:0;"><?php echo translate("Yorumlar"); ?></h3>
            <?php if($total_comment > 0): ?>
                <button id="byorum" class="v3-btn v3-btn-info" onclick="toggleCommentForm()"><?php echo translate("Yorum Yap"); ?></button>
            <?php endif; ?>
        </div>
    </div>

    <div id="form-message" style="display:none; margin-bottom:10px;"></div>

    <form name="yorum" id="yform" style="<?php echo ($total_comment > 0) ? 'display:none;' : ''; ?>">
        <input type="hidden" name="id" value="<?php echo $clean_id; ?>">
        <?php 
            $type_map = ['d'=>'kayit', 's'=>'sayfa', 'h'=>'haber', 'u'=>'uye', 'v'=>'video'];
            $page_char = $sayfa[0] ?? 'd'; // Varsayılan
            $t2_val = $type_map[$page_char] ?? 'medya';
            $t1_val = ($page_char == 'u') ? 't5' : (isset($_SESSION["lang"]) ? $_SESSION["lang"] : 'tr');
        ?>
        <input type="hidden" name="t1" value="<?php echo $t1_val; ?>">
        <input type="hidden" name="t2" value="<?php echo $t2_val; ?>">

        <?php if(empty($_SESSION["User_ID"])): ?>
            <div class="v3-col-md-12 v3-col-xs-12 mt5">
                <div class="v3-input-group">
                    <span class="v3-input-group-addon"><i class="fas fa-user"></i></span>
                    <input type="text" class="v3-form-control" name="t4" required placeholder="<?php echo translate("Adınız Soyadınız"); ?>">
                </div>
            </div>
             <?php else: ?>
            <input type="hidden" name="t4" value="<?php echo $_SESSION["User_Name"]; ?>">
            <input type="hidden" name="t5" value="<?php echo $_SESSION["User_Email"]; ?>">
        <?php endif; ?>

        <div class="v3-col-md-12 v3-col-xs-12 mt5">
            <textarea name="n1" class="v3-form-control" rows="3" required placeholder="<?php echo translate("Düşüncelerinizi paylaşın..."); ?>"></textarea>
        </div>

        <div class="v3-col-md-8 v3-col-xs-7 mt5" style="display:flex; align-items:center;">
            <div class="rating-wrapper">
                <input type="radio" id="star5" name="s3" value="5"><label for="star5" title="5 Yıldız"></label>
                <input type="radio" id="star4" name="s3" value="4"><label for="star4" title="4 Yıldız"></label>
                <input type="radio" id="star3" name="s3" value="3"><label for="star3" title="3 Yıldız"></label>
                <input type="radio" id="star2" name="s3" value="2"><label for="star2" title="2 Yıldız"></label>
                <input type="radio" id="star1" name="s3" value="1"><label for="star1" title="1 Yıldız"></label>
            </div>
            <span style="font-size:12px; color:#999; margin-left:10px;"><?php echo translate("Puanlayın"); ?></span>
        </div>

        <div class="v3-col-md-4 v3-col-xs-5 mt5">
            <button type="submit" class="v3-btn v3-btn-warning v3-form-control" id="btnSubmit">
                <i class="fas fa-paper-plane"></i> <?php echo translate("Gönder"); ?>
            </button>
        </div>
    </form>
</div>

<hr>

<?php if($total_comment > 0): ?>
<div class="alert alert-info" style="padding:10px;">
    <?php echo translate("Bu içerik"); ?> <strong><?php echo $total_comment; ?></strong> <?php echo translate("yorum ve ortalama"); ?> 
    <strong><?php echo $avg_rating; ?></strong> <?php echo translate("puan aldı."); ?>
</div>
<?php else: ?>
<div class="alert alert-warning" style="padding:10px;">
    <?php echo translate("Henüz yorum yapılmamış. İlk yorumu sen yap!"); ?>
</div>
<?php endif; ?>

<div id="comments_container">
    <div style="text-align:center; padding:20px;">
        <i class="fas fa-spinner fa-spin fa-2x"></i><br><?php echo translate("Yorumlar Yükleniyor..."); ?>
    </div>
</div>

<script>
    // Form Gösterme/Gizleme
    function toggleCommentForm() {
        var form = document.getElementById('yform');
        var btn = document.getElementById('byorum');
        if (form.style.display === "none") {
            form.style.display = "block";
            btn.style.display = "none";
        }
    }

    // Yorumları Yükle
    function loadComments() {
        jQuery('#comments_container').load('<?php echo $cpath; ?>deppo/tools/script/comments.php?id=<?php echo $clean_id; ?>');
    }

    // Modern AJAX Gönderimi
    jQuery(document).ready(function($) {
        // Sayfa yüklendiğinde yorumları çek
        loadComments();

        $('#yform').on('submit', function(e) {
            e.preventDefault();
            var btn = $('#btnSubmit');
            var originalText = btn.html();
            
            // Basit Validasyon
            var comment = $('textarea[name="n1"]').val();
            if(comment.trim().length < 3) {
                alert("<?php echo translate('Lütfen geçerli bir yorum yazın.'); ?>");
                return;
            }

            btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Gönderiliyor...');

            $.ajax({
                type: "POST",
                url: "config/func.php?islem=yorum", // Buranın doğru endpoint olduğundan emin olun
                data: $(this).serialize(),
                success: function(response) {
                    // Başarılı
                    $('#form-message').html('<div class="alert alert-success"><i class="fa fa-check"></i> ' + "<?php echo translate('Yorumunuz başarıyla gönderildi (Onay bekliyor olabilir).'); ?>" + '</div>').show();
                    $('#yform')[0].reset();
                    $('#yform').slideUp();
                    loadComments(); // Listeyi yenile
                },
                error: function() {
                    $('#form-message').html('<div class="alert alert-danger">Hata oluştu, lütfen tekrar deneyin.</div>').show();
                },
                complete: function() {
                    btn.prop('disabled', false).html(originalText);
                    setTimeout(function(){ $('#form-message').fadeOut(); }, 5000);
                }
            });
        });
    });
</script>