<?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();
$stock_items = [];
$subcontractors = [];
$supplier_prices_by_item = [];

try {
    $stmt = $conn->prepare("SELECT id, item_name FROM stock_items WHERE is_active = 1 ORDER BY item_name ASC");
    $stmt->execute();
    $stock_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $conn->prepare("SELECT id, subcontractor_name FROM subcontractors ORDER BY subcontractor_name ASC");
    $stmt->execute();
    $subcontractors = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt_prices = $conn->prepare("SELECT sp.stock_item_id, sp.price, s.supplier_name, s.id as supplier_id FROM supplier_products sp JOIN suppliers s ON sp.supplier_id = s.id ORDER BY sp.price ASC");
    $stmt_prices->execute();
    $all_supplier_prices = $stmt_prices->fetchAll(PDO::FETCH_ASSOC);
    foreach ($all_supplier_prices as $price_row) {
        $stock_item_id = $price_row['stock_item_id'];
        if (!isset($supplier_prices_by_item[$stock_item_id])) {
            $supplier_prices_by_item[$stock_item_id] = [];
        }
        $supplier_prices_by_item[$stock_item_id][] = [
            'supplier_id' => $price_row['supplier_id'],
            'supplier_name' => $price_row['supplier_name'],
            'price' => $price_row['price']
        ];
    }
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_id = $_POST['item_id'] ?? null;
    $quantity = $_POST['quantity'] ?? 0;
    $notes = $_POST['notes'] ?? '';
    $department = $_POST['department'] ?? '';
    $urgency = $_POST['urgency'] ?? 'normal';
    $supplier_id = $_POST['supplier_id'] ?? null;
    $subcontractor_id = $_POST['subcontractor_id'] ?? null;
    $requested_by_user_id = $_SESSION['user_id'];
    $request_date = date('Y-m-d');
    $request_no = 'TALEP-' . date('Y') . '-' . uniqid();

    // Boş gelen değerleri NULL olarak ayarla
    $item_id = !empty($item_id) ? $item_id : null;
    $supplier_id = !empty($supplier_id) ? $supplier_id : null;
    $subcontractor_id = !empty($subcontractor_id) ? $subcontractor_id : null;

    try {
        $stmt = $conn->prepare("INSERT INTO purchase_requests (request_no, item_id, supplier_id, subcontractor_id, quantity, notes, requested_by_user_id, request_date, department, urgency) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$request_no, $item_id, $supplier_id, $subcontractor_id, $quantity, $notes, $requested_by_user_id, $request_date, $department, $urgency]);
        
        $message = 'Yeni ürün talebi başarıyla oluşturuldu!';
        $message_type = 'success';
        header('Location: purchase_requests.php?status=success&message=' . urlencode($message));
        exit;
    } catch (PDOException $e) {
        $message = 'Hata: Talep oluşturulurken bir sorun oluştu. ' . $e->getMessage();
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Yeni Ürün Talebi Oluştur</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>Yeni Ürün Talebi 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_purchase_request.php" method="POST">
        <div class="form-section-title">Genel Bilgiler</div>
        <div class="form-grid">
            <div class="form-group">
                <label for="department">Hangi Bölüm İçin?</label>
                <input type="text" id="department" name="department" required>
            </div>
            <div class="form-group">
                <label for="item_id">Ürün/Malzeme Adı:</label>
                <select id="item_id" name="item_id" required>
                    <option value="">Seçiniz</option>
                    <?php foreach ($stock_items as $item): ?>
                        <option value="<?php echo $item['id']; ?>"><?php echo htmlspecialchars($item['item_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="quantity">Miktar:</label>
                <input type="number" id="quantity" name="quantity" min="1" required>
            </div>
            <div class="form-group">
                <label for="urgency">Aciliyet Durumu:</label>
                <select id="urgency" name="urgency" required>
                    <option value="normal">Normal</option>
                    <option value="urgent">Acil</option>
                    <option value="critical">Kritik</option>
                </select>
            </div>
        </div>
        
        <div class="form-section-title">Sağlayıcı ve Fiyat Bilgisi</div>
        <div class="form-grid" id="supplier-subcontractor-section">
            <div class="form-group full-width">
                <p>Seçilen ürün için tedarikçi seçimi:</p>
                <div id="supplier-prices-list">
                    </div>
            </div>
            <div class="form-group full-width">
                <label for="subcontractor_id">Taşeron Firma (Hizmet Talebi için):</label>
                <div class="form-group-with-btn">
                    <select id="subcontractor_id" name="subcontractor_id">
                        <option value="">Seçiniz</option>
                        <?php foreach ($subcontractors as $subcontractor): ?>
                            <option value="<?php echo $subcontractor['id']; ?>"><?php echo htmlspecialchars($subcontractor['subcontractor_name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" id="no-subcontractor-btn" class="secondary-btn" style="background-color: #6c757d;">Taşeron ile Çalışmayacak</button>
                </div>
            </div>
        </div>

        <div class="form-group full-width">
            <label for="notes">Notlar/Açıklama:</label>
            <textarea id="notes" name="notes" rows="5"></textarea>
        </div>
        <div class="form-actions full-width">
            <button type="submit">Talep Oluştur</button>
        </div>
    </form>
</main>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const itemSelect = document.getElementById('item_id');
    const supplierPricesList = document.getElementById('supplier-prices-list');
    const subcontractorSelect = document.getElementById('subcontractor_id');
    const noSubcontractorBtn = document.getElementById('no-subcontractor-btn');

    const allSupplierPrices = <?php echo json_encode($supplier_prices_by_item); ?>;

    itemSelect.addEventListener('change', function() {
        const itemId = this.value;

        supplierPricesList.innerHTML = '';
        if (itemId) {
            subcontractorSelect.value = '';
            const suppliersForThisItem = allSupplierPrices[itemId] || [];
            if (suppliersForThisItem.length > 0) {
                suppliersForThisItem.forEach(supplier => {
                    const radioDiv = document.createElement('div');
                    radioDiv.classList.add('supplier-option');
                    radioDiv.innerHTML = `
                        <label>
                            <input type="radio" name="supplier_id" value="${supplier.supplier_id}">
                            ${supplier.supplier_name} - ${parseFloat(supplier.price).toFixed(2)} TL
                        </label>
                    `;
                    supplierPricesList.appendChild(radioDiv);
                });
            } else {
                supplierPricesList.innerHTML = '<p>Bu ürün için tedarikçi bulunamadı.</p>';
            }
        }
    });

    noSubcontractorBtn.addEventListener('click', function() {
        subcontractorSelect.value = '';
    });
});
</script>
<style>
    .supplier-option label {
        display: block;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 8px;
        margin-bottom: 5px;
        transition: background-color 0.2s;
    }
    .supplier-option label:hover {
        background-color: #f0f4f8;
    }
    .supplier-option input[type="radio"]:checked + label {
        background-color: #e6f2ff;
        border-color: #007bff;
    }
    .form-group-with-btn {
        display: flex;
        gap: 10px;
    }
</style>
</body>
</html>