<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(0);
$path="../../";
include("../../map.php");
include("../../scripts.php");
include("../../secure.php");
$filename = findDirectoryPath("deppo")."/ranking.json";
// JSON dosyasını oku
function getReport() {
    global $filename;
    if (!file_exists($filename)) return [];
    return json_decode(file_get_contents($filename), true) ?: [];
}
// JSON dosyasına yaz
function saveData($data) {
    global $filename;
    file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = getReport();
    if (empty($_POST['delete']) && empty($_POST['update'])) { // Yeni kayıt ekleme
        $_SESSION['ilk_tarih'] = $_POST['tarih'];
        $kelime = trim($_POST['kelime']);
        $rekabet = str_replace(".", "", trim($_POST['rekabet']));
        $sira = trim($_POST['sira'] ?? '0');  // Eğer boşsa '0' yap
        $tarih = trim($_POST['tarih'] ?? '0'); // Eğer boşsa '0' yap
        $arama_motoru = trim($_POST['arama_motoru']);
        // Aynı kelime ve tarih varsa ekleme yapma
        foreach ($data as $entry) {
            if ($entry['kelime'] === $kelime && $entry['tarih'] === $tarih) {
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit;
            }
        }
        $data[] = [
            'kelime' => $kelime,
            'arama_motoru' => $arama_motoru,
            'rekabet' => $rekabet,
            'sira' => $sira,
            'tarih' => $tarih
        ];
    } elseif (isset($_POST['delete'])) { // Silme işlemi
        $data = array_filter($data, function ($item) {
            return !($item['kelime'] === $_POST['delete'] && $item['tarih'] === $_POST['delete_date']);
        });
    } elseif (isset($_POST['update'])) { // Update işlemi
        foreach ($data as &$entry) {
            if ($entry['kelime'] === $_POST['kelime'] && $entry['tarih'] === $_POST['tarih']) {
                $entry['rekabet'] = str_replace(".", "", trim($_POST['rekabet']));
                $entry['sira'] = $_POST['sira'];
            }
        }
        saveData($data);
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    saveData($data);
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}
if (!isset($_SESSION['ilk_tarih'])) {
    $_SESSION['ilk_tarih'] = date('Y-m-d');
}
$data = getReport();
usort($data, fn($a, $b) => strtotime($b['tarih']) - strtotime($a['tarih'])); // En yeni tarih önce
// GET ile gelen ay bilgisini session'a kaydet
if (isset($_GET["month"])) {
    $_SESSION["month"] = $_GET["month"];
}
// Eğer GET boşsa, varsayılan olarak en yeni kayıtlar gösterilir
if (!isset($_SESSION["month"]) || $_SESSION["month"] === "") {
    $_SESSION["month"] = "latest";
}
// Tüm verilerden benzersiz ayları al (YYYY-MM formatında)
$aylar = array_unique(array_map(fn($entry) => date("m-Y", strtotime($entry['tarih'])), $data));
rsort($aylar); // En yeni ayı en üste getir
$latestData = [];
foreach ($data as $entry) {
    $entryMonth = date("m", strtotime($entry['tarih'])); // Verinin ay bilgisini al
    if ($_SESSION["month"] === "latest") {
        // En yeni olanını al
        if (!isset($latestData[$entry['kelime']])) {
            $latestData[$entry['kelime']] = $entry;
        }
    } else {
        // Belirtilen aya ait verileri al
        if ($entryMonth == $_SESSION["month"]) {
            $latestData[] = $entry;
        }
    }
}$tags=explode(",",tanim("tags","n1",0));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Seo Rapor</title>
</head>
<style>
    td {position: relative;}
    td a{position: absolute; top: 14px; right: 12px;}
</style>
<body>
    <div class="qmodal">
        <div class="qmodal-content">
            <div class="alert alert-warning" id="result" style="display:none;"></div>
            <!-- Header with Action Buttons -->
            <div class="qmodal-header">
                <div class="header-title">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="?"><i class="fa fa-home"></i></a></li>
                            <li class="breadcrumb-item active" aria-current="page">Seo Rapor</li>
                        </ol>
                    </nav>
                </div>
                <button type="button" class="btn btn-warning" onclick="location.href='?'"><i class="fas fa-home"></i></button>
                <form class="msa" action="?" method="get" id="getdata">
                    <select name="tag" class="msa" style="height: 34px !important;width:150px;" onchange="this.form.submit()">
                      <option value="">Update Ranking</option>
                      <optgroup label="Tags">
                        <?php foreach($tags as $tag){ $i++; ?>
                          <option value="<?php echo str_replace("{city} ","",$tag); ?>"><?php echo  str_replace("{city} ","",$tag); ?></option>
                      <?php } ?>
                  </optgroup>
                  <optgroup label="Report Keys">
                    <?php
                    $kelimeler = [];
                    foreach ($data as $entry) {
					$kelimeler[$entry['kelime']] = true; // Benzersiz kelimeyi sakla
				}
				foreach (array_keys($kelimeler) as $kelime){?>
					<option value="<?= htmlspecialchars($kelime) ?>" class="<?= ($_SESSION[md5(htmlspecialchars($kelime))] == "true") ? 'bg-success' : '' ?>"><?= htmlspecialchars($kelime) ?></option>
				<?php } ?>
			</optgroup>
        </select>
        <input type="hidden" name="etag" value="<?= md5(htmlspecialchars($entry['kelime'])) ?>">
    </form>
    <select name="month" onchange="self.location.href=this.options[this.selectedIndex].value;">
     <option value="?month=latest" <?= $_SESSION["month"] === "latest" ? 'selected' : '' ?>>Filtrele</option>
     <?php foreach ($aylar as $ay):
		list($month, $year) = explode("-", $ay); // Ay ve yılı ayır
		?>
		<option value="?month=<?= $month ?>" <?= $_SESSION["month"] === $month ? 'selected' : '' ?>>
			<?= aylar($month)." ".$year?>
		</option>
	<?php endforeach; ?>
	</select>
    <button type="button" class="btn btn-danger" onclick="location.href='?ne=<?php echo $_GET["ne"];?>&islem=<?php echo $_GET["islem"];?>&durum=supur'"><i class="fas fa-trash"></i></button>
    <button type="button" class="btn btn-warning mfrm cp" data-toggle="modal" data-target="#myModal" data-title="Rapor" data-url="<?php echo $weburl?>/ranking"><i class="fas fa-chart-line"></i></button>
	<p id="seoText" style="display:none;">Merhaba, <?php echo $weburl?> alan adına ait aylık SEO raporunuz güncellenmiştir. Raporunuzu <?php echo $weburl?>/ranking adresinden görüntüleyebilirsiniz. Verilerin tahmini olduğunu ve Google sonuçlarının konum ile kullanıcı geçmişine bağlı olarak değişiklik gösterebileceğini lütfen unutmayınız.</p>
	<button type="button" class="btn btn-warning cp" onclick="copyToClipboard('#seoText')"><i class="fas fa-copy"></i></button>
  </div>
  <!-- Left Tab Menu -->
  <div class="v8-columns">
    <!-- Content Area -->
    <div class="" ts1="<?php echo dtarih($rs["ts1"],"gg ka yy time");?>" ts2="<?php echo dtarih($rs["ts2"],"gg ka yy time");?>" ts3="<?php echo dtarih($rs["ts3"],"gg ka yy time");?>">
        <form method="POST" class="mb-3">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <td><input type="text" list="tags" name="kelime" placeholder="Kelime" class="form-control" required>
<datalist id="tags">
<?php foreach($tags as $tag){ $i++; ?>
                          <option value="<?php echo str_replace("{city} ","",$tag); ?>"><?php echo  str_replace("{city} ","",$tag); ?></option>
                      <?php } ?>
</datalist>
</td>
                        <td style="width:15%">
                            <select name="arama_motoru" class="form-control">
                                <option value="Google">Google</option>
                                <option value="Bing">Bing</option>
                                <option value="Yandex">Yandex</option>
                            </select>
                        </td>
                        <td style="width:15%"><input type="text" name="rekabet" placeholder="Rekabet" class="form-control" required></td>
                        <td style="width:10%"><input type="number" name="sira" placeholder="Sıra" class="form-control" required></td>
                        <td style="width:15%"><input type="date" name="tarih" class="form-control" value="<?= $_SESSION['ilk_tarih'] ?>" required></td>
                        <td style="width:10%"><button type="submit" class="btn btn-success">Ekle</button></td>
                    </tr>
                </tbody>
            </table>
        </form>
        <table class="table table-bordered">
           <tr>
              <th>Kelime</th>
              <th style="width:15%">Arama Motoru</th>
              <th style="width:15%">Rekabet</th>
              <th style="width:10%">Sıra</th>
              <th style="width:15%">Tarih</th>
              <th style="width:10%">İşlem</th>
          </tr>
          <?php foreach ($latestData as $entry): ?>
             <tr class="<?= ($_SESSION[md5(htmlspecialchars($entry['kelime']))] == "true") ? 'bg-success' : '' ?>">
                 <form method="POST">
					<input type="hidden" name="update" value="<?= base64_encode($entry['kelime'].$entry['tarih']) ?>">
                    <td><input type="text" class="form-control" name="kelime" value="<?= htmlspecialchars($entry['kelime']) ?>"> <a href="?tag=<?= htmlspecialchars($entry['kelime']) ?>&etag=<?= md5(htmlspecialchars($entry['kelime'])) ?>" class="btn btn-info"><i class="fab fa-searchengin"></i></a></td>
                    <td><input type="text" class="form-control" name="arama_motoru" value="<?= htmlspecialchars($entry['arama_motoru']) ?>"></td>
                    <td><input type="text" class="form-control" name="rekabet" value="<?= number_format($entry['rekabet'], 0, ',', '.') ?>"></td>
                    <td><input type="number" class="form-control" name="sira" value="<?= htmlspecialchars($entry['sira']) ?>"></td>
                    <td><input type="date" class="form-control" name="tarih" value="<?= htmlspecialchars($entry['tarih']) ?>"></td>
                    <td>
                        <button type="submit" class="btn btn-warning"><i class="fas fa-refresh"></i></button>
                    </form>
                    <form method="POST" style="display:inline;">
                       <input type="hidden" name="delete" value="<?= htmlspecialchars($entry['kelime']) ?>">
                       <input type="hidden" name="delete_date" value="<?= htmlspecialchars($entry['tarih']) ?>">
                       <button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i></button>
                   </form>
               </td>
           </tr>
       <?php endforeach; ?>
   </table>
</div>
</div>
</body>
<script>
    function editKeyword(kelime, aramaMotoru, rekabet, sira, tarih) {
        let newKelime = prompt("Yeni Kelime:", kelime);
        if (!newKelime) return;
        let newAramaMotoru = prompt("Yeni Arama Motoru (Google/Bing/Yandex):", aramaMotoru);
        if (!newAramaMotoru) return;
        let newRekabet = prompt("Yeni Rekabet:", rekabet);
        if (!newRekabet) return;
        let newSira = prompt("Yeni Sıra:", sira);
        if (!newSira) return;
        let newTarih = prompt("Yeni Tarih (YYYY-MM-DD):", tarih);
        if (!newTarih) return;
        let form = document.createElement("form");
        form.method = "POST";
        form.innerHTML = `
                <input type="hidden" name="edit" value="${kelime}">
                <input type="hidden" name="new_kelime" value="${newKelime}">
                <input type="hidden" name="new_arama_motoru" value="${newAramaMotoru}">
                <input type="hidden" name="new_rekabet" value="${newRekabet}">
                <input type="hidden" name="new_sira" value="${newSira}">
                <input type="hidden" name="new_tarih" value="${newTarih}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
</script>
<?php echo $footer?>
</html>
<?php
//-----------------------------------------------------> Ekle
if($_GET["tag"]<>""){
	$_SESSION[$_GET["etag"]]="true";
	$url = "https://index.crmplus.com.tr/api?getdata=" . base64_encode(str_replace('www.', '', $_SERVER['HTTP_HOST']) . "," . $_GET["tag"]);
	$response = file_get_contents($url);
	if ($response === false) { echo "Veri alınırken bir hata oluştu."; exit; }
	$data = json_decode($response, true);

	if ($data['kelime']){
		$jsonData = getReport();
		$jsonData[] = [ 'kelime' => $data['kelime'], 'arama_motoru' => 'Google', 'rekabet' => $data['rekabet'], 'sira' => max(0, $data['sira']), 'tarih' => date('Y-m-d') ];
		saveData($jsonData);
		echo location("?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."",self,500,1);
	}else{
		echo $response;
	}
}elseif($_GET["durum"]=="multiupdate"){
	
}elseif($_GET["durum"]=="supur"){
  unlink($filename);
  echo location("?ne=".$_GET["ne"]."&islem=".$_GET["islem"]."",self,500,1);
}
?>