<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi(['hesap_yonetimi', 'raporlar']);

$sayfa_baslik = __("cash_expense_receipts");
$paraBirimi = getParaBirimiSembolu();

// Düzenleme işlemi
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['duzenle'])) {
    if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = __("invalid_form_submission");
        header("Location: kasa_gider_makbuzlari.php");
        exit();
    }

    $hareket_id = filter_input(INPUT_POST, 'hareket_id', FILTER_VALIDATE_INT);
    $aciklama = temizle($_POST['aciklama']);
    $tutar = filter_var(str_replace(',', '.', $_POST['tutar'] ?? '0'), FILTER_VALIDATE_FLOAT);
    $tarih = temizle($_POST['tarih']);

    if ($hareket_id && $aciklama && $tutar > 0 && $tarih) {
        try {
            // Eski değerleri al
            $stmt = $db->prepare("SELECT * FROM hesap_hareketleri WHERE id = ? AND sirket_id = ? AND tur = 'cikis'");
            $stmt->execute([$hareket_id, $_SESSION['aktif_sirket_id']]);
            $eski_hareket = $stmt->fetch();

            if ($eski_hareket) {
                // Eski tutarı hesaba geri ekle
                $stmt = $db->prepare("UPDATE hesaplar SET bakiye = bakiye + ? WHERE id = ?");
                $stmt->execute([$eski_hareket['tutar'], $eski_hareket['hesap_id']]);

                // Yeni tutarı hesaptan düş
                $stmt = $db->prepare("UPDATE hesaplar SET bakiye = bakiye - ? WHERE id = ?");
                $stmt->execute([$tutar, $eski_hareket['hesap_id']]);

                // Hareketi güncelle
                $stmt = $db->prepare("UPDATE hesap_hareketleri SET aciklama = ?, tutar = ?, tarih = ? WHERE id = ?");
                $stmt->execute([$aciklama, $tutar, $tarih, $hareket_id]);

                // Log kaydı
                sistem_log_ekle($db, 'guncelle', 'hesap_hareketleri', $hareket_id, $eski_hareket, [
                    'aciklama' => $aciklama,
                    'tutar' => $tutar,
                    'tarih' => $tarih
                ], __('cash_expense_receipt_updated'));
                $_SESSION['basari'] = __("cash_expense_receipt_updated_successfully");
            } else {
                $_SESSION['hata'] = __("record_to_update_not_found");
            }
        } catch (Exception $e) {
            $_SESSION['hata'] = __("database_error") . ": " . $e->getMessage();
        }
    } else {
        $_SESSION['hata'] = __("please_fill_all_fields_correctly");
    }
    header("Location: kasa_gider_makbuzlari.php");
    exit();
}

// Silme işlemi
if (isset($_GET['sil']) && isset($_GET['csrf_token'])) {
    if (!csrf_token_dogrula($_GET['csrf_token'])) {
        $_SESSION['hata'] = __("invalid_security_key");
        header("Location: kasa_gider_makbuzlari.php");
        exit();
    }

    $hareket_id = filter_input(INPUT_GET, 'sil', FILTER_VALIDATE_INT);
    if ($hareket_id) {
        try {
            // Silinecek kaydı al
            $stmt = $db->prepare("SELECT * FROM hesap_hareketleri WHERE id = ? AND sirket_id = ? AND tur = 'cikis'");
            $stmt->execute([$hareket_id, $_SESSION['aktif_sirket_id']]);
            $hareket = $stmt->fetch();

            if ($hareket) {
                // Tutarı hesaba geri ekle
                $stmt = $db->prepare("UPDATE hesaplar SET bakiye = bakiye + ? WHERE id = ?");
                $stmt->execute([$hareket['tutar'], $hareket['hesap_id']]);

                // Kaydı sil
                $stmt = $db->prepare("DELETE FROM hesap_hareketleri WHERE id = ?");
                $stmt->execute([$hareket_id]);

                // Log kaydı
                sistem_log_ekle($db, 'sil', 'hesap_hareketleri', $hareket_id, $hareket, null, __('cash_expense_receipt_deleted'));

                $_SESSION['basari'] = __("cash_expense_receipt_deleted_successfully");
            } else {
                $_SESSION['hata'] = __("record_to_delete_not_found");
            }
        } catch (Exception $e) {
            $_SESSION['hata'] = __("error_occurred_while_deleting") . ": " . $e->getMessage();
        }
    }
    header("Location: kasa_gider_makbuzlari.php");
    exit();
}

// Filtreleme parametreleri
$baslangic_tarihi = $_GET['baslangic_tarihi'] ?? date('Y-m-01');
$bitis_tarihi = $_GET['bitis_tarihi'] ?? date('Y-m-d');
$hesap_id = filter_input(INPUT_GET, 'hesap_id', FILTER_VALIDATE_INT);
$arama = temizle($_GET['arama'] ?? '');

// Sayfalama
$sayfa = filter_input(INPUT_GET, 'sayfa', FILTER_VALIDATE_INT) ?: 1;
$limit = 20;
$offset = ($sayfa - 1) * $limit;

// Hesapları çek
$stmt = $db->prepare("SELECT id, hesap_adi FROM hesaplar WHERE sirket_id = ? AND aktif = 1 ORDER BY hesap_adi");
$stmt->execute([$_SESSION['aktif_sirket_id']]);
$hesaplar = $stmt->fetchAll();

// İstatistikler için toplam değerler
$istatistik_sql = "SELECT 
    COUNT(*) as toplam_makbuz,
    SUM(tutar) as toplam_tutar,
    AVG(tutar) as ortalama_tutar,
    MIN(tutar) as min_tutar,
    MAX(tutar) as max_tutar
    FROM hesap_hareketleri hh 
    LEFT JOIN hesaplar h ON h.id = hh.hesap_id 
    WHERE hh.sirket_id = ? AND hh.tur = 'cikis' 
    AND hh.tarih BETWEEN ? AND ?";

$istatistik_params = [$_SESSION['aktif_sirket_id'], $baslangic_tarihi, $bitis_tarihi];

if ($hesap_id) {
    $istatistik_sql .= " AND hh.hesap_id = ?";
    $istatistik_params[] = $hesap_id;
}

if ($arama) {
    $istatistik_sql .= " AND hh.aciklama LIKE ?";
    $istatistik_params[] = "%$arama%";
}

$stmt = $db->prepare($istatistik_sql);
$stmt->execute($istatistik_params);
$istatistikler = $stmt->fetch();

// Ana sorgu
$sql = "SELECT hh.*, h.hesap_adi, hh.baglanti_id 
        FROM hesap_hareketleri hh 
        LEFT JOIN hesaplar h ON h.id = hh.hesap_id 
        WHERE hh.sirket_id = ? AND hh.tur = 'cikis' 
        AND hh.tarih BETWEEN ? AND ?";

$params = [$_SESSION['aktif_sirket_id'], $baslangic_tarihi, $bitis_tarihi];

if ($hesap_id) {
    $sql .= " AND hh.hesap_id = ?";
    $params[] = $hesap_id;
}

if ($arama) {
    $sql .= " AND hh.aciklama LIKE ?";
    $params[] = "%$arama%";
}

// Toplam kayıt sayısı
$count_sql = "SELECT COUNT(*) " . substr($sql, strpos($sql, 'FROM'));
$stmt = $db->prepare($count_sql);
$stmt->execute($params);
$toplam_kayit = $stmt->fetchColumn();

// Ana veri
$sql .= " ORDER BY hh.tarih DESC, hh.id DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$makbuzlar = $stmt->fetchAll();

$toplam_sayfa = ceil($toplam_kayit / $limit);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo Yönetim - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .stats-card {
            transition: transform 0.2s;
        }
        .stats-card:hover {
            transform: translateY(-2px);
        }
        .table-hover tbody tr:hover {
            background-color: rgba(0,123,255,.075);
        }
        .btn-group .btn {
            border-radius: 0.375rem !important;
            margin-right: 2px;
        }
        .filter-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0"><?= $sayfa_baslik . ' ' . __("and_transactions") ?></h1>
                <a href="kasa_gider.php" class="btn btn-success">
                    <i class="bi bi-plus-lg"></i> <?= __("new_receipt") ?>
                </a>
            </div>

            <!-- Başarı/Hata Mesajları -->
            <?php if (isset($_SESSION['basari'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill me-2"></i><?= $_SESSION['basari'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php unset($_SESSION['basari']); ?>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['hata'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $_SESSION['hata'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php unset($_SESSION['hata']); ?>
            <?php endif; ?>

            <!-- İstatistikler -->
            <div class="row mb-4">
                <div class="col-md-2">
                    <div class="card bg-primary text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6 class="card-title"><?= __("total_receipts") ?></h6>
                                    <h4 class="mb-0"><?= number_format($istatistikler['toplam_makbuz']) ?></h4>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-receipt fs-2"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-danger text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6 class="card-title"><?= __("total_expense") ?></h6>
                                    <h4 class="mb-0"><?= number_format($istatistikler['toplam_tutar'] ?: 0, 2) ?> <?= $paraBirimi ?></h4>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-arrow-down-circle fs-2"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-info text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6 class="card-title"><?= __("average_expense") ?></h6>
                                    <h4 class="mb-0"><?= number_format($istatistikler['ortalama_tutar'] ?: 0, 2) ?> <?= $paraBirimi ?></h4>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-bar-chart fs-2"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-dark stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6 class="card-title"><?= __("minimum_expense") ?></h6>
                                    <h4 class="mb-0"><?= number_format($istatistikler['min_tutar'] ?: 0, 2) ?> <?= $paraBirimi ?></h4>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-arrow-down fs-2"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-secondary text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h6 class="card-title"><?= __("maximum_expense") ?></h6>
                                    <h4 class="mb-0"><?= number_format($istatistikler['max_tutar'] ?: 0, 2) ?> <?= $paraBirimi ?></h4>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-arrow-up fs-2"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filtreleme -->
            <div class="card mb-4 filter-card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-funnel"></i> <?= __("filtering_and_search") ?>
                    </h5>
                </div>
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label for="baslangic_tarihi" class="form-label"><?= __("start_date") ?></label>
                            <input type="date" class="form-control" id="baslangic_tarihi" name="baslangic_tarihi" value="<?= $baslangic_tarihi ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="bitis_tarihi" class="form-label"><?= __("end_date") ?></label>
                            <input type="date" class="form-control" id="bitis_tarihi" name="bitis_tarihi" value="<?= $bitis_tarihi ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="hesap_id" class="form-label"><?= __("account") ?></label>
                            <select class="form-select" id="hesap_id" name="hesap_id">
                                <option value=""><?= __("all_accounts") ?></option>
                                <?php foreach ($hesaplar as $hesap): ?>
                                    <option value="<?= $hesap['id'] ?>" <?= $hesap_id == $hesap['id'] ? 'selected' : '' ?>>
                                        <?= temizle($hesap['hesap_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="arama" class="form-label"><?= __("search_description") ?></label>
                            <input type="text" class="form-control" id="arama" name="arama" value="<?= $arama ?>" placeholder="<?= __("search_description_placeholder") ?>">
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-search"></i> <?= __("filter") ?>
                            </button>
                            <a href="kasa_gider_makbuzlari.php" class="btn btn-secondary">
                                <i class="bi bi-arrow-clockwise"></i> <?= __("clear") ?>
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Makbuz Listesi -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="bi bi-list"></i> <?= __("cash_expense_receipts_and_transactions") ?>
                        <span class="badge bg-primary"><?= number_format($toplam_kayit) ?></span>
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (empty($makbuzlar)): ?>
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> <?= __("no_cash_expense_receipts_found") ?>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th><?= __("date") ?></th>
                                        <th><?= __("account") ?></th>
                                        <th><?= __("transaction_type") ?></th>
                                        <th><?= __("description") ?></th>
                                        <th><?= __("amount") ?></th>
                                        <th><?= __("actions") ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($makbuzlar as $makbuz): ?>
                                        <?php 
                                        // Transfer işlemi mi kontrol et
                                        $is_transfer = !empty($makbuz['baglanti_id']);
                                        $islem_turu = $is_transfer ? __("transfer_out") : __("expense");
                                        $badge_class = $is_transfer ? 'bg-info' : 'bg-secondary';
                                        ?>
                                        <tr id="row-<?= $makbuz['id'] ?>">
                                            <td><?= date('d.m.Y', strtotime($makbuz['tarih'])) ?></td>
                                            <td>
                                                <span class="badge <?= $badge_class ?>"><?= temizle($makbuz['hesap_adi']) ?></span>
                                            </td>
                                            <td>
                                                <span class="badge <?= $is_transfer ? 'bg-info' : 'bg-danger' ?>">
                                                    <?= $islem_turu ?>
                                                </span>
                                            </td>
                                            <td><?= temizle($makbuz['aciklama']) ?></td>
                                            <td>
                                                <span class="text-danger fw-bold">
                                                    <?= number_format($makbuz['tutar'], 2) ?> <?= $paraBirimi ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="kasa_gider_pdf.php?id=<?= $makbuz['id'] ?>" target="_blank" 
                                                       class="btn btn-outline-danger btn-sm" title="<?= __("view_pdf") ?>">
                                                        <i class="bi bi-file-earmark-pdf"></i>
                                                    </a>
                                                    <?php if (sayfa_yetki_kontrol('kasa_gider_makbuzlari', 'duzenle')): ?>
                                                        <button type="button" class="btn btn-outline-primary btn-sm" 
                                                                onclick="duzenleModal(<?= $makbuz['id'] ?>, '<?= addslashes($makbuz['aciklama']) ?>', <?= $makbuz['tutar'] ?>, '<?= $makbuz['tarih'] ?>')" 
                                                                title="<?= __("edit") ?>">
                                                            <i class="bi bi-pencil"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <?php if (sayfa_yetki_kontrol('kasa_gider_makbuzlari', 'sil')): ?>
                                                        <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                onclick="silOnay(<?= $makbuz['id'] ?>, '<?= addslashes($makbuz['aciklama']) ?>')" 
                                                                title="<?= __("delete") ?>">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Sayfalama -->
                        <?php if ($toplam_sayfa > 1): ?>
                            <nav aria-label="<?= __("page_navigation") ?>">
                                <ul class="pagination justify-content-center">
                                    <?php if ($sayfa > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?sayfa=<?= $sayfa - 1 ?>&baslangic_tarihi=<?= $baslangic_tarihi ?>&bitis_tarihi=<?= $bitis_tarihi ?>&hesap_id=<?= $hesap_id ?>&arama=<?= urlencode($arama) ?>"><?= __("previous") ?></a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $sayfa - 2); $i <= min($toplam_sayfa, $sayfa + 2); $i++): ?>
                                        <li class="page-item <?= $i == $sayfa ? 'active' : '' ?>">
                                            <a class="page-link" href="?sayfa=<?= $i ?>&baslangic_tarihi=<?= $baslangic_tarihi ?>&bitis_tarihi=<?= $bitis_tarihi ?>&hesap_id=<?= $hesap_id ?>&arama=<?= urlencode($arama) ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($sayfa < $toplam_sayfa): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?sayfa=<?= $sayfa + 1 ?>&baslangic_tarihi=<?= $baslangic_tarihi ?>&bitis_tarihi=<?= $bitis_tarihi ?>&hesap_id=<?= $hesap_id ?>&arama=<?= urlencode($arama) ?>"><?= __("next") ?></a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Düzenleme Modal -->
<div class="modal fade" id="duzenleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= __("edit_cash_expense_receipt") ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= csrf_token_olustur() ?>">
                    <input type="hidden" name="hareket_id" id="edit_hareket_id">
                    
                    <div class="mb-3">
                        <label for="edit_aciklama" class="form-label"><?= __("description") ?> *</label>
                        <textarea class="form-control" id="edit_aciklama" name="aciklama" rows="3" required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_tutar" class="form-label"><?= __("amount") ?> (<?= $paraBirimi ?>) *</label>
                        <input type="number" class="form-control" id="edit_tutar" name="tutar" step="0.01" min="0.01" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_tarih" class="form-label"><?= __("date") ?> *</label>
                        <input type="date" class="form-control" id="edit_tarih" name="tarih" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __("cancel") ?></button>
                    <button type="submit" name="duzenle" class="btn btn-primary"><?= __("update") ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Silme Onay Modal -->
<div class="modal fade" id="silModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= __("confirm_receipt_deletion") ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p><?= __("are_you_sure_delete_receipt") ?></p>
                <div class="alert alert-warning">
                    <strong><?= __("warning") ?>:</strong> <?= __("this_action_cannot_be_undone") ?>
                </div>
                <p><strong><?= __("description") ?>:</strong> <span id="sil_aciklama"></span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                <a href="#" id="sil_link" class="btn btn-danger"><?= __("yes_delete") ?></a>
            </div>
        </div>
    </div>
</div>

<script>
function duzenleModal(id, aciklama, tutar, tarih) {
    document.getElementById('edit_hareket_id').value = id;
    document.getElementById('edit_aciklama').value = aciklama;
    document.getElementById('edit_tutar').value = tutar;
    document.getElementById('edit_tarih').value = tarih;
    
    var modal = new bootstrap.Modal(document.getElementById('duzenleModal'));
    modal.show();
}

function silOnay(id, aciklama) {
    document.getElementById('sil_aciklama').textContent = aciklama;
    document.getElementById('sil_link').href = '?sil=' + id + '&csrf_token=<?= csrf_token_olustur() ?>';
    
    var modal = new bootstrap.Modal(document.getElementById('silModal'));
    modal.show();
}

// Başarı/Hata mesajları için otomatik gizleme
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            alert.style.opacity = '0';
            setTimeout(function() {
                alert.remove();
            }, 300);
        }, 5000);
    });
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
