<?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 = '';
$sale = null;
$sale_id = $_REQUEST['id'] ?? 0;
$offers = [];
if ($sale_id > 0) {
    try {
        $stmt = $conn->prepare("SELECT * FROM sales WHERE id = ?");
        $stmt->execute([$sale_id]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$sale) {
            $message = 'Düzenlemek istediğiniz satış kaydı bulunamadı.';
            $message_type = 'error';
        }
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
try {
    $stmt_offers = $conn->prepare("SELECT id, offer_no, customer_name FROM offers ORDER BY offer_date DESC");
    $stmt_offers->execute();
    $offers = $stmt_offers->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $sale) {
    $offer_id = $_POST['offer_id'] ?? $sale['offer_id'];
    $customer_name = $_POST['customer_name'] ?? $sale['customer_name'];
    $customer_email = $_POST['customer_email'] ?? $sale['customer_email'];
    $total_price = $_POST['total_price'] ?? $sale['total_price'];
    $status = $_POST['status'] ?? $sale['status'];
    $notes = $_POST['notes'] ?? $sale['notes'];
    try {
        $stmt = $conn->prepare("UPDATE sales SET offer_id = ?, customer_name = ?, customer_email = ?, total_price = ?, status = ?, notes = ? WHERE id = ?");
        $stmt->execute([$offer_id, $customer_name, $customer_email, $total_price, $status, $notes, $sale_id]);
        $message = 'Satış kaydı başarıyla güncellendi.';
        $message_type = 'success';
        $stmt = $conn->prepare("SELECT * FROM sales WHERE id = ?");
        $stmt->execute([$sale_id]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $message = 'Güncelleme sırasında bir hata oluştu: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$sale && $sale_id > 0) {
    echo "Hata: Satış kaydı bulunamadı veya yetkiniz yok.";
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Satış Kaydı Düzenle: <?php echo htmlspecialchars($sale['sale_no'] ?? ''); ?></title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
    <h2>Satış Kaydı 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 ($sale): ?>
    <form action="edit_sale.php" method="POST">
        <input type="hidden" name="id" value="<?php echo $sale['id']; ?>">
        <div class="form-grid">
            <div class="form-group">
                <label for="sale_no">Satış No:</label>
                <input type="text" id="sale_no" value="<?php echo htmlspecialchars($sale['sale_no']); ?>" disabled>
            </div>
            <div class="form-group">
                <label for="offer_id">İlgili Teklif:</label>
                <select id="offer_id" name="offer_id">
                    <option value="">İlişkilendirme Yok</option>
                    <?php foreach ($offers as $offer): ?>
                        <option value="<?php echo $offer['id']; ?>" <?php echo $sale['offer_id'] === $offer['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($offer['offer_no'] . ' - ' . $offer['customer_name']); ?>
                        </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($sale['customer_name']); ?>" required>
            </div>
            <div class="form-group">
                <label for="customer_email">Müşteri E-posta:</label>
                <input type="email" id="customer_email" name="customer_email" value="<?php echo htmlspecialchars($sale['customer_email']); ?>">
            </div>
            <div class="form-group">
                <label for="total_price">Toplam Fiyat (TL):</label>
                <input type="number" id="total_price" name="total_price" step="0.01" value="<?php echo htmlspecialchars($sale['total_price']); ?>" required>
            </div>
            <div class="form-group">
                <label for="status">Durum:</label>
                <select id="status" name="status">
                    <option value="invoiced" <?php echo $sale['status'] === 'invoiced' ? 'selected' : ''; ?>>Faturalandırıldı</option>
                    <option value="paid" <?php echo $sale['status'] === 'paid' ? 'selected' : ''; ?>>Ödendi</option>
                    <option value="partially_paid" <?php echo $sale['status'] === 'partially_paid' ? 'selected' : ''; ?>>Kısmen Ödendi</option>
                    <option value="cancelled" <?php echo $sale['status'] === 'cancelled' ? 'selected' : ''; ?>>İptal Edildi</option>
                </select>
            </div>
        </div>
        <div class="form-group full-width">
            <label for="notes">Notlar:</label>
            <textarea id="notes" name="notes" rows="5"><?php echo htmlspecialchars($sale['notes']); ?></textarea>
        </div>
        <div class="form-actions full-width">
            <button type="submit">Güncelle</button>
        </div>
    </form>
    <?php endif; ?>
</main>
</body>
</html>