<?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();
$message = '';
$message_type = '';
$offer = null;
$offer_items = [];
$offer_categories = ['İnşaat', 'Malzeme', 'Yapı Dekorasyon', 'Soğutma', 'Diğer'];
$projects = [];
$offer_id = $_REQUEST['id'] ?? 0;
if ($offer_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT * FROM offers WHERE id = ?");
        $stmt->execute([$offer_id]);
        $offer = $stmt->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);
        $stmt_projects = $conn->prepare("SELECT id, project_name FROM projects ORDER BY project_name ASC");
        $stmt_projects->execute();
        $projects = $stmt_projects->fetchAll(PDO::FETCH_ASSOC);
        if (!$offer) {
            $message = 'Düzenlemek istediğiniz teklif bulunamadı.';
            $message_type = 'error';
        }
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $offer) {
    $customer_name = $_POST['customer_name'] ?? $offer['customer_name'];
    $customer_email = $_POST['customer_email'] ?? $offer['customer_email'];
    $customer_phone = $_POST['customer_phone'] ?? $offer['customer_phone'];
    $customer_address = $_POST['customer_address'] ?? $offer['customer_address'];
    $project_id = $_POST['project_id'] ?? $offer['project_id'];
    $category = $_POST['category'] ?? $offer['category'];
    $description = $_POST['description'] ?? $offer['description'];
    $status = $_POST['status'] ?? $offer['status'];
    $items = $_POST['items'] ?? [];
    $total_price = 0;
    try {
        $conn->beginTransaction();
        $stmt_delete_items = $conn->prepare("DELETE FROM offer_items WHERE offer_id = ?");
        $stmt_delete_items->execute([$offer_id]);
        foreach ($items as $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;
            $cost = (float)($item['cost'] ?? 0);
            $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, $cost]);
        }
        $stmt_update_offer = $conn->prepare("UPDATE offers SET customer_name = ?, customer_email = ?, customer_phone = ?, customer_address = ?, project_id = ?, description = ?, category = ?, total_price = ?, status = ? WHERE id = ?");
        $stmt_update_offer->execute([$customer_name, $customer_email, $customer_phone, $customer_address, $project_id, $description, $category, $total_price, $status, $offer_id]);
        $conn->commit();
        $message = 'Teklif başarıyla güncellendi.';
        $message_type = 'success';
    } catch (PDOException $e) {
        $conn->rollBack();
        $message = 'Güncelleme sırasında bir hata oluştu: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$offer && $offer_id > 0) {
    echo "Hata: Teklif bulunamadı veya yetkiniz yok.";
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Teklif Düzenle: <?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">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
    <h2>Teklif Düzenle</h2>
    <?php if ($message): ?>
        <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
            <?php echo htmlspecialchars($message); ?>
        </p>
    <?php endif; ?>
    <?php if ($offer): ?>
    <form action="edit_offer.php?id=<?php echo htmlspecialchars($offer['id']); ?>" method="POST">
        <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 htmlspecialchars($offer['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 ($offer['category'] === $cat) ? 'selected' : ''; ?>><?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($offer['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($offer['customer_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($offer['customer_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 ($offer['project_id'] == $project['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($project['project_name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group full-width">
            <label for="status">Durum:</label>
            <select id="status" name="status">
                <option value="draft" <?php echo $offer['status'] === 'draft' ? 'selected' : ''; ?>>Taslak</option>
                <option value="sent" <?php echo $offer['status'] === 'sent' ? 'selected' : ''; ?>>Gönderildi</option>
                <option value="accepted" <?php echo $offer['status'] === 'accepted' ? 'selected' : ''; ?>>Kabul Edildi</option>
                <option value="rejected" <?php echo $offer['status'] === 'rejected' ? 'selected' : ''; ?>>Reddedildi</option>
            </select>
        </div>

        <div class="form-section-title">Fiyat Bilgisi</div>
        <div id="offer-items-container">
            <?php if (!empty($offer_items)): ?>
                <?php foreach ($offer_items as $index => $item): ?>
                    <div class="form-grid offer-item-row">
                        <div class="form-group">
                            <label for="item_description_<?php echo $index; ?>">Ne yapılacak?</label>
                            <input type="text" name="items[<?php echo $index; ?>][description]" value="<?php echo htmlspecialchars($item['item_description']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="item_quantity_<?php echo $index; ?>">Miktar</label>
                            <input type="number" name="items[<?php echo $index; ?>][quantity]" value="<?php echo htmlspecialchars($item['quantity']); ?>" min="1" class="item-quantity">
                        </div>
                        <div class="form-group">
                            <label for="item_unit_price_<?php echo $index; ?>">Birim Fiyat (TL)</label>
                            <input type="number" name="items[<?php echo $index; ?>][unit_price]" value="<?php echo htmlspecialchars($item['unit_price']); ?>" step="0.01" min="0" class="item-unit-price">
                        </div>
                        <?php if ($_SESSION['user_role'] === 'admin'): ?>
                        <div class="form-group">
                            <label for="item_cost_<?php echo $index; ?>">Maliyet Fiyatı (TL)</label>
                            <input type="number" name="items[<?php echo $index; ?>][cost]" value="<?php echo htmlspecialchars($item['cost']); ?>" step="0.01" min="0" class="item-cost">
                        </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="form-grid offer-item-row">
                    <div class="form-group">
                        <label for="item_description[]">Ne yapılacak?</label>
                        <input type="text" name="items[0][description]" placeholder="İş kalemi açıklaması" required>
                    </div>
                    <div class="form-group">
                        <label for="item_quantity[]">Miktar</label>
                        <input type="number" name="items[0][quantity]" value="1" min="1" class="item-quantity">
                    </div>
                    <div class="form-group">
                        <label for="item_unit_price[]">Birim Fiyat (TL)</label>
                        <input type="number" name="items[0][unit_price]" value="0.00" step="0.01" min="0" class="item-unit-price">
                    </div>
                    <?php if ($_SESSION['user_role'] === 'admin'): ?>
                    <div class="form-group">
                        <label for="item_cost[]">Maliyet Fiyatı (TL)</label>
                        <input type="number" name="items[0][cost]" value="0.00" step="0.01" min="0" class="item-cost">
                    </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <div class="form-actions full-width">
            <button type="button" id="add-item-btn" class="secondary-btn">Yeni Kalem Ekle</button>
        </div>

        <div class="form-section-title">Ek Bilgiler</div>
        <div class="form-group full-width">
            <label for="description">Ek Açıklama</label>
            <textarea id="description" name="description" rows="5"><?php echo htmlspecialchars($offer['description'] ?? ''); ?></textarea>
        </div>
        <div class="form-actions full-width">
            <button type="submit">Teklifi Güncelle</button>
        </div>
    </form>
    <?php endif; ?>
</main>
<script>
document.addEventListener('DOMContentLoaded', function() {
    let itemIndex = <?php echo count($offer_items); ?>;
    const addItemBtn = document.getElementById('add-item-btn');
    const itemsContainer = document.getElementById('offer-items-container');
    addItemBtn.addEventListener('click', function() {
        const newItemRow = document.createElement('div');
        newItemRow.classList.add('form-grid', 'offer-item-row');
        let adminCostInput = '';
        <?php if ($_SESSION['user_role'] === 'admin'): ?>
            adminCostInput = `
            <div class="form-group">
                <label for="item_cost[]">Maliyet Fiyatı (TL)</label>
                <input type="number" name="items[${itemIndex}][cost]" value="0.00" step="0.01" min="0" class="item-cost">
            </div>
            `;
        <?php endif; ?>
        newItemRow.innerHTML = `
            <div class="form-group">
                <label for="item_description[]">Ne yapılacak?</label>
                <input type="text" name="items[${itemIndex}][description]" placeholder="İş kalemi açıklaması" required>
            </div>
            <div class="form-group">
                <label for="item_quantity[]">Miktar</label>
                <input type="number" name="items[${itemIndex}][quantity]" value="1" min="1" class="item-quantity">
            </div>
            <div class="form-group">
                <label for="item_unit_price[]">Birim Fiyat (TL)</label>
                <input type="number" name="items[${itemIndex}][unit_price]" value="0.00" step="0.01" min="0" class="item-unit-price">
            </div>
            ${adminCostInput}
            <div class="form-group remove-btn-group">
                <button type="button" class="remove-item-btn secondary-btn" style="background-color: #dc3545;">-</button>
            </div>
        `;
        itemsContainer.appendChild(newItemRow);
        itemIndex++;
    });

    itemsContainer.addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-item-btn')) {
            e.target.closest('.offer-item-row').remove();
        }
    });
});
</script>
</body>
</html>