<?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;
$offer = null;
$offer_items = [];
$offer_item_costs = [];
$offer_id = $_GET['id'] ?? 0;
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$db = new Database();
$conn = $db->getConnection();

if ($offer_id > 0) {
    try {
        $stmt_offer = $conn->prepare("SELECT o.*, p.project_name FROM offers o LEFT JOIN projects p ON o.project_id = p.id WHERE o.id = ?");
        $stmt_offer->execute([$offer_id]);
        $offer = $stmt_offer->fetch(PDO::FETCH_ASSOC);
        
        $stmt_items = $conn->prepare("SELECT * FROM offer_items WHERE offer_id = ? ORDER BY id ASC");
        $stmt_items->execute([$offer_id]);
        $offer_items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

        // Alt maliyetleri çekme
        $stmt_costs = $conn->prepare("SELECT oic.* FROM offer_item_costs oic JOIN offer_items oi ON oic.offer_item_id = oi.id WHERE oi.offer_id = ?");
        $stmt_costs->execute([$offer_id]);
        $raw_costs = $stmt_costs->fetchAll(PDO::FETCH_ASSOC);
        
        // Maliyetleri item ID'ye göre gruplama
        foreach ($raw_costs as $cost) {
            $offer_item_costs[$cost['offer_item_id']][] = $cost;
        }
        
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$offer) {
    $message = 'Hata: Teklif bulunamadı.';
    $message_type = 'error';
}

// Toplam maliyet ve karı hesaplayalım
$total_cost = 0;
foreach ($offer_items as $item) {
    $total_cost += $item['cost'];
}
$profit = $offer['total_price'] - $total_cost;
$profit_margin = ($offer['total_price'] > 0) ? ($profit / $offer['total_price']) * 100 : 0;
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Teklif Detayı: <?php echo htmlspecialchars($offer['offer_no'] ?? ''); ?></title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .cost-summary-card {
            background-color: #fff8e1;
            border: 1px solid #ffc107;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }
        .cost-summary-card h4 {
            color: #ef6c00;
            margin-bottom: 5px;
            font-size: 1.1rem;
        }
        .sub-cost-table {
            width: 100%;
            margin-top: 10px;
            font-size: 0.9em;
        }
        .sub-cost-table td {
            padding: 5px 0;
            border: none;
            border-bottom: 1px dashed #eee;
        }
        .sub-cost-table th {
            background-color: transparent;
            color: var(--text-muted);
            font-weight: 500;
            padding: 5px 0;
        }
    </style>
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<?php if ($message): ?>
    <p class="message" style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<?php if ($offer): ?>
    <div class="header-actions">
        <h2>Teklif No: <?php echo htmlspecialchars($offer['offer_no']); ?></h2>
        <div class="action-buttons">
            <a href="create_offer_pdf.php?id=<?php echo $offer['id']; ?>" class="btn-primary" style="background-color: var(--accent-red);">PDF Olarak İndir</a>
            <a href="edit_offer.php?id=<?php echo $offer['id']; ?>" class="btn-primary">Teklifi Düzenle</a>
        </div>
    </div>

    <div class="detail-box">
        <h3 class="detail-box-title">Genel Teklif Bilgileri</h3>
        <div class="detail-grid">
            <div><strong>Müşteri Adı:</strong> <?php echo htmlspecialchars($offer['customer_name']); ?></div>
            <div><strong>Müşteri Telefon:</strong> <?php echo htmlspecialchars($offer['customer_phone'] ?? '-'); ?></div>
            <div><strong>Teklif Tarihi:</strong> <?php echo htmlspecialchars($offer['created_at']); ?></div>
            <div><strong>İlgili Proje:</strong> <?php echo htmlspecialchars($offer['project_name'] ?? '-'); ?></div>
            <div><strong>Kategori:</strong> <?php echo htmlspecialchars($offer['category'] ?? '-'); ?></div>
            <div class="full-width"><strong>Durum:</strong> 
                <?php $statusInfo = getStatusInfo($offer['status']); ?>
                <span class="status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span>
            </div>
            <div class="full-width"><strong>Adres:</strong> <?php echo htmlspecialchars($offer['customer_address'] ?? '-'); ?></div>
        </div>
    </div>

    <div class="detail-box">
        <h3 class="detail-box-title">Teklif Kalemleri ve Maliyet Analizi</h3>
        <?php if (empty($offer_items)): ?>
            <p>Bu teklife ait bir kalem bulunmamaktadır.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Ne yapılacak?</th>
                        <th>Miktar</th>
                        <th>Satış Fiyatı</th>
                        <th>Toplam Satış</th>
                        <?php if ($_SESSION['user_role'] === 'admin'): ?>
                            <th>Toplam Maliyet</th>
                            <th>Kar / Marj</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($offer_items as $item): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($item['item_description']); ?>
                                <?php if ($_SESSION['user_role'] === 'admin' && !empty($offer_item_costs[$item['id']])): ?>
                                    <div class="cost-summary-card">
                                        <h4>Alt Maliyet Detayları:</h4>
                                        <table class="sub-cost-table">
                                            <?php foreach ($offer_item_costs[$item['id']] as $cost_detail): ?>
                                                <tr>
                                                    <td style="width: 70%;"><?php echo htmlspecialchars($cost_detail['cost_description']); ?></td>
                                                    <td style="width: 30%; text-align: right;"><?php echo number_format($cost_detail['cost_amount'], 2, ',', '.'); ?> TL</td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <tr style="font-weight: bold; background-color: #f8fafc;">
                                                <td>KALEM TOPLAM MALİYETİ:</td>
                                                <td style="text-align: right;"><?php echo number_format($item['cost'], 2, ',', '.'); ?> TL</td>
                                            </tr>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                            <td><?php echo number_format($item['unit_price'], 2, ',', '.'); ?> TL</td>
                            <td><?php echo number_format($item['total_price'], 2, ',', '.'); ?> TL</td>
                            <?php if ($_SESSION['user_role'] === 'admin'): ?>
                                <td><?php echo number_format($item['cost'], 2, ',', '.'); ?> TL</td>
                                <td><?php echo number_format($item['total_price'] - $item['cost'], 2, ',', '.'); ?> TL</td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr style="background-color: var(--bg-light); font-weight: bold;">
                        <td colspan="3" style="text-align: right;">GENEL TOPLAM:</td>
                        <td><?php echo number_format($offer['total_price'], 2, ',', '.'); ?> TL</td>
                        <?php if ($_SESSION['user_role'] === 'admin'): ?>
                            <td><?php echo number_format($total_cost, 2, ',', '.'); ?> TL</td>
                            <td style="color: <?php echo $profit > 0 ? 'var(--accent-green)' : 'var(--accent-red)'; ?>;">
                                <?php echo number_format($profit, 2, ',', '.'); ?> TL
                            </td>
                        <?php endif; ?>
                    </tr>
                </tfoot>
            </table>
        <?php endif; ?>
    </div>
    <hr>
    <h3>Ek Açıklama</h3>
    <pre><?php echo htmlspecialchars($offer['description'] ?? '-'); ?></pre>
<?php endif; ?>
</main>
</body>
</html>