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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_name = $_POST['customer_name'] ?? '';
    $customer_surname = $_POST['customer_surname'] ?? '';
    $address = $_POST['address'] ?? '';
    $phone_number = $_POST['phone_number'] ?? '';
    $items = $_POST['items'] ?? [];
    $request_date = date('Y-m-d');
    $created_by_user_id = $_SESSION['user_id'];
    
    try {
        $conn->beginTransaction();
        
        $stmt_request = $conn->prepare("INSERT INTO requests (customer_name, customer_surname, address, phone_number, request_date, created_by_user_id) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt_request->execute([$customer_name, $customer_surname, $address, $phone_number, $request_date, $created_by_user_id]);
        $request_id = $conn->lastInsertId();

        foreach ($items as $item) {
            $item_description = $item['description'] ?? '';
            $stmt_item = $conn->prepare("INSERT INTO request_items (request_id, item_description) VALUES (?, ?)");
            $stmt_item->execute([$request_id, $item_description]);
        }
        
        $conn->commit();
        
        $message = "Yeni talep başarıyla oluşturuldu!";
        $message_type = 'success';
        header('Location: requests.php?status=success&message=' . urlencode($message));
        exit;

    } catch (PDOException $e) {
        $conn->rollBack();
        $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 Talep 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 Talep 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_request.php" method="POST">
    <div class="form-section-title">Müşteri Bilgileri</div>
    <div class="form-grid">
        <div class="form-group">
            <label for="customer_name">Müşteri Adı *</label>
            <input type="text" id="customer_name" name="customer_name" required>
        </div>
        <div class="form-group">
            <label for="customer_surname">Müşteri Soyadı *</label>
            <input type="text" id="customer_surname" name="customer_surname" required>
        </div>
        <div class="form-group">
            <label for="phone_number">Telefon Numarası *</label>
            <input type="text" id="phone_number" name="phone_number" required>
        </div>
        <div class="form-group full-width">
            <label for="address">Açık Adres *</label>
            <textarea id="address" name="address" rows="3" required></textarea>
        </div>
    </div>
    
    <div class="form-section-title">Talep Edilen İşler</div>
    <div id="request-items-container">
        <div class="form-grid request-item-row">
            <div class="form-group full-width">
                <label for="item_description[]">Yapılacak İş</label>
                <input type="text" name="items[0][description]" placeholder="Örn: Evin elektrik tesisatı kontrolü" required>
            </div>
        </div>
    </div>
    <div class="form-actions full-width">
        <button type="button" id="add-item-btn" class="secondary-btn">Yeni İş Kalemi Ekle</button>
    </div>

    <div class="form-actions full-width">
        <button type="submit">Talep Oluştur</button>
    </div>
</form>
</main>
<script>
document.addEventListener('DOMContentLoaded', function() {
    let itemIndex = 1;
    const addItemBtn = document.getElementById('add-item-btn');
    const itemsContainer = document.getElementById('request-items-container');

    addItemBtn.addEventListener('click', function() {
        const newItemRow = document.createElement('div');
        newItemRow.classList.add('form-grid', 'request-item-row');
        newItemRow.innerHTML = `
            <div class="form-group full-width">
                <label for="item_description[]">Yapılacak İş</label>
                <input type="text" name="items[${itemIndex}][description]" placeholder="Örn: Evin elektrik tesisatı kontrolü" required>
            </div>
            <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('.request-item-row').remove();
        }
    });
});
</script>
</body>
</html>