<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;
$db = new Database();
$conn = $db->getConnection();
$sales = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
try {
    $stmt = $conn->prepare("SELECT s.*, o.offer_no FROM sales s LEFT JOIN offers o ON s.offer_id = o.id ORDER BY s.sale_date DESC");
    $stmt->execute();
    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Satışlar</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Satışlar</h2>
    <a href="create_sale.php">Yeni Satış Ekle</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<?php if (empty($sales)): ?>
    <p>Henüz kayıtlı bir satış bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Satış No</th>
                <th>Teklif No</th>
                <th>Müşteri Adı</th>
                <th>Tarih</th>
                <th>Toplam Fiyat</th>
                <th>Durum</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($sales as $sale): ?>
            <tr>
                <td><?php echo htmlspecialchars($sale['sale_no']); ?></td>
                <td><?php echo htmlspecialchars($sale['offer_no'] ?? '-'); ?></td>
                <td><?php echo htmlspecialchars($sale['customer_name']); ?></td>
                <td><?php echo htmlspecialchars($sale['sale_date']); ?></td>
                <td><?php echo number_format($sale['total_price'], 2, ',', '.'); ?> TL</td>
                <td>
                    <?php 
                    $statusInfo = getStatusInfo($sale['status']); 
                    ?>
                    <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
                </td>
                <td>
                    <a href="view_sale.php?id=<?php echo $sale['id']; ?>">Gör</a> |
                    <a href="edit_sale.php?id=<?php echo $sale['id']; ?>">Düzenle</a> |
                    <a href="delete.php?table=sales&id=<?php echo $sale['id']; ?>&redirect=sales.php" onclick="return confirm('Bu kaydı silmek istediğinizden emin misiniz?');">Sil</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</main>
</body>
</html>