<?php
session_start();
require 'functions.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: giris.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$commissionRates = [0 => 0.20, 1 => 0.10, 2 => 0.05, 3 => 0.025];

// Kullanıcının referans kodunu çek
$stmt = $pdo->prepare("SELECT reference_code FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Kullanıcının kendi satışlarını çek
$stmt = $pdo->prepare("SELECT id, sale_amount, created_at FROM sales_reports WHERE user_id = ? AND is_approved = 1 ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$sales = $stmt->fetchAll() ?: [];

$apiUrl = "https://sauspharma.com/api.php?key=c3fab0a8dbdc43e7693480a4fe30676a&do=orders";
$response = file_get_contents($apiUrl);
$orders = json_decode($response, true);

$apiSales = [];
if (!empty($orders)) {
    foreach ($orders as $order) {
        // ref_no null değilse ve kullanıcının reference_code ile eşleşiyorsa
        if (isset($order['ref_no']) && $order['ref_no'] === $user['reference_code']) {
            foreach ($order['urunler'] as $urun) {
                $apiSales[] = [
                    'tutar' => $urun['tutar'],
                    'date' => date("d-m-Y", $order['kayit_tarih']) // Unix timestamp'ı okunabilir tarihe çevir
                ];
            }
        }
    }
}

// Kullanıcının referans ağacından gelen komisyonları hesapla
$referralCommissions = getReferralCommissions($pdo, $user['reference_code']);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <title>Satış ve Komisyon Listesi</title>
    <style>
		body {
            margin: 0;
            font-family: 'Arial', sans-serif;
            background-color: #fff;
            color: #333;
			padding-bottom: 80px; /* Footer yüksekliğine göre ayarlayın */
        }
        header {
            background-color: #fff;
            color: #333;
            text-align: center;
            padding: 20px;
        }
        header h1 {
            margin: 0;
            font-size: 24px;
        }
		
		.top-right {
            position: absolute;
            right: 25px;
            top: 40px;
        }

        .material-icons {
            cursor: pointer;
			
        }
		
		.material-icons:active {
            cursor: pointer;
			color: #459D7A
        }
		
        .footer-menu {
            display: flex;
            justify-content: space-around;
            padding: 20px 0;
            background-color: #fff;
            position: fixed;
            bottom: 0;
            width: 100%;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }
		.active {
			font-weight:600;
            color: #459D7A !important;
			
        }
        .footer-menu a {
            text-align: center;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #333;
        }
		
        .footer-menu a i {
            font-size: 24px; /* İkon boyutu */
        }
        .footer-menu a span {
            font-size: 12px;
            margin-top: 4px;
			
        }
		.menu {
    padding: 20px;
    background-color: #fff;
}
        table {
            width: 100%;
            margin-top: 20px;
        }
        th, td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>

<h3 style="text-align:center;">Satışlarımız</h3>

<!-- Kendi Satışlarınız -->
<h4 style="text-align:center;">Kendi Satışlarınız</h4>
<main>
<table>
    <thead>
        <tr>
            <th>Satış Tutarı</th>
            <th>Komisyonlu Tutar (%20)</th>
            <th>Satış Tarihi</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($sales as $sale): ?>
        <tr>
            <td><?= number_format($sale['sale_amount'], 2); ?> TL</td>
            <td><?= number_format($sale['sale_amount'] * $commissionRates[0], 2); ?> TL</td>
            <td><?= date('d-m-Y', strtotime($sale['created_at'])); ?></td>
        </tr>
        <?php endforeach; ?>
		        <?php foreach ($apiSales as $apiSale): ?>
        <tr>
            <td><?= htmlspecialchars($apiSale['tutar']); ?> TL</td>
            <td><?= htmlspecialchars($apiSale['tutar'] * $commissionRates[0], 2); ?> TL</td>
            <td><?= htmlspecialchars($apiSale['date']); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- Referanslardan Gelen Satışlar ve Komisyonlar -->
<h4 style="text-align:center;">Referanslardan Gelen Satışlar ve Komisyonlar</h4>
<?php if (!empty($referralCommissions)): ?>
<table>
    <thead>
        <tr>
            <th>Satış ID</th>
            <th>Satış Tutarı</th>
            <th>Komisyonlu Tutar</th>
            <th>Satış Tarihi</th>
            <th>Referans Seviyesi</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($referralCommissions as $commission): ?>
        <tr>
            <td><?= htmlspecialchars($commission['sale_id']); ?></td>
            <td><?= number_format($commission['sale_amount'], 2); ?> TL</td>
            <td><?= number_format($commission['commission_amount'], 2); ?> TL</td>
            <td><?= date('d-m-Y', strtotime($commission['sale_date'])); ?></td>
            <td><?= htmlspecialchars($commission['referral_level']); ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php else: ?>
<p style="text-align:center;">Referanslarınızdan gelen kaydedilmiş satış bulunmamaktadır.</p>
<?php endif; ?>
</main>
<div class="footer-menu">
    <a href="dashboard.php">
        <i class="material-icons">home</i>
        <span>Ana Sayfa</span>
    </a>
    <a href="sale_list.php" class="active">
        <i class="material-icons">monetization_on</i>
        <span>Satışlar</span>
    </a>
    <a href="profil.php">
        <i class="material-icons">person</i>
        <span>Profil</span>
    </a>
</div>

</body>
</html>

