<?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;

$message = '';
$message_type = '';
$db = new Database();
$conn = $db->getConnection();
$projects = [];
$offer_categories = ['İnşaat', 'Malzeme', 'Yapı Dekorasyon', 'Soğutma', 'Diğer'];

// Keşif verilerini çekme (otomatik doldurma için)
$discovery_data = null;
$discovery_id = $_GET['discovery_id'] ?? ($_POST['discovery_id'] ?? 0);
if ($discovery_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT * FROM technical_office_discoveries WHERE id = ?");
        $stmt->execute([$discovery_id]);
        $discovery_data = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        die("Hata: Keşif verileri alınamadı. " . $e->getMessage());
    }
}

try {
    $stmt = $conn->prepare("SELECT id, project_name FROM projects ORDER BY project_name ASC");
    $stmt->execute();
    $projects = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Son teklif numarasını bul ve artır (MKSR-001 mantığı)
    $stmt_last_offer = $conn->prepare("SELECT offer_no FROM offers ORDER BY id DESC LIMIT 1");
    $stmt_last_offer->execute();
    $last_offer_no = $stmt_last_offer->fetchColumn();

    if ($last_offer_no && strpos($last_offer_no, 'MKSR-') === 0) {
        $last_number = intval(substr($last_offer_no, 5));
        $new_number = $last_number + 1;
        $next_offer_no = 'MKSR-' . str_pad($new_number, 3, '0', STR_PAD_LEFT);
    } else {
        $next_offer_no = 'MKSR-001';
    }

} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_name = $_POST['customer_name'] ?? '';
    $customer_phone = $_POST['customer_phone'] ?? '';
    $customer_address = $_POST['customer_address'] ?? '';
    $project_id = $_POST['project_id'] ?? null;
    $category = $_POST['category'] ?? '';
    $items = $_POST['items'] ?? [];
    $all_costs_json = $_POST['all_costs_json'] ?? '[]'; // JSON olarak gelen alt maliyetler
    $description = $_POST['description'] ?? '';
    $offer_no = $_POST['generated_offer_no'] ?? 'HATA'; // Oluşturulan numarayı al
    $user_id = $_SESSION['user_id'];
    $total_price = 0;
    $costs_by_item = json_decode($all_costs_json, true);

    try {
        $conn->beginTransaction();

        $stmt_offer = $conn->prepare("INSERT INTO offers (offer_no, customer_name, customer_phone, customer_address, project_id, description, category, total_price, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt_offer->execute([$offer_no, $customer_name, $customer_phone, $customer_address, $project_id, $description, $category, $total_price, $user_id]);
        $offer_id = $conn->lastInsertId();
        
        $total_project_cost = 0;

        foreach ($items as $item_key => $item) {
            $item_description = $item['description'] ?? '';
            $unit_price = (float)($item['unit_price'] ?? 0);
            $quantity = (int)($item['quantity'] ?? 0);
            $item_total_price = $unit_price * $quantity;
            $total_price += $item_total_price;
            
            // Alt maliyetleri topla
            $item_total_cost = 0;
            if (isset($costs_by_item[$item_key])) {
                foreach ($costs_by_item[$item_key] as $cost_entry) {
                    $item_total_cost += (float)$cost_entry['amount'];
                }
            }
            $total_project_cost += $item_total_cost; // Proje maliyetini topla

            // offer_items tablosuna ekle
            $stmt_item = $conn->prepare("INSERT INTO offer_items (offer_id, item_description, unit_price, quantity, total_price, cost) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt_item->execute([$offer_id, $item_description, $unit_price, $quantity, $item_total_price, $item_total_cost]);
            $offer_item_id = $conn->lastInsertId();

            // Alt maliyetleri offer_item_costs tablosuna ekle
            if (isset($costs_by_item[$item_key])) {
                $stmt_cost = $conn->prepare("INSERT INTO offer_item_costs (offer_item_id, cost_description, cost_amount) VALUES (?, ?, ?)");
                foreach ($costs_by_item[$item_key] as $cost_entry) {
                    $stmt_cost->execute([$offer_item_id, $cost_entry['description'], $cost_entry['amount']]);
                }
            }
        }
        
        // Genel toplamı güncelle
        $stmt_update_total = $conn->prepare("UPDATE offers SET total_price = ? WHERE id = ?");
        $stmt_update_total->execute([$total_price, $offer_id]);
        
        $conn->commit();
        
        $message = "Yeni teklif başarıyla oluşturuldu! Teklif No: " . $offer_no;
        $message_type = 'success';
        header('Location: offers.php?status=success&message=' . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $conn->rollBack();
        $message = 'Hata: Teklif oluşturulurken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Yeni Teklif Oluştur</title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        /* Sadece bu sayfa için gerekli stil */
        .cost-button-group {
            display: flex;
            align-items: flex-end;
            gap: 10px;
        }
        .cost-button-group button {
            width: auto;
            padding: 8px 15px;
            font-size: 0.9rem;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 10;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.6);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border-radius: 12px;
            width: 80%;
            max-width: 600px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .modal-content h4 {
            margin-top: 0;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 10px;
        }
        .cost-entry {
            display: grid;
            grid-template-columns: 2fr 1fr 50px;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
            border-bottom: 1px dashed #eee;
            padding-bottom: 5px;
        }
    </style>
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<h2>Yeni Teklif Oluştur</h2>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<form action="create_offer.php" method="POST">
    <input type="hidden" name="generated_offer_no" value="<?php echo $next_offer_no; ?>">
    <input type="hidden" name="all_costs_json" id="all_costs_json" value="{}">
    
    <div class="form-section-title">Genel Bilgiler</div>
    <div class="form-grid">
        <div class="form-group">
            <label for="offer_no">Teklif Numarası</label>
            <input type="text" id="offer_no" value="<?php echo $next_offer_no; ?>" disabled>
        </div>
        <div class="form-group">
            <label for="category">Teklif Kategorisi *</label>
            <select id="category" name="category" required>
                <option value="">Seçiniz</option>
                <?php foreach ($offer_categories as $cat): ?>
                    <option value="<?php echo htmlspecialchars($cat); ?>"><?php echo htmlspecialchars($cat); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label for="customer_name">Müşteri Adı *</label>
            <input type="text" id="customer_name" name="customer_name" value="<?php echo htmlspecialchars($discovery_data['customer_name'] ?? ''); ?>" required>
        </div>
        <div class="form-group">
            <label for="customer_phone">Müşteri Telefon</label>
            <input type="text" id="customer_phone" name="customer_phone" value="<?php echo htmlspecialchars($discovery_data['company_phone'] ?? ''); ?>">
        </div>
    </div>
    <div class="form-group full-width">
        <label for="customer_address">Müşteri Adresi</label>
        <textarea id="customer_address" name="customer_address" rows="3"><?php echo htmlspecialchars($discovery_data['company_address'] ?? ''); ?></textarea>
    </div>
    <div class="form-group full-width">
        <label for="project_id">İlgili Proje</label>
        <select id="project_id" name="project_id">
            <option value="">Seçiniz</option>
            <?php foreach ($projects as $project): ?>
                <option value="<?php echo $project['id']; ?>" <?php echo ($discovery_data['project_id'] ?? null) == $project['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($project['project_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="form-section-title">Fiyat ve Maliyet Bilgisi (Kalem Kalem)</div>
    <div id="offer-items-container">
        <div class="form-grid offer-item-row" data-item-index="0">
            <div class="form-group full-width">
                <label for="item_description_0">İş Kalemi / Ne yapılacak? *</label>
                <input type="text" name="items[0][description]" placeholder="Detaylı iş açıklaması" required>
            </div>
            <div class="form-group">
                <label for="item_quantity_0">Miktar *</label>
                <input type="number" name="items[0][quantity]" value="1" min="1" class="item-quantity" required>
            </div>
            <div class="form-group">
                <label for="item_unit_price_0">Satış Fiyatı (TL) *</label>
                <input type="number" name="items[0][unit_price]" value="0.00" step="0.01" min="0" class="item-unit-price" required>
            </div>
            <div class="form-group">
                <label>Toplam Satış (TL)</label>
                <input type="text" class="item-total-price" value="0.00" disabled>
            </div>
            <div class="form-group">
                <label>Toplam Maliyet (TL)</label>
                <input type="text" class="item-total-cost-display" value="0.00" disabled>
            </div>
            <div class="form-group cost-button-group full-width" style="grid-column: 1 / 3;">
                <button type="button" class="open-cost-modal-btn secondary-btn" data-item-index="0">Maliyetleri Ekle/Gör (+)</button>
                <button type="button" class="remove-item-btn secondary-btn" style="background-color: #dc3545;">- Kalemi Sil</button>
            </div>
        </div>
    </div>
    <div class="form-actions full-width" style="text-align: left;">
        <button type="button" id="add-item-btn" class="secondary-btn">Yeni Kalem Ekle</button>
    </div>

    <div class="form-section-title">Genel Teklif Bilgileri</div>
    <div class="form-group full-width">
        <label for="description">Ek Açıklama (Opsiyonel)</label>
        <textarea id="description" name="description" rows="5"><?php echo htmlspecialchars($discovery_data['action_to_be_taken'] ?? ''); ?></textarea>
    </div>

    <div class="form-actions full-width">
        <button type="submit">Teklifi Oluştur</button>
    </div>
</form>

<div id="costModal" class="modal">
    <div class="modal-content">
        <h4>Kalem Maliyet Detayları</h4>
        <div id="current-item-info"></div>
        <form id="cost-entry-form">
            <div class="cost-entry-fields">
                <input type="text" id="cost_description_input" placeholder="Maliyet Açıklaması (Malzeme, İşçilik vb.)">
                <input type="number" id="cost_amount_input" step="0.01" min="0" placeholder="Maliyet Tutarı (TL)">
                <button type="button" id="add-cost-btn" class="btn btn-primary" style="padding: 10px;">+</button>
            </div>
        </form>
        <hr>
        <h5>Mevcut Maliyetler</h5>
        <div id="item-cost-list">
            </div>
        <hr>
        <div style="text-align: right;">
            <p><strong>TOPLAM MALİYET: <span id="modal-total-cost">0.00 TL</span></strong></p>
            <button id="close-modal-btn" class="secondary-btn">Kapat</button>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        let itemIndex = 1;
        const itemsContainer = document.getElementById('offer-items-container');
        const costModal = document.getElementById('costModal');
        const closeModalBtn = document.getElementById('close-modal-btn');
        const addCostBtn = document.getElementById('add-cost-btn');
        const itemCostList = document.getElementById('item-cost-list');
        const modalTotalCostSpan = document.getElementById('modal-total-cost');
        const allCostsInput = document.getElementById('all_costs_json');
        
        let activeItemIndex = null;
        let allCosts = JSON.parse(allCostsInput.value);

        function updateAllCostsInput() {
            allCostsInput.value = JSON.stringify(allCosts);
        }

        function calculateRowTotals(row) {
            const index = row.dataset.itemIndex;
            const quantity = parseFloat(row.querySelector('.item-quantity').value) || 0;
            const unitPrice = parseFloat(row.querySelector('.item-unit-price').value) || 0;
            
            const totalPrice = quantity * unitPrice;
            
            // Alt maliyetleri topla
            const itemTotalCost = (allCosts[index] || []).reduce((sum, cost) => sum + (parseFloat(cost.amount) * quantity), 0);

            row.querySelector('.item-total-price').value = totalPrice.toFixed(2);
            row.querySelector('.item-total-cost-display').value = itemTotalCost.toFixed(2);

            updateAllCostsInput();
        }

        function renderCostList(itemIndex) {
            itemCostList.innerHTML = '';
            let total = 0;
            const costs = allCosts[itemIndex] || [];
            
            costs.forEach((cost, idx) => {
                const costElement = document.createElement('div');
                costElement.classList.add('cost-entry');
                costElement.innerHTML = `
                    <div>${cost.description}</div>
                    <div>${parseFloat(cost.amount).toFixed(2)} TL</div>
                    <button type="button" class="remove-cost-btn btn-danger" data-cost-index="${idx}" style="padding: 5px 10px; font-size: 0.9em;">X</button>
                `;
                itemCostList.appendChild(costElement);
                total += parseFloat(cost.amount);
            });

            modalTotalCostSpan.textContent = total.toFixed(2) + ' TL';
            
            // Ana formdaki ilgili kalemin toplam maliyetini güncelle
            const mainRow = document.querySelector(`.offer-item-row[data-item-index="${itemIndex}"]`);
            if (mainRow) {
                mainRow.querySelector('.item-total-cost-display').value = (total * parseFloat(mainRow.querySelector('.item-quantity').value)).toFixed(2);
            }
        }

        // --- Event Listeners ---

        // 1. Maliyet Ekleme Butonu
        itemsContainer.addEventListener('click', function(e) {
            if (e.target.classList.contains('open-cost-modal-btn')) {
                activeItemIndex = e.target.dataset.itemIndex;
                const itemDescription = document.querySelector(`.offer-item-row[data-item-index="${activeItemIndex}"] input[name$="[description]"]`).value;
                document.getElementById('current-item-info').innerHTML = `<strong>Kalem:</strong> ${itemDescription || 'Yeni Kalem'}`;
                
                renderCostList(activeItemIndex);
                costModal.style.display = 'block';
            }
        });

        // 2. Yeni Alt Maliyet Ekleme
        addCostBtn.addEventListener('click', function() {
            const description = document.getElementById('cost_description_input').value.trim();
            const amount = parseFloat(document.getElementById('cost_amount_input').value);

            if (description && amount > 0 && activeItemIndex !== null) {
                if (!allCosts[activeItemIndex]) {
                    allCosts[activeItemIndex] = [];
                }
                allCosts[activeItemIndex].push({ description, amount });

                document.getElementById('cost_description_input').value = '';
                document.getElementById('cost_amount_input').value = '0.00';
                
                renderCostList(activeItemIndex);
                updateAllCostsInput();
            }
        });

        // 3. Alt Maliyet Silme
        itemCostList.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-cost-btn')) {
                const costIndex = parseInt(e.target.dataset.costIndex);
                if (activeItemIndex !== null && allCosts[activeItemIndex] && !isNaN(costIndex)) {
                    allCosts[activeItemIndex].splice(costIndex, 1);
                    renderCostList(activeItemIndex);
                    updateAllCostsInput();
                }
            }
        });

        // 4. Modal Kapatma
        closeModalBtn.addEventListener('click', function() {
            costModal.style.display = 'none';
        });

        // 5. Yeni Kalem Ekleme
        document.getElementById('add-item-btn').addEventListener('click', function() {
            const newItemRow = document.createElement('div');
            newItemRow.classList.add('form-grid', 'offer-item-row');
            newItemRow.dataset.itemIndex = itemIndex;

            let adminCostInput = '';
            let totalCostDisplay = '';
            
            // Form yapısını oluştur
            // (Aynı admin kontrol mantığı burada da kullanılmalı - PHP'den gelen koşulu JS'e taşıdık)
            const is_admin = true; // Gerçek PHP koşulunu buraya taşımak yerine, PHP ile HTML render edildiği için burası basitleştirilebilir.
            
            // PHP koşullarını tekrar buraya gömmek yerine, basit tutuyorum:
            adminCostInput = `
                <div class="form-group cost-button-group full-width" style="grid-column: 1 / 3;">
                    <button type="button" class="open-cost-modal-btn secondary-btn" data-item-index="${itemIndex}">Maliyetleri Ekle/Gör (+)</button>
                    <button type="button" class="remove-item-btn secondary-btn" style="background-color: #dc3545;">- Kalemi Sil</button>
                </div>
            `;
            
            newItemRow.innerHTML = `
                <div class="form-group full-width">
                    <label for="item_description_${itemIndex}">İş Kalemi / Ne yapılacak? *</label>
                    <input type="text" name="items[${itemIndex}][description]" placeholder="Detaylı iş açıklaması" required>
                </div>
                <div class="form-group">
                    <label for="item_quantity_${itemIndex}">Miktar *</label>
                    <input type="number" name="items[${itemIndex}][quantity]" value="1" min="1" class="item-quantity" required>
                </div>
                <div class="form-group">
                    <label for="item_unit_price_${itemIndex}">Satış Fiyatı (TL) *</label>
                    <input type="number" name="items[${itemIndex}][unit_price]" value="0.00" step="0.01" min="0" class="item-unit-price" required>
                </div>
                
                <div class="form-group">
                    <label>Toplam Satış (TL)</label>
                    <input type="text" class="item-total-price" value="0.00" disabled>
                </div>
                <div class="form-group">
                    <label>Toplam Maliyet (TL)</label>
                    <input type="text" class="item-total-cost-display" value="0.00" disabled>
                </div>
                
                ${adminCostInput}
            `;
            
            itemsContainer.appendChild(newItemRow);
            
            // Yeni satıra event listener ekle
            newItemRow.addEventListener('input', function() {
                calculateRowTotals(newItemRow);
            });

            itemIndex++;
        });
        
        // 6. Genel Input Değişiklikleri
        itemsContainer.addEventListener('input', function(e) {
            const target = e.target;
            if (target.closest('.offer-item-row')) {
                calculateRowTotals(target.closest('.offer-item-row'));
            }
        });

        // Sayfa yüklendiğinde mevcut satırların toplamını hesapla (ilk satır için)
        itemsContainer.querySelectorAll('.offer-item-row').forEach(row => {
            calculateRowTotals(row);
        });

        // İlk satırdaki Maliyetleri Ekle/Gör butonu için PHP'den gelen kısmı düzelttik
        const initialRow = itemsContainer.querySelector('.offer-item-row[data-item-index="0"]');
        if (initialRow) {
            initialRow.querySelector('.cost-button-group').innerHTML = `
                <button type="button" class="open-cost-modal-btn secondary-btn" data-item-index="0">Maliyetleri Ekle/Gör (+)</button>
                <button type="button" class="remove-item-btn secondary-btn" style="background-color: #dc3545;">- Kalemi Sil</button>
            `;
        }
    });
</script>
</body>
</html>