<?php
$path = "../../";
include("../../map.php");

// --- 1. GÜVENLİK VE DEĞİŞKEN TANIMLARI ---
// XSS Koruması için yardımcı fonksiyon
function clean($data) {
    return htmlspecialchars($data ?? '', ENT_QUOTES, 'UTF-8');
}

// Gelen verileri temizle
$formMode = isset($_GET["form"]) && $_GET["form"] == "true";
$ne       = clean($_GET["ne"] ?? '');
$islem    = clean($_GET["islem"] ?? '');
$durum    = clean($_GET["durum"] ?? '');
$show     = clean($_GET["show"] ?? '');
$sayfa    = clean($_GET["sayfa"] ?? '');
$grupID   = clean($_GET["grupID"] ?? '');
$s13      = clean($_GET["s13"] ?? '');
$id       = clean($_GET["id"] ?? '');
$key      = clean($_GET["key"] ?? '');

// Tarih filtrelerinin gösterileceği modüller
$dateModules = ['request', 'siparisler', 'tahsilat', 'service', 'gorev', 'yorum', 'fatura', 'kasa', 'cek', 'senet'];
$showDateFilter = in_array($islem, $dateModules);

// Tarih varsayılanları
$ts1_val = clean($_GET["ts1"] ?? date('Y-m-d', strtotime('-7 days')));
$ts2_val = clean($_GET["ts2"] ?? date('Y-m-d'));

// --- 2. FORM GÖRÜNÜMÜ (MODAL İÇERİĞİ) ---
if ($formMode) {
?>
    <style>
        .filter-card { padding: 15px; }
        .filter-row { margin-bottom: 10px; }
        .input-group-text { background-color: #f8f9fa; color: #555; }
        .form-control:focus { box-shadow: none; border-color: #f0ad4e; }
    </style>

    <form class="filter-card" action="?" method="get">
        <input type="hidden" name="ne" value="<?php echo $ne; ?>">
        <input type="hidden" name="islem" value="<?php echo $islem; ?>">
        <input type="hidden" name="show" value="<?php echo $show; ?>">
        <input type="hidden" name="sayfa" value="<?php echo $sayfa; ?>">
        <input type="hidden" name="id" value="<?php echo $id; ?>">
        <?php if(!$showDateFilter && isset($_GET["drm"])) { ?>
            <input type="hidden" name="drm" value="<?php echo clean($_GET["drm"]); ?>">
        <?php } ?>

        <div class="row">
            <div class="col-md-12 mb-3">
                <div class="input-group">
                    <span class="input-group-addon input-group-text"><i class="fa fa-search"></i></span>
                    <input type="text" class="form-control input-lg" name="key" value="<?php echo $key; ?>" placeholder="<?php echo ctranslate('Kelime ile ara...'); ?>">
                </div>
            </div>

            <?php if ($showDateFilter) { ?>
                <div class="col-md-4 col-sm-6 mb-2">
                    <label class="text-muted small"><?php echo ctranslate("Başlangıç"); ?></label>
                    <input type="date" class="form-control" name="ts1" id="fts1" value="<?php echo $ts1_val; ?>">
                </div>
                <div class="col-md-4 col-sm-6 mb-2">
                    <label class="text-muted small"><?php echo ctranslate("Bitiş"); ?></label>
                    <input type="date" class="form-control" name="ts2" id="fts2" value="<?php echo $ts2_val; ?>">
                </div>
                <div class="col-md-4 col-sm-12 mb-2">
                    <label class="text-muted small"><?php echo ctranslate("Hızlı Seçim"); ?></label>
                    <select id="when" class="form-control">
                        <option value=""><?php echo ctranslate("Zaman Aralığı"); ?></option>
                        <option value="<?php echo date('Y-m-d', strtotime('-30 days')); ?>"><?php echo ctranslate("Son 30 Gün"); ?></option>
                        <option value="<?php echo date("Y-m-d"); ?>"><?php echo ctranslate("Bugün"); ?></option>
                        <option value="<?php echo $haftabasi; ?>"><?php echo ctranslate("Bu Hafta"); ?></option>
                        <option value="<?php echo $aybasi; ?>"><?php echo ctranslate("Bu Ay"); ?></option>
                        <option value="<?php echo $yilbasi; ?>"><?php echo ctranslate("Bu Yıl"); ?></option>
                        <option value="<?php echo date('Y-m-d', strtotime($yilbasi . ' -1 years')); ?>"><?php echo date('Y', strtotime('-1 years')); ?></option>
                    </select>
                </div>
            <?php } ?>

            <?php if ($islem == "request") { ?>
                <div class="col-md-12 mb-2">
                    <select name="fID" class="form-control">
                        <option value=""><?php echo ctranslate("Tüm Formlar"); ?></option>
                        <?php 
                        $sqlr = mysqli_query($conn, "SELECT DISTINCT t1, s1 FROM t2 WHERE ne='request' $luye"); 
                        while ($rsr = mysqli_fetch_assoc($sqlr)) { 
                            $selected = (isset($_GET["fID"]) && $_GET["fID"] == $rsr["s1"]) ? "selected" : "";
                            echo "<option value='{$rsr["s1"]}' $selected>{$rsr["t1"]}</option>";
                        } 
                        ?>
                    </select>
                </div>
            <?php } ?>

            <?php if ($islem == "siparisler") { ?>
                <div class="col-md-6 mb-2">
                    <select name="t5" class="form-control">
                        <option value=""><?php echo ctranslate("Ödeme Yöntemi"); ?></option>
                        <option value="PayTr"><?php echo translate("+#PayTr"); ?></option>
                        <option value="Pos"><?php echo translate("+#Pos"); ?></option>
                        <option value="Havale"><?php echo translate("+#Havale"); ?></option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="s4" class="form-control">
                        <option value=""><?php echo ctranslate("Sipariş Durumu"); ?></option>
                        <option value="0"><i class="fa fa-pause"></i> <?php echo translate("+#Onay Bekliyor"); ?></option>
                        <option value="1" <?php echo ($s4 == 1) ? 'selected' : ''; ?>><?php echo translate("+#Onaylandı"); ?></option>
                        <?php if ($f3 > 1) { ?>
                            <option value="3" <?php echo ($s4 == 3) ? 'selected' : ''; ?>><?php echo translate("+#Sevkiyatta"); ?></option>
                        <?php } ?>
                        <option value="4" <?php echo ($s4 == 4) ? 'selected' : ''; ?>><?php echo translate("+#Teslim Edildi"); ?></option>
                        <option value="2" <?php echo ($s4 == 2) ? 'selected' : ''; ?>><?php echo translate("+#İptal"); ?></option>
                        <?php if ($module["order_return"] > 1) { ?>
                            <option value="5" <?php echo ($s4 == 5) ? 'selected' : ''; ?>><?php echo translate("+#İade"); ?></option>
                        <?php } ?>
                    </select>
                </div>
            <?php } ?>

            <?php if ($islem == "kasa" || $islem == "nakit_akis") { ?>
                <div class="col-md-12 mb-2">
                    <select name="drm" class="form-control">
                        <option value=""><?php echo ctranslate("Hareket Tipi"); ?></option>
                        <?php if ($islem == "kasa") { ?>
                            <option value="gelir"><?php echo ctranslate("Gelir"); ?></option>
                            <option value="gider"><?php echo ctranslate("Gider"); ?></option>
                        <?php } else { ?>
                            <option value="alacak"><?php echo ctranslate("Alacak"); ?></option>
                            <option value="borc"><?php echo ctranslate("Borç"); ?></option>
                        <?php } ?>
                    </select>
                </div>
            <?php } ?>

            <?php if ($islem == "kayitlar") { ?>
                <div class="col-md-6 mb-2">
                    <select name="s13" class="form-control">
                        <option value=""><?php echo ctranslate("Durum Seçiniz"); ?></option>
                        <option value="0">[0] <?php echo ctranslate("#Pasif"); ?></option>
                        <option value="1">[1] <?php echo ctranslate("#Aktif"); ?></option>
                        <option value="3">[3] <?php echo ctranslate("#Tedarik Edilemiyor"); ?></option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="grupID" class="form-control" id="s1">
                        <option value=""><?php echo ctranslate("Tüm Kategoriler"); ?></option>
                        <?php 
                        $sqlx = mysqli_query($conn, "SELECT * FROM kategoriler WHERE ne='ukategori' ORDER BY sira ASC"); 
                        while ($rsx = mysqli_fetch_assoc($sqlx)) {
                            echo "<option value='{$rsx["Cat_ID"]}'>+ {$rsx["Cat_" . $_SESSION['lang']]}</option>";
                            $sqly = mysqli_query($conn, "SELECT * FROM kategoriler WHERE ne='ualt_kategori' AND c1='" . $rsx["Cat_ID"] . "' ORDER BY sira ASC");
                            while ($rsy = mysqli_fetch_assoc($sqly)) {
                                echo "<option value='{$rsy["Cat_ID"]}'>&nbsp;&nbsp;- {$rsy["Cat_" . $_SESSION['lang']]}</option>";
                            }
                        } 
                        ?>
                    </select>
                </div>
                <?php if ($e5 >= 1) { ?>
                    <div class="col-md-6 mb-2">
                        <div class="input-group">
                            <span class="input-group-addon input-group-text small">Min ₺</span>
                            <input name="min_pb1" class="form-control" type="number" step="0.01">
                        </div>
                    </div>
                    <div class="col-md-6 mb-2">
                        <div class="input-group">
                            <span class="input-group-addon input-group-text small">Max ₺</span>
                            <input name="max_pb1" class="form-control" type="number" step="0.01">
                        </div>
                    </div>
                <?php } ?>
                <?php if ($f7 >= 1) { ?>
                    <div class="col-md-6 mb-2">
                        <div class="input-group">
                            <span class="input-group-addon input-group-text small">Min Stok</span>
                            <input name="min_s5" class="form-control" type="number">
                        </div>
                    </div>
                    <div class="col-md-6 mb-2">
                        <div class="input-group">
                            <span class="input-group-addon input-group-text small">Max Stok</span>
                            <input name="max_s5" class="form-control" type="number">
                        </div>
                    </div>
                <?php } ?>
            <?php } ?>

            <?php if ($islem == "uyeler") { ?>
                <div class="col-md-6 mb-2">
                    <select name="s13" class="form-control">
                        <option value=""><?php echo ctranslate("Üyelik Durumu"); ?></option>
                        <option value="0"><?php echo ctranslate("#Pasif"); ?></option>
                        <option value="1"><?php echo ctranslate("#Aktif"); ?></option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="grupID" class="form-control">
                        <option value=""><?php echo ctranslate("Üye Grubu"); ?></option>
                        <?php 
                        $sqlx = mysqli_query($conn, "SELECT * FROM kategoriler WHERE ne='kkategori' ORDER BY sira ASC"); 
                        while ($rsx = mysqli_fetch_assoc($sqlx)) {
                            echo "<option value='{$rsx["Cat_ID"]}'>{$rsx["Cat_" . $_SESSION['lang']]}</option>";
                        } 
                        ?>
                    </select>
                </div>
            <?php } ?>

            <div class="col-md-12 text-right mt-3">
                <hr>
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal"><?php echo ctranslate("Vazgeç"); ?></button>
                <button type="submit" class="btn btn-warning">
                    <i class="fas fa-filter"></i> <?php echo ctranslate("Filtrele"); ?>
                </button>
            </div>
        </div>
    </form>

    <script>
    // Tarih Aralığı Otomatik Doldurma
    jQuery('#when').on('change', function() {
        var w = jQuery(this).val();
        if (w !== "") {
            jQuery('#fts1').val(w);
            jQuery('#fts2').val('<?php echo date("Y-m-d"); ?>');
        }
    });

    // Başlangıç tarihi değişirse bitiş tarihini bugün yap (Opsiyonel UX)
    jQuery('#fts1').on('change', function() {
        if (jQuery('#fts2').val() == "") {
            jQuery('#fts2').val('<?php echo date("Y-m-d"); ?>');
        }
    });
    </script>

<?php } else { ?>
    <?php
    // URL Oluşturma
    $params = http_build_query([
        'ne' => $ne,
        'islem' => $islem,
        'durum' => $durum,
        'show' => $show,
        'grupID' => $grupID,
        's13' => $s13,
        'form' => 'true'
    ]);
    ?>
    <a class="mb-1 mt-1 mr-1 btn btn-warning filter_btn majx" 
       data-toggle="modal" 
       data-target="#ajaxModal" 
       data-width="50%" 
       data-url="modules/public/filter.php?<?php echo $params; ?>" 
       data-title="<?php echo ctranslate("Detaylı Filtrele"); ?>">
        <i class="fa fa-filter" aria-hidden="true"></i>
    </a>
<?php } ?>