<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/language_functions.php'; // For getCurrentLanguage()

// Initialize language
$current_language = getCurrentLanguage();
$translation_file = __DIR__ . "/../languages/{$current_language}.php";
$translations = file_exists($translation_file) ? require $translation_file : [];

// Translation function
if (!function_exists('__')) {
    function __($key, $params = []) {
        global $translations;
        $translation = $translations[$key] ?? $key;
        
        // Replace placeholders if any
        if (!empty($params)) {
            foreach ($params as $param => $value) {
                $translation = str_replace(':' . $param, $value, $translation);
            }
        }
        
        return $translation;
    }
}

$sayfa_baslik = __('add_expense');
yetkili_mi('kasa'); // yetki kontrolü

// Kasa listesini çek
$stmt = $db->prepare("SELECT id, hesap_adi, bakiye FROM hesaplar WHERE sirket_id = ? AND aktif = 1");
$stmt->execute([$_SESSION['aktif_sirket_id']]);
$kasalar = $stmt->fetchAll(PDO::FETCH_ASSOC);

$hata = $mesaj = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $kasa_id = filter_input(INPUT_POST, 'kasa_id', FILTER_VALIDATE_INT);
    $aciklama = trim($_POST['aciklama'] ?? '');
    $tutar = floatval(str_replace(',', '.', $_POST['tutar'] ?? '0'));
    $tarih = $_POST['tarih'] ?? date('Y-m-d');

    // Temel doğrulamalar
    if (!$kasa_id || $aciklama === '' || $tutar <= 0) {
        $hata = __("fill_required_fields");
    } else {
        // Kasa bakiyesi kontrolü
        $stmt = $db->prepare("SELECT bakiye FROM hesaplar WHERE id = ? AND sirket_id = ?");
        $stmt->execute([$kasa_id, $_SESSION['aktif_sirket_id']]);
        $kasa = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$kasa) {
            $hata = __("selected_account_not_found");
        } elseif ($kasa['bakiye'] < $tutar) {
            $hata = __("insufficient_balance");
        } else {
            // Kasa hareketi kaydı
            $stmt = $db->prepare("INSERT INTO hesap_hareketleri (hesap_id, sirket_id, tutar, tur, aciklama, tarih) VALUES (?, ?, ?, 'cikis', ?, ?)");
            $stmt->execute([$kasa_id, $_SESSION['aktif_sirket_id'], $tutar, $aciklama, $tarih]);
            $hareket_id = $db->lastInsertId();
            // Bakiye güncelle
            $db->prepare("UPDATE hesaplar SET bakiye = bakiye - ? WHERE id = ?")->execute([$tutar, $kasa_id]);
            // LOG KAYDI
            if (function_exists('sistem_log_ekle')) {
                $kullanici_id = $_SESSION['kullanici_id'] ?? null;
                $sirket_id = $_SESSION['aktif_sirket_id'] ?? null;
                $yeni_deger = [
                    'kasa_id' => $kasa_id,
                    'aciklama' => $aciklama,
                    'tutar' => $tutar,
                    'tarih' => $tarih
                ];
                sistem_log_ekle($db, 'ekle', 'hesap_hareketleri', $hareket_id, null, $yeni_deger, __('Kasa Gider Makbuzu eklendi'), $kullanici_id);
            }
            // PDF linki
            $pdf_link = "<a href='kasa_gider_pdf.php?id={$hareket_id}' target='_blank' class='btn btn-outline-secondary btn-sm ms-2'><i class='bi bi-file-earmark-pdf'></i> PDF</a>";
            $mesaj = __("expense_added_successfully") . " $pdf_link";
        }
    }
}
?>

<!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>
        .dl-horizontal dt { float: left; width: 160px; overflow: hidden; clear: left; text-align: right; text-overflow: ellipsis; white-space: nowrap; font-weight: bold; margin-bottom: 0.5rem;}
        .dl-horizontal dd { margin-left: 180px; margin-bottom: 0.5rem;}
        .badge-odendi { background-color: var(--bs-success); }
        .badge-kismen { background-color: var(--bs-warning); color: #000 !important; }
        .badge-odenmedi { background-color: var(--bs-danger); }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>
<div class="container mt-4">
    <h2 class="mb-3"><i class="bi bi-cash-stack me-2"></i><?= __("add_expense") ?></h2>
    <?php if ($hata): ?>
        <div class="alert alert-danger"><?= $hata ?></div>
    <?php elseif ($mesaj): ?>
        <div class="alert alert-success"><?= $mesaj ?></div>
    <?php endif; ?>

    <form method="post" class="card shadow-sm p-4 mb-3">
        <div class="mb-3">
            <label for="aciklama" class="form-label"><?= __("description") ?> <span class="text-danger">*</span></label>
            <input type="text" name="aciklama" id="aciklama" class="form-control" required maxlength="200">
        </div>
        <div class="mb-3">
            <label for="tutar" class="form-label"><?= __("amount") ?> <span class="text-danger">*</span></label>
            <input type="number" step="0.01" name="tutar" id="tutar" class="form-control" required>
        </div>
        <div class="mb-3">
            <label for="kasa_id" class="form-label"><?= __("select_cash_register") ?> <span class="text-danger">*</span></label>
            <select name="kasa_id" id="kasa_id" class="form-select" required>
                <option value=""><?= __("select_cash_register") ?></option>
                <?php foreach ($kasalar as $kasa): ?>
                    <option value="<?= $kasa['id'] ?>">
                        <?= temizle($kasa['hesap_adi']) ?> (Bakiye: <?= number_format($kasa['bakiye'], 2, ',', '.') . ' ' . getParaBirimiSembolu() ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label for="tarih" class="form-label"><?= __("date") ?></label>
            <input type="date" name="tarih" id="tarih" class="form-control" value="<?= date('Y-m-d') ?>">
        </div>
        <button type="submit" class="btn btn-primary"><?= __("save_expense") ?></button>
    </form>

    
	
</div>
<?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>
