<?php
require_once '../config/database.php';
session_start();

if (!isset($_SESSION['rol']) || !in_array($_SESSION['rol'], ['superadmin', 'yonetici'])) {
    header('Location: login.php');
    exit;
}

$site_id = (int)($_SESSION['site_id'] ?? 0);
$site_adi = $_SESSION['site_adi'] ?? 'Site';
$errors = [];
$success = '';

require_once '../site/class/enpara.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        
        if ($_POST['action'] === 'add_hesap') {
            $banka_adi     = trim($_POST['banka_adi']);
            $iban          = strtoupper(trim($_POST['iban']));
            $hesap_no      = trim($_POST['hesap_no']);
            $client_id     = trim($_POST['client_id']);
            $client_secret = trim($_POST['client_secret']);
            $access_token  = trim($_POST['access_token']);
            $refresh_token = trim($_POST['refresh_token']);

            try {
                $stmt = $pdo->prepare("INSERT INTO banka_hesap 
                    (site_id, banka_adi, iban, hesap_no, client_id, client_secret, access_token, refresh_token, son_guncelleme) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$site_id, $banka_adi, $iban, $hesap_no, $client_id, $client_secret, $access_token, $refresh_token]);
                $success = 'Banka hesabı eklendi.';
            } catch (Exception $e) {
                $errors[] = 'Hata: ' . $e->getMessage();
            }
        } 
        
        elseif ($_POST['action'] === 'delete_hesap') {
            $id = (int)$_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM banka_hesap WHERE id = ? AND site_id = ?");
            $stmt->execute([$id, $site_id]);
            $success = 'Hesap silindi.';
        } 
        
        elseif ($_POST['action'] === 'get_balance') {
            $id = (int)$_POST['id'];
            
            try {
                $stmt = $pdo->prepare("SELECT * FROM banka_hesap WHERE id = ? AND site_id = ?");
                $stmt->execute([$id, $site_id]);
                $hesap = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$hesap) {
                    $errors[] = 'Hesap bulunamadı.';
                } elseif (empty($hesap['access_token']) || empty($hesap['client_id'])) {
                    $errors[] = 'Client ID veya Access Token eksik.';
                } else {
                    $enpara = new EnparaAPI();
                    $account = !empty($hesap['hesap_no']) ? trim($hesap['hesap_no']) : trim($hesap['iban']);

                    $result = $enpara->getStatement(
                        $hesap['client_id'],
                        $hesap['client_secret'],
                        $hesap['access_token'],
                        $account
                    );

                    $debug = "🔍 DEBUG BİLGİSİ:<br>";
                    $debug .= "HTTP Code: " . $result['http_code'] . "<br>";
                    $debug .= "Kullanılan Hesap: " . htmlspecialchars($account) . "<br>";

                    if (!empty($result['body'])) {
                        $body = json_decode($result['body'], true);
                        $yeni_bakiye = 0;

                        if (isset($body['accountBalance'])) {
                            $yeni_bakiye = (float)$body['accountBalance'];
                        } elseif (isset($body['lastTrxClosingBalance'])) {
                            $yeni_bakiye = (float)$body['lastTrxClosingBalance'];
                        }

                        $stmt = $pdo->prepare("UPDATE banka_hesap SET bakiye = ?, son_guncelleme = NOW() WHERE id = ?");
                        $stmt->execute([$yeni_bakiye, $id]);

                        $success = 'Bakiye başarıyla güncellendi: ₺' . number_format($yeni_bakiye, 2, ',', '.');
                        $debug .= "<br><strong>✅ Bakiye: " . $yeni_bakiye . "</strong>";
                    } else {
                        $debug .= "<br>⚠️ Body boş geldi.";
                        $debug .= "<br><strong>RAW BODY:</strong><br>" . htmlspecialchars($result['body']);
                    }
                    
                    $errors[] = $debug;
                }
            } catch (Exception $e) {
                $errors[] = 'Sistem Hatası: ' . $e->getMessage();
            }
        }
    }
}

// Hesapları çek
$hesaplar = [];
$stmt = $pdo->prepare("SELECT * FROM banka_hesap WHERE site_id = ? ORDER BY banka_adi");
$stmt->execute([$site_id]);
$hesaplar = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>

<div class="content-wrapper pb-5">
    <div class="content-header">
        <div class="container-fluid">
            <h1 class="m-0"><i class="fas fa-university"></i> Banka Hesap Takibi - <?= htmlspecialchars($site_adi) ?></h1>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger"><?= implode('<br><hr>', $errors) ?></div>
            <?php endif; ?>
            <?php if ($success): ?>
                <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
            <?php endif; ?>

            <!-- Yeni Hesap Ekle -->
            <div class="card mb-4">
                <div class="card-header bg-primary">
                    <h3 class="card-title">Yeni Banka Hesabı Ekle</h3>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="add_hesap">
                        <div class="row">
                            <div class="col-md-3">
                                <label>Banka Adı <span class="text-danger">*</span></label>
                                <input type="text" name="banka_adi" class="form-control" required>
                            </div>
                            <div class="col-md-3">
                                <label>IBAN</label>
                                <input type="text" name="iban" class="form-control text-uppercase" maxlength="34">
                            </div>
                            <div class="col-md-3">
                                <label>Hesap No</label>
                                <input type="text" name="hesap_no" class="form-control">
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-3">
                                <label>Client ID</label>
                                <input type="text" name="client_id" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label>Client Secret</label>
                                <input type="text" name="client_secret" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label>Access Token</label>
                                <input type="text" name="access_token" class="form-control">
                            </div>
                            <div class="col-md-3">
                                <label>Refresh Token</label>
                                <input type="text" name="refresh_token" class="form-control">
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary mt-3">Hesabı Kaydet</button>
                    </form>
                </div>
            </div>

            <!-- Hesap Listesi -->
            <div class="card">
                <div class="card-header bg-info">
                    <h3 class="card-title">Mevcut Banka Hesapları</h3>
                </div>
                <div class="card-body table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Banka</th>
                                <th>IBAN / Hesap No</th>
                                <th class="text-end">Bakiye</th>
                                <th>Son Güncelleme</th>
                                <th>İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($hesaplar)): ?>
                                <tr><td colspan="5" class="text-center py-4">Henüz banka hesabı eklenmemiş.</td></tr>
                            <?php else: ?>
                                <?php foreach ($hesaplar as $h): ?>
                                <tr>
                                    <td><?= htmlspecialchars($h['banka_adi']) ?></td>
                                    <td><?= htmlspecialchars($h['iban'] ?: $h['hesap_no']) ?></td>
                                    <td class="text-end font-weight-bold text-success">₺<?= number_format($h['bakiye'], 2, ',', '.') ?></td>
                                    <td><?= $h['son_guncelleme'] ? date('d.m.Y H:i', strtotime($h['son_guncelleme'])) : '-' ?></td>
                                    <td>
                                        <button onclick="deleteHesap(<?= $h['id'] ?>)" class="btn btn-sm btn-danger">Sil</button>
                                        <button onclick="getBalance(<?= $h['id'] ?>)" class="btn btn-sm btn-success">Bakiye & Hareket Getir</button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
function deleteHesap(id) {
    if (confirm('Bu hesabı silmek istediğinizden emin misiniz?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `<input type="hidden" name="action" value="delete_hesap"><input type="hidden" name="id" value="${id}">`;
        document.body.appendChild(form);
        form.submit();
    }
}
function getBalance(id) {
    if (confirm('Enpara’dan bakiye ve hareketleri çekmek istiyor musunuz?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="get_balance">
            <input type="hidden" name="id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<?php include '../inc/footer.php'; ?>