<?php

include '../config.php';
$zaman = time();
$ip = $_SERVER['REMOTE_ADDR'];

function getFullname($id) {
        global $db;
        $userx = $db->query('SELECT * FROM kullanicilar WHERE user_id = '.$id.'')->fetch(PDO::FETCH_ASSOC);
        $userx = $userx['user_fullname'];
        return $userx;
    }


function getProfilResmi($id) {
        global $db;
        $userx = $db->query('SELECT * FROM kullanicilar WHERE user_id = '.$id.'')->fetch(PDO::FETCH_ASSOC);
        $userx = $userx['user_picture'];
        return $userx;
    }

if($_POST['type']=='sohbetList'){

    // ÇOK HIZLI SORGU: Sadece son 50K mesaja bak ve basit işlemler yap
    $mesajListesi = $db->query("
        SELECT 
            m.id,
            m.gonderen_id,
            m.alan_id,
            m.icerik,
            m.okundu,
            m.zaman,
            g.user_id as g_id,
            g.user_fullname as g_fullname,
            g.user_picture as g_picture,
            g.user_bot as g_bot,
            g.user_jeton as g_jeton,
            a.user_id as a_id,
            a.user_fullname as a_fullname,
            a.user_picture as a_picture,
            a.user_bot as a_bot,
            a.user_jeton as a_jeton
        FROM mesajlar m
        INNER JOIN kullanicilar g ON m.gonderen_id = g.user_id
        INNER JOIN kullanicilar a ON m.alan_id = a.user_id
        WHERE (
            (g.user_bot = 0 AND a.user_bot = 1) OR 
            (g.user_bot = 1 AND a.user_bot = 0)
        )
        AND g.user_deaktif = 0
        AND a.user_deaktif = 0
        ORDER BY m.id DESC
        LIMIT 5000
    ", PDO::FETCH_ASSOC);
    
    // PHP ile grupla - çok daha hızlı!
    $conversations = [];
    $user_last_messages = [];
    $user_message_count = []; // Kullanıcıdan kaç mesaj gelmiş
    
    foreach($mesajListesi as $row) {
        // Gerçek kullanıcı ve bot ID'lerini belirle
        if($row['g_bot'] == 0) {
            $user_id = $row['g_id'];
            $bot_id = $row['a_id'];
            $is_from_user = ($row['gonderen_id'] == $user_id);
        } else {
            $user_id = $row['a_id'];
            $bot_id = $row['g_id'];
            $is_from_user = ($row['gonderen_id'] == $user_id);
        }
        
        $conv_key = $bot_id . '-' . $user_id;
        
        // İlk mesajı al (en son mesaj)
        if(!isset($conversations[$conv_key])) {
            $conversations[$conv_key] = $row;
        }
        
        // Kullanıcıdan gelen mesaj sayısını say
        if($is_from_user) {
            if(!isset($user_message_count[$conv_key])) {
                $user_message_count[$conv_key] = 0;
            }
            $user_message_count[$conv_key]++;
        }
        
        // Kullanıcıdan gelen en son mesajı bul (sıralama için)
        if($is_from_user && !isset($user_last_messages[$conv_key])) {
            $user_last_messages[$conv_key] = $row['zaman'];
        }
    }
    
    // Kullanıcıdan hiç mesaj gelmemiş konuşmaları filtrele
    $conversations = array_filter($conversations, function($row) use ($user_message_count) {
        $bot_id = ($row['g_bot'] == 1) ? $row['g_id'] : $row['a_id'];
        $user_id = ($row['g_bot'] == 0) ? $row['g_id'] : $row['a_id'];
        $conv_key = $bot_id . '-' . $user_id;
        
        // En az 1 kullanıcı mesajı olmalı
        return isset($user_message_count[$conv_key]) && $user_message_count[$conv_key] > 0;
    });
    
    // Kullanıcıdan gelen en son mesaja göre sırala
    uasort($conversations, function($a, $b) use ($user_last_messages) {
        $a_bot_id = ($a['g_bot'] == 1) ? $a['g_id'] : $a['a_id'];
        $a_user_id = ($a['g_bot'] == 0) ? $a['g_id'] : $a['a_id'];
        $b_bot_id = ($b['g_bot'] == 1) ? $b['g_id'] : $b['a_id'];
        $b_user_id = ($b['g_bot'] == 0) ? $b['g_id'] : $b['a_id'];
        
        $a_key = $a_bot_id . '-' . $a_user_id;
        $b_key = $b_bot_id . '-' . $b_user_id;
        
        $a_time = $user_last_messages[$a_key] ?? 0;
        $b_time = $user_last_messages[$b_key] ?? 0;
        
        return $b_time - $a_time; // Yeniden eskiye
    });
    
    // İlk 300 konuşmayı göster
    $conversations = array_slice($conversations, 0, 300);

    foreach($conversations as $row){
        
        // Gerçek kullanıcı ve bot ID'lerini belirle
        if($row['g_bot'] == 0) {
            // Gönderen gerçek kullanıcı
            $user_id = $row['g_id'];
            $bot_id = $row['a_id'];
            $user_fullname = $row['g_fullname'];
            $user_picture = $row['g_picture'];
            $bot_fullname = $row['a_fullname'];
            $user_jeton = $row['g_jeton'];
            $mesaj_bizden = ($row['gonderen_id'] == $bot_id);
        } else {
            // Alıcı gerçek kullanıcı
            $user_id = $row['a_id'];
            $bot_id = $row['g_id'];
            $user_fullname = $row['a_fullname'];
            $user_picture = $row['a_picture'];
            $bot_fullname = $row['g_fullname'];
            $user_jeton = $row['a_jeton'];
            $mesaj_bizden = ($row['gonderen_id'] == $bot_id);
        }
        
        // Mesaj içeriğini kısalt ve başına "Siz: " ekle
        $icerigi = mb_substr($row['icerik'], 0, 25);
        
        // Resim mesajlarını özel göster
        if (preg_match('~\.(png|gif|jpe?g|bmp)~i', $row['icerik'])) {
            $prefix = $mesaj_bizden ? '<span style="color: #F54927; font-weight: 600;">Siz: </span>' : '';
            $icerigi = $prefix . '<ion-icon style="font-size: 20px !important;" name="image-outline"></ion-icon> <font style="font-size: 15px !important; float: right; margin-left: 5px;"><b>Fotoğraf</b></font>';
        } else {
            $icerigi = $mesaj_bizden ? '<span style="color: #F54927; font-weight: 600;">Siz: </span>' . $icerigi : $icerigi;
        }
        
        // Okunmamış mesaj vurgusu (sadece kullanıcıdan gelen mesajlar için)
        $border_style = ($row['okundu'] == 0 && !$mesaj_bizden) ? 'style="border: 3px solid #f00;"' : '';
        $bold_start = ($row['okundu'] == 0 && !$mesaj_bizden) ? '<b>' : '';
        $bold_end = ($row['okundu'] == 0 && !$mesaj_bizden) ? '</b>' : '';
        
        // Yüksek jetonlu kullanıcılar için özel class (5000+ jeton)
        $jeton_class = ($user_jeton >= 5000) ? 'HIGH_JETON' : 'LOW_JETON';
        
        // Son mesaj saati
        $mesaj_saati = date('H:i', $row['zaman']);
        
        // Kullanıcı mesaj sayısı
        $conv_key = $bot_id . '-' . $user_id;
        $msg_count = isset($user_message_count[$conv_key]) ? $user_message_count[$conv_key] : 0;
        
        ?>
        <li id="mesaj_<?=$bot_id?>_<?=$user_id?>" class="<?=$jeton_class?>" data-msg-count="<?=$msg_count?>">
            <a onclick="acMesaj(<?=$bot_id?>,<?=$user_id?>,'<?=$user_fullname?>','<?=$user_picture?>');" href="#" class="item">
                <div class="d-flex align-items-center">
                    <div class="avatar m-0 mr-50">
                        <img <?=$border_style?> src="../<?=$user_picture?>" height="36" width="36" alt="user image">
                        <span class="avatar-status-busy"></span>
                    </div>
                    <div class="chat-sidebar-name">
                        <h6 class="mb-0"><?=$user_fullname?> <small class="text-muted">(Bot: <?=$bot_fullname?>) · <?=$mesaj_saati?></small></h6>
                        <span class="text-muted"><?=$bold_start?><?=$icerigi?><?=$bold_end?></span>
                    </div>
                </div>
            </a>
        </li>
        <?php
    }
    
}elseif($_POST['type']=='mesajList'){



function makeImg($s) {
    // @(https?://([-\w\.]+)+(:\d+)?/[\w/_\.%\-+~]+(\.exe|\.mp3|\.pdf|\.rar|\.doc|\.jar|\.ppt|\.xls|\.png|\.jpg|\.jpeg|\.gif|\.mp4|\.avi|\.mkv|\.flv|\.3gp|\.mms|\.sis|\.sisx|\.jad|\.mdi|\.qcp)(\?\S+)?)@
    return preg_replace('@(https?://([-\w\.]+)+(:\d+)?/[\w/_\.%\-+~]+(\.png|\.jpg|\.jpeg|\.gif)(\?\S+)?)@', '<img style="max-width: 50px; height: auto; border-radius: 1%;" src="$1" />', $s);
}

$user1 = $_POST['myuserid'];
$user2 = $_POST['userid'];

$mesajlar = $db->query('SELECT * FROM mesajlar WHERE (gonderen_id='.$user1.' AND alan_id='.$user2.') or (gonderen_id='.$user2.' AND alan_id='.$user1.') ORDER BY id ASC',PDO::FETCH_ASSOC);

$user1row = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$user1}'")->fetch(PDO::FETCH_ASSOC);
$user2row = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$user2}'")->fetch(PDO::FETCH_ASSOC);

// Çark çevirme sayısını hesapla
$carkSayisi = $db->query("SELECT COUNT(*) FROM cark_gecmis WHERE user_id = '{$user2}'")->fetchColumn();

  // $upquery = $db->prepare("UPDATE mesajlar SET okundu =? WHERE alan_id=? AND gonderen_id=?"); 
  // $update = $upquery->execute(array( 1, $user1, $user2)); 

// Hidden inputs for message details
echo '<input type="hidden" name="userpic" value="'.$user1row['user_picture'].'">
<input type="hidden" name="userid" value="'.$user1row['user_id'].'">
<input type="hidden" name="useridx" value="'.$user2row['user_id'].'">
<input type="hidden" name="darlama" value="'.$user2row['user_darlama'].'">
<input type="hidden" name="satisizin" value="'.$user2row['user_satisizin'].'">
<input type="hidden" name="userfullname" value="'.$user1row['user_fullname'].'">
<input type="hidden" name="kullanicifullname" value="'.$user2row['user_fullname'].'">
<input type="hidden" name="usersehir" value="'.$user2row['user_sehir'].'">
<input type="hidden" name="useryas" value="'.$user1row['user_yas'].'">
<input type="hidden" name="kullaniciyas" value="'.$user2row['user_yas'].'">
<input type="hidden" name="kullanicijeton" value="'.$user2row['user_jeton'].'">
<input type="hidden" name="sonaktivite" value="'.date('d.m.Y - H:i:s', $user2row['user_songiris']).'">
<input type="hidden" name="aramapaket" value="'.($user2row['user_call'] == 0 ? 'Hayır' : 'Evet').'">
<input type="hidden" name="onaypaket" value="'.($user2row['user_onay'] == 0 ? 'Hayır' : 'Evet').'">
<input type="hidden" name="carksayisi" value="'.$carkSayisi.'">';



foreach($mesajlar as $mesaj)
{

if($mesaj['gonderen_id']==$user1){ 




   $micerik = makeImg($mesaj['icerik']);


    ?>




                                            <div class="chat">
<!--                                                 <div class="chat-avatar">
                                                    <a class="avatar m-0">
                                                        <img src="../<?=$user1row['user_picture']?>" alt="avatar" height="36" width="36" />
                                                    </a>
                                                </div> -->
                                                <div class="chat-body">
                                                    <div class="chat-message">
                                                        <p><?=$micerik?></p>
                                                        <span class="chat-time"><?=date('H:i',$mesaj['zaman'])?></span>
                                                    </div>
                                                </div>
                                            </div>

<?php }elseif($mesaj['alan_id']==$user1){ 
$micerik = makeImg($mesaj['icerik']);

    ?>




        <div class="chat chat-left">
<!--                                                 <div class="chat-avatar">
                                                    <a class="avatar m-0">
                                                        <img src="../<?=$user2row['user_picture']?>" alt="avatar" height="36" width="36" />
                                                    </a>
                                                </div> -->
                                                <div class="chat-body">
                                                    <div class="chat-message">
                                                        <p><?=$micerik?></p>
                                                        <span class="chat-time"><?=date('H:i',$mesaj['zaman'])?></span>
                                                    </div>
                                                </div>
                                            </div>




<?php 
}
}
}elseif($_POST['type']=='msgsend'){

    $gonderen_id = (int)$_POST['gonderen_id'];   // panelden yazan (muhtemelen bot id)
    $alan_id     = (int)$_POST['userid'];       // kullanıcı id
    $msj         = strip_tags($_POST['msj']);
    $author      = $_COOKIE['author_token'];

    $str = $msj;

    $user1row = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$alan_id}'")->fetch(PDO::FETCH_ASSOC);

    $yas = $user1row['user_yas'];
    $sehir = $user1row['user_sehir'];
    $isimver = explode(" ", $user1row['user_fullname']);
    $isim2 = ucwords(strtolower($isimver[0]));
    $isim = $isim2;

    $find = ['{yas}','{sehir}','{isim}'];
    $replace = compact('yas', 'sehir', 'isim');

    $msj = str_replace($find, $replace, $str);

    if($msj!=""){

        // Panelden atılan mesajı "AI kapalı" olarak işaretle
        $query = $db->prepare("
            INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, author, zaman)
            VALUES (:gonderen_id, :alan_id, :icerik, :ip, :author, :zaman)
        ");

        $insert = $query->execute([
            ':gonderen_id' => $gonderen_id,
            ':alan_id'     => $alan_id,
            ':icerik'      => $msj,
            ':ip'          => "::4",
            ':author'      => $author,
            ':zaman'       => $zaman
        ]);

        $uquery = $db->prepare("UPDATE mesajlar SET okundu =? WHERE alan_id=? AND gonderen_id=?"); 
        $update = $uquery->execute([1, $gonderen_id, $alan_id]); 

        $zquery = $db->prepare("UPDATE kullanicilar SET user_darlama = 0 WHERE user_id = ?");
        $update = $zquery->execute([$alan_id]);

        echo json_encode(["sonuc" => 1]);

    }else{
        echo "boş";
    }
}elseif($_POST['type']=='random_aktif'){

$suan = time();
$suan5dk = time()-300;
$suan30dk = time()-1800;

// ORDER BY RAND() yerine: Daha fazla kayıt çek, PHP'de shuffle yap (çok daha hızlı)
if($_POST['type2']=='aktif'){
    $allRows = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 0 AND user_songiris >= $suan5dk AND user_sehir <> '' AND user_cinsiyet = 'erkek' ORDER BY id DESC LIMIT 50", PDO::FETCH_ASSOC)->fetchAll();
}else if($_POST['type2']=='jetonlu'){
    $allRows = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 0 AND user_jeton > 0 AND user_sehir <> '' AND user_cinsiyet = 'erkek' ORDER BY id DESC LIMIT 50", PDO::FETCH_ASSOC)->fetchAll();
}else if($_POST['type2']=='normal'){
    $allRows = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 0 AND user_songiris >= $suan30dk AND user_sehir <> '' AND user_cinsiyet = 'erkek' ORDER BY id DESC LIMIT 50", PDO::FETCH_ASSOC)->fetchAll();
}

// PHP'de shuffle ve ilk 8'ini al
shuffle($allRows);
$query = array_slice($allRows, 0, 8);

// Rastgele bot seçimi (ORDER BY RAND yerine PHP shuffle)
function randBot(){
    global $db;
    $bots = $db->query("SELECT user_id FROM kullanicilar WHERE user_bot = 1 ORDER BY id DESC LIMIT 20", PDO::FETCH_ASSOC)->fetchAll();
    if(count($bots) > 0){
        return $bots[array_rand($bots)]['user_id'];
    }
    return null;
}

$userbot_id = randBot();

/*$aramaidler = array();*/

     foreach($query as $row){
        $rand = time_ago(date('Y-m-d H:i:s', $row['user_songiris']));
          echo '<a class="list-group-item"> <div class="media"> <div class="media-left pr-1"><span class="avatar avatar-sm avatar-online rounded-circle"><img src="../'.$row['user_picture'].'" alt="avatar"><i></i></span></div> <div class="media-body w-100"> <h6 class="media-heading mb-0">'.$row['user_fullname'].'</h6> <p class="font-small-2 mb-0 text-muted">'.$rand.'</p> </div> 
          <button onclick="aramaGonder('.$userbot_id.','.$row['user_id'].');" type="button" class="btn btn-sm btn-outline-danger round mr-1"><i class="ft-phone"></i></button>
          <button onclick="tekil_mesaj_bot('.$row['user_id'].');" type="button" class="btn btn-sm btn-outline-info round" data-toggle="modal" data-target="#bootstrap"><i class="ft-message-square"></i> Mesaj Yaz</button> </div> </a> ';
          /*$aramaidler[] = "aramaGonder(".$userbot_id.",".$row['user_id'].");";*/
     }


/*echo '<script type="text/javascript">';
echo 'function topluArama(){';

foreach($aramaidler as $veri){
echo "\n";
echo $veri;
echo "\n";

}

echo "}</script>";*/

}elseif($_POST['type']=='tekil_mesaj_bot'){ 

$user_id = $_POST['user_id'];
$mUser = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$user_id}'")->fetch(PDO::FETCH_ASSOC);

// ORDER BY RAND yerine: Daha fazla çek, PHP'de shuffle
$allBots = $db->query("SELECT * FROM kullanicilar WHERE user_bot = 1 AND user_send = 0 ORDER BY id DESC LIMIT 100", PDO::FETCH_ASSOC)->fetchAll();
shuffle($allBots);
$randBot = array_slice($allBots, 0, 35);

    ?>




                                        <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="userinput1">İsim Soyisim</label>
                                                            <input type="text" id="userinput1" class="form-control border-info" name="name" value="<?=$mUser['user_fullname']?>" readonly>
                                                            
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="userinput2">Jeton</label>
                                                            <input type="text" id="userinput2" class="form-control border-info" name="company" value="<?=$mUser['user_jeton']?>" readonly>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="userinput1">Yaş</label>
                                                            <input type="text" id="userinput1" class="form-control border-info" name="name" value="<?=$mUser['user_yas']?>" readonly>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="userinput2">Şehir</label>
                                                            <input type="text" id="userinput2" class="form-control border-info" name="company" value="<?=$mUser['user_sehir']?>" readonly>
                                                        </div>
                                                    </div>
                                                </div>

                                     <fieldset class="form-group form-group-style border-info">
                                        <label for="selectOpt" class="filled">Bot Seç</label>
                                        <select class="form-control input-lg" id="selectOpt">
                                            <option>Bir Kullanıcı Seçin</option>
                                            <?php foreach ($randBot as $veri) { ?>
                                            <option id="userid1" value='<?=$veri['user_id']?>'><?=$veri['user_fullname']?> - Yaş: <?=$veri['user_yas']?></option>
                                            <?php } ?>

                                        </select>
                                    </fieldset>

                                        <fieldset class="form-group position-relative">
                                        <textarea class="form-control border-info" id="mesicerik" rows="3" placeholder="Göndermek istediğiniz mesajı girin!"></textarea>
                                    </fieldset>



<?php }elseif($_POST['type']=='tekil_mesaj_gonder'){ 

$gonderen_id = $_POST['gonderen'];
$alan_id = $_POST['alan'];
$msj = strip_tags($_POST['msj']);

$str = $msj;

$user1row = $db->query("SELECT * FROM kullanicilar WHERE user_id = '{$alan_id}'")->fetch(PDO::FETCH_ASSOC);

$isim = explode(" ", $user1row['user_fullname'])[0]; // İlk isim
$yas = $user1row['user_yas'];
$sehir = $user1row['user_sehir'];
$cinsiyet = $user1row['user_cinsiyet'];

$find = ['{isim}','{yas}','{sehir}','{cinsiyet}'];
$replace = compact('isim', 'yas', 'sehir', 'cinsiyet');

$msj = str_replace($find, $replace, $str);


    $query = $db->prepare("INSERT INTO mesajlar (gonderen_id, alan_id, icerik, ip, zaman) VALUES (:gonderen_id, :alan_id, :icerik, :ip, :zaman)");
    $insert = $query->execute(array(':gonderen_id'=>$gonderen_id,':alan_id'=>$alan_id,':icerik'=>$msj,':ip'=>$ip,':zaman'=>$zaman));

    if($insert){
    $array = array("sonuc" => 1);
    echo json_encode($array); 
    }

}elseif($_GET['type']=='userSearch'){ 

$str = $_GET['q'];

if(isset($str)){

$query = $db->query("SELECT * FROM kullanicilar WHERE user_fullname LIKE '%$str%' ORDER BY id DESC LIMIT 50", PDO::FETCH_ASSOC);
if ( $query->rowCount() ){ 
    ?>

<?php foreach($query as $veri): ?>
                                            <tr>
                                                <td class="text-truncate p-2">
                                                    <span class="avatar avatar-xs">
                                                        <img class="box-shadow-2" src="../<?=$veri['user_picture']?>" alt="avatar">
                                                    </span>
                                                    <span><?=$veri['user_fullname']?></span>
                                                </td>
                                                <td class="text-truncate p-2">
                                                    <i class="la la-dot-circle-o success font-medium-1"></i><?=$veri['user_email']?>
                                                </td>
                                                <td class="text-truncate p-2">
                                                    Yaş: <b><?=$veri['user_yas']?></b>, <?=$veri['user_sehir']?>
                                                </td>
                                                <td class="text-truncate p-2">
                                                    <?=date('d.m.Y - H:i:s',$veri['user_songiris'])?>
                                                </td>
                                                
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-outline-warning round"><?=$veri['user_jeton']?> Jeton</button>
                                                </td>

                                                <td class="text-truncate p-2">
                                                    <?=$veri['user_ban'] ? '<span class="badge badge-danger">Banned</span>' : '<span class="badge badge-success">Aktif</span>'?>    
                                                </td>

                                                <td>
                                                   
                        <button class="btn btn-sm btn-info round dropdown-toggle" id="btnGroupDrop1" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="ft-settings icon-left"></i> İşlemler</button>
                        <div class="dropdown-menu" aria-labelledby="btnGroupDrop1"><a class="dropdown-item" onclick="botu_sil(<?=$veri['user_id']?>);" href="javascript:void(0)">Botu Sil</a></div>
                 
                                                </td>
                                               
                                            </tr>
                                            <?php endforeach; ?>


<?php 

}



}
}elseif($_POST['type']=='satisIzniToplu'){

    // Tüm user_satisizin = 0 olanları 1 yap
    $updateQuery = $db->prepare("UPDATE kullanicilar SET user_satisizin = 1 WHERE user_satisizin = 0");
    $updateQuery->execute();
    
    $etkilenenSayisi = $updateQuery->rowCount();
    
    $array = array("result" => "1", "count" => $etkilenenSayisi);
    echo json_encode($array);

}elseif($_POST['type']=='jetonUpdate'){ 


  $user_id = $_POST['user_id'];
  $kredi = $_POST['kredi'];

$query = $db->prepare("UPDATE kullanicilar SET
user_jeton = :user_jeton WHERE user_id = :user_id");
$update = $query->execute(array(
"user_jeton" => $kredi,
"user_id" => $user_id
));

if($update){
  $array = array("result" => "1");
  echo json_encode($array);
}else{
    $array = array("result" => "1");
  echo json_encode($array);
}



}elseif($_POST['type']=='sikayetUpdate'){ 


  $sikayet_id = $_POST['sikayet_id'];
  $islemType = $_POST['islemType'];

$sikayetRow = $db->query("SELECT * FROM sikayetler WHERE id = '{$sikayet_id}'")->fetch(PDO::FETCH_ASSOC);

if($islemType==1){

$edilen = $sikayetRow['u_to'];

$query = $db->prepare("UPDATE kullanicilar SET
user_ban = :user_ban, user_picture = :user_picture WHERE user_id = :user_id");
$update = $query->execute(array(
"user_ban" => time(),
"user_picture" => "assets/img/no-avatar.png",
"user_id" => $edilen
));

$query = $db->prepare("UPDATE sikayetler SET
status = :status WHERE id = :id");
$update = $query->execute(array(
"status" => "2",
"id" => $sikayet_id
));


}elseif($islemType==2){

$edilen = $sikayetRow['u_to'];

$query = $db->prepare("UPDATE kullanicilar SET
user_picture = :user_picture WHERE user_id = :user_id");
$update = $query->execute(array(
"user_picture" => "assets/img/no-avatar.png",
"user_id" => $edilen
));

$query = $db->prepare("UPDATE sikayetler SET
status = :status WHERE id = :id");
$update = $query->execute(array(
"status" => "3",
"id" => $sikayet_id
));

}elseif($islemType==3){

$query = $db->prepare("UPDATE sikayetler SET
status = :status WHERE id = :id");
$update = $query->execute(array(
"status" => "1",
"id" => $sikayet_id
));


}


if($update){
  $array = array("result" => "1");
  echo json_encode($array);
}else{
    $array = array("result" => "0");
  echo json_encode($array);
}



}elseif($_POST['type']=='playOnayla'){
    // Play Store değerlendirme başvurusunu onayla ve 5 jeton ekle
    
    $basvuru_id = intval($_POST['basvuru_id']);
    $user_id = intval($_POST['user_id']);
    
    // Başvuruyu kontrol et
    $basvuru = $db->query("SELECT * FROM play_degerlendirme WHERE id = $basvuru_id AND user_id = $user_id")->fetch(PDO::FETCH_ASSOC);
    
    if (!$basvuru) {
        $array = array("result" => "0", "message" => "Başvuru bulunamadı!");
        echo json_encode($array);
        exit();
    }
    
    if ($basvuru['durum'] == 1) {
        $array = array("result" => "0", "message" => "Bu başvuru zaten onaylanmış!");
        echo json_encode($array);
        exit();
    }
    
    // Kullanıcıya 5 jeton ekle (sadece bir kere eklenmemişse)
    if ($basvuru['jeton_verildi'] == 0) {
        $query = $db->prepare("UPDATE kullanicilar SET user_jeton = user_jeton + 5 WHERE user_id = ?");
        $jetonUpdate = $query->execute([$user_id]);
    }
    
    // Başvuruyu onayla
    $query = $db->prepare("UPDATE play_degerlendirme SET 
        durum = 1, 
        onay_tarihi = ?, 
        jeton_verildi = 1 
        WHERE id = ?");
    $update = $query->execute([time(), $basvuru_id]);
    
    if ($update) {
        $array = array("result" => "1", "message" => "Başvuru onaylandı ve kullanıcıya 5 jeton eklendi!");
        echo json_encode($array);
    } else {
        $array = array("result" => "0", "message" => "Bir hata oluştu!");
        echo json_encode($array);
    }

}elseif($_POST['type']=='playReddet'){
    // Play Store değerlendirme başvurusunu reddet
    
    $basvuru_id = intval($_POST['basvuru_id']);
    $user_id = intval($_POST['user_id']);
    $admin_notu = $_POST['admin_notu'] ?? '5 Yıldız seçtikten sonra alttaki Deneyiminizi anlatın yazan yere en az 10 kelimelik güzel bir yorum yapıp sağ üstteki yayınla butonuna dokunmanız ve sonrasında ekran görüntüsü atmanız gerekmektedir.';
    
    // Başvuruyu kontrol et
    $basvuru = $db->query("SELECT * FROM play_degerlendirme WHERE id = $basvuru_id AND user_id = $user_id")->fetch(PDO::FETCH_ASSOC);
    
    if (!$basvuru) {
        $array = array("result" => "0", "message" => "Başvuru bulunamadı!");
        echo json_encode($array);
        exit();
    }
    
    // Başvuruyu reddet (red tarihini kaydet)
    $query = $db->prepare("UPDATE play_degerlendirme SET 
        durum = 2, 
        admin_notu = ?,
        onay_tarihi = ?,
        jeton_verildi = 0
        WHERE id = ?");
    $update = $query->execute([$admin_notu, time(), $basvuru_id]);
    
    if ($update) {
        $array = array("result" => "1", "message" => "Başvuru reddedildi!");
        echo json_encode($array);
    } else {
        $array = array("result" => "0", "message" => "Bir hata oluştu!");
        echo json_encode($array);
    }

}


?>