<?php
session_start();
require_once 'config.php';
require_once 'auth.php';

// Admin kontrolü
if (!isset($_SESSION['admin_logged_in']) || !has_permission('cashback_manage')) {
    header('Location: index.php');
    exit;
}

// Get current date for filtering
$current_date = date('Y-m-d');
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Get statistics
try {
    // Active cashback programs
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cashback_programs WHERE status = 'active'");
    $stmt->execute();
    $active_programs = $stmt->fetch()['count'];

    // Total cashback paid today
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(cashback_amount), 0) as total FROM cashback_payments WHERE DATE(created_at) = ?");
    $stmt->execute([$current_date]);
    $daily_cashback = $stmt->fetch()['total'];

    // Total users with cashback today
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT user_id) as count FROM cashback_payments WHERE DATE(created_at) = ?");
    $stmt->execute([$current_date]);
    $daily_users = $stmt->fetch()['count'];

    // Average cashback percentage
    $stmt = $pdo->prepare("SELECT AVG(cashback_percentage) as avg_percentage FROM cashback_programs WHERE status = 'active'");
    $stmt->execute();
    $avg_percentage = $stmt->fetch()['avg_percentage'] ?? 0;

    // Get cashback programs
    $stmt = $pdo->prepare("SELECT * FROM cashback_programs ORDER BY created_at DESC");
    $stmt->execute();
    $programs = $stmt->fetchAll();

    // Get recent cashback payments
    $stmt = $pdo->prepare("SELECT cp.*, u.username, cb.program_name 
                          FROM cashback_payments cp 
                          JOIN users u ON cp.user_id = u.id 
                          JOIN cashback_programs cb ON cp.program_id = cb.id 
                          WHERE DATE(cp.created_at) BETWEEN ? AND ? 
                          ORDER BY cp.created_at DESC LIMIT 100");
    $stmt->execute([$start_date, $end_date]);
    $payments = $stmt->fetchAll();

} catch (PDOException $e) {
    error_log("Cashback Error: " . $e->getMessage());
    $active_programs = $daily_cashback = $daily_users = $avg_percentage = 0;
    $programs = $payments = [];
}

include 'inc/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-2">
            <?php include 'sidebar.php'; ?>
        </div>
        <div class="col-md-10">
            <div class="main-content">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-money-bill-wave"></i> Cashback Programları</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProgramModal">
                        <i class="fas fa-plus"></i> Yeni Program Ekle
                    </button>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo number_format($active_programs); ?></h4>
                                        <p class="mb-0">Aktif Programlar</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-percentage fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4>₺<?php echo number_format($daily_cashback, 2); ?></h4>
                                        <p class="mb-0">Günlük Cashback</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-coins fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo number_format($daily_users); ?></h4>
                                        <p class="mb-0">Günlük Kullanıcı</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-users fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4>%<?php echo number_format($avg_percentage, 1); ?></h4>
                                        <p class="mb-0">Ortalama Oran</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-chart-line fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Date Filter -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Başlangıç Tarihi</label>
                                <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Bitiş Tarihi</label>
                                <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary d-block">
                                    <i class="fas fa-filter"></i> Filtrele
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Tabs -->
                <ul class="nav nav-tabs" id="cashbackTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="programs-tab" data-bs-toggle="tab" data-bs-target="#programs" type="button">
                            <i class="fas fa-list"></i> Cashback Programları
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="payments-tab" data-bs-toggle="tab" data-bs-target="#payments" type="button">
                            <i class="fas fa-money-bill"></i> Ödeme Geçmişi
                        </button>
                    </li>
                </ul>

                <div class="tab-content" id="cashbackTabsContent">
                    <!-- Programs Tab -->
                    <div class="tab-pane fade show active" id="programs" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="programsTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Program Adı</th>
                                                <th>Cashback Oranı</th>
                                                <th>Min. Kayıp</th>
                                                <th>Max. Cashback</th>
                                                <th>Durum</th>
                                                <th>Oluşturulma</th>
                                                <th>İşlemler</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($programs as $program): ?>
                                            <tr>
                                                <td><?php echo $program['id']; ?></td>
                                                <td><?php echo htmlspecialchars($program['program_name']); ?></td>
                                                <td>%<?php echo number_format($program['cashback_percentage'], 1); ?></td>
                                                <td>₺<?php echo number_format($program['min_loss_amount'], 2); ?></td>
                                                <td>₺<?php echo number_format($program['max_cashback_amount'], 2); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = $program['status'] === 'active' ? 'bg-success' : 'bg-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>">
                                                        <?php echo ucfirst($program['status']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($program['created_at'])); ?></td>
                                                <td>
                                                    <button class="btn btn-sm btn-warning" onclick="editProgram(<?php echo $program['id']; ?>)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-danger" onclick="deleteProgram(<?php echo $program['id']; ?>)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payments Tab -->
                    <div class="tab-pane fade" id="payments" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped" id="paymentsTable">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı</th>
                                                <th>Program</th>
                                                <th>Kayıp Miktarı</th>
                                                <th>Cashback Miktarı</th>
                                                <th>Durum</th>
                                                <th>Tarih</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($payments as $payment): ?>
                                            <tr>
                                                <td><?php echo $payment['id']; ?></td>
                                                <td><?php echo htmlspecialchars($payment['username']); ?></td>
                                                <td><?php echo htmlspecialchars($payment['program_name']); ?></td>
                                                <td>₺<?php echo number_format($payment['loss_amount'], 2); ?></td>
                                                <td>₺<?php echo number_format($payment['cashback_amount'], 2); ?></td>
                                                <td>
                                                    <?php
                                                    $status_class = '';
                                                    switch($payment['status']) {
                                                        case 'paid': $status_class = 'bg-success'; break;
                                                        case 'pending': $status_class = 'bg-warning'; break;
                                                        case 'cancelled': $status_class = 'bg-danger'; break;
                                                        default: $status_class = 'bg-secondary';
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>">
                                                        <?php echo ucfirst($payment['status']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo date('d.m.Y H:i', strtotime($payment['created_at'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Program Modal -->
<div class="modal fade" id="addProgramModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Yeni Cashback Programı Ekle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addProgramForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Program Adı</label>
                                <input type="text" class="form-control" name="program_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Cashback Oranı (%)</label>
                                <input type="number" step="0.1" min="0" max="100" class="form-control" name="cashback_percentage" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Minimum Kayıp Miktarı (₺)</label>
                                <input type="number" step="0.01" min="0" class="form-control" name="min_loss_amount" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Maksimum Cashback (₺)</label>
                                <input type="number" step="0.01" min="0" class="form-control" name="max_cashback_amount" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Durum</label>
                                <select class="form-control" name="status" required>
                                    <option value="active">Aktif</option>
                                    <option value="inactive">Pasif</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Geçerlilik Süresi (Gün)</label>
                                <input type="number" min="1" class="form-control" name="validity_days" value="7">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Açıklama</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                <button type="button" class="btn btn-primary" onclick="saveProgram()">Kaydet</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#programsTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Turkish.json"
        },
        "order": [[ 0, "desc" ]]
    });
    
    $('#paymentsTable').DataTable({
        "language": {
            "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Turkish.json"
        },
        "order": [[ 0, "desc" ]]
    });
});

function saveProgram() {
    const formData = new FormData(document.getElementById('addProgramForm'));
    
    fetch('api/cashback.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Cashback programı başarıyla eklendi!');
            location.reload();
        } else {
            alert('Hata: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Bir hata oluştu!');
    });
}

function editProgram(id) {
    // Edit functionality can be implemented here
    alert('Düzenleme özelliği yakında eklenecek!');
}

function deleteProgram(id) {
    if (confirm('Bu cashback programını silmek istediğinizden emin misiniz?')) {
        fetch('api/cashback.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({id: id})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Cashback programı başarıyla silindi!');
                location.reload();
            } else {
                alert('Hata: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Bir hata oluştu!');
        });
    }
}
</script>

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