<?php
require_once 'check_auth.php';

$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($order_id <= 0) {
    redirect('index.php');
}

try {
    $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? LIMIT 1");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();
    
    if (!$order) {
        redirect('index.php');
    }
} catch(PDOException $e) {
    die("Sorgu hatası: " . $e->getMessage());
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update') {
    $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
    $customer_name = isset($_POST['customer_name']) ? cleanInput($_POST['customer_name']) : '';
    $customer_phone = isset($_POST['customer_phone']) ? cleanInput($_POST['customer_phone']) : '';
    $customer_city = isset($_POST['customer_city']) ? cleanInput($_POST['customer_city']) : '';
    $customer_district = isset($_POST['customer_district']) ? cleanInput($_POST['customer_district']) : '';
    $customer_address = isset($_POST['customer_address']) ? cleanInput($_POST['customer_address']) : '';
    $payment_type = isset($_POST['payment_type']) ? cleanInput($_POST['payment_type']) : '';
    $status = isset($_POST['status']) ? cleanInput($_POST['status']) : '';
    $cargo_no = isset($_POST['cargo_no']) ? cleanInput($_POST['cargo_no']) : '';
    $notes = isset($_POST['notes']) ? cleanInput($_POST['notes']) : '';
    $product_price = isset($_POST['product_price']) ? cleanInput($_POST['product_price']) : '0.00';
    $product_price = str_replace([',', '.'], ['', '.'], $product_price);
    
    $allowed_statuses = ['pending', 'approved', 'shipped', 'delivered'];
    if (!in_array($status, $allowed_statuses)) {
        $status = 'pending';
    }
    
    if (!in_array($payment_type, ['kapidanakit', 'kapidakart'])) {
        $payment_type = 'kapidanakit';
    }
    
    $product_name = getProductName($product_id);
    
    try {
        $stmt = $pdo->prepare("UPDATE orders SET 
            product_id = ?, product_name = ?, product_price = ?,
            customer_name = ?, customer_phone = ?, customer_city = ?, customer_district = ?, customer_address = ?,
            payment_type = ?, status = ?, cargo_no = ?, notes = ?
            WHERE id = ?");
        
        $result = $stmt->execute([
            $product_id, $product_name, $product_price,
            $customer_name, $customer_phone, $customer_city, $customer_district, $customer_address,
            $payment_type, $status, $cargo_no, $notes,
            $order_id
        ]);
        
        if ($result) {
            $success = 'Sipariş başarıyla güncellendi!';
            
            $stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ? LIMIT 1");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
        } else {
            $error = 'Güncelleme başarısız!';
        }
    } catch(PDOException $e) {
        $error = 'Hata: ' . $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'delete') {
    try {
        $stmt = $pdo->prepare("DELETE FROM orders WHERE id = ?");
        $stmt->execute([$order_id]);
        redirect('index.php?deleted=1');
    } catch(PDOException $e) {
        $error = 'Silme hatası: ' . $e->getMessage();
    }
}

$page_title = 'Sipariş Detayı';
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $page_title; ?> - Max Power Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
body { background-color: #f5f7fa; }
.sidebar {
    background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%);
    min-height: 100vh;
}
.sidebar .nav-link {
    color: rgba(255,255,255,0.85);
    padding: 12px 20px;
    border-radius: 8px;
    margin: 4px 0;
}
.sidebar .nav-link:hover, .sidebar .nav-link.active {
    background: rgba(255,255,255,0.1);
    color: #fff;
}
.topbar {
    background: #fff;
    border-bottom: 1px solid #eee;
    padding: 15px 0;
}
.detail-card {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.detail-card .card-header {
    background: #fff;
    border-bottom: 1px solid #eee;
    border-radius: 12px 12px 0 0 !important;
    padding: 20px;
}
.form-label {
    font-weight: 600;
    color: #495057;
    margin-bottom: 8px;
}
.form-control, .form-select {
    padding: 10px 15px;
    border-radius: 8px;
    border: 1px solid #ddd;
}
.form-control:focus, .form-select:focus {
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    border-color: #667eea;
}
.info-label {
    font-size: 0.8rem;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
    margin-bottom: 5px;
}
.info-value {
    font-size: 1rem;
    font-weight: 600;
    color: #212529;
}
.status-badge {
    padding: 8px 16px;
    border-radius: 25px;
    font-size: 0.9rem;
    font-weight: 600;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
    <div class="col-md-2 col-lg-2 px-0 sidebar">
        <div class="p-4 text-center border-bottom border-secondary">
            <h5 class="text-white mb-0 fw-bold"><i class="fas fa-bolt me-2 text-warning"></i>Max Power</h5>
            <p class="text-white-50 small mb-0 mt-1">Admin Paneli</p>
        </div>
        <nav class="nav flex-column p-3">
            <a href="index.php" class="nav-link active">
                <i class="fas fa-list-alt me-2"></i> Siparişler
            </a>
            <a href="ads.php" class="nav-link">
                <i class="fas fa-ad me-2"></i> Reklam Pikselleri
            </a>
            <a href="logout.php" class="nav-link mt-3" style="color:#ff6b6b;">
                <i class="fas fa-sign-out-alt me-2"></i> Çıkış
            </a>
        </nav>
    </div>
    
    <div class="col-md-10 col-lg-10 px-0">
        <div class="topbar px-4">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-1 small">
                            <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none">Siparişler</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Sipariş Detayı</li>
                        </ol>
                    </nav>
                    <h4 class="mb-0 fw-bold">
                        <i class="fas fa-file-invoice me-2 text-primary"></i>
                        Sipariş: <span class="text-primary"><?php echo $order['order_no']; ?></span>
                        <?php echo getStatusBadge($order['status']); ?>
                    </h4>
                </div>
                <a href="index.php" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>Geri Dön
                </a>
            </div>
        </div>
        
        <div class="p-4">
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show mb-4" role="alert">
                    <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="card detail-card mb-4">
                        <div class="card-header">
                            <h6 class="mb-0 fw-bold"><i class="fas fa-info-circle me-2 text-primary"></i>Sipariş Bilgileri</h6>
                        </div>
                        <div class="card-body p-4">
                            <div class="row g-3">
                                <div class="col-12">
                                    <div class="info-label">Sipariş Numarası</div>
                                    <div class="info-value text-primary"><?php echo $order['order_no']; ?></div>
                                </div>
                                <div class="col-12">
                                    <div class="info-label">Oluşturulma Tarihi</div>
                                    <div class="info-value"><?php echo date('d.m.Y H:i:s', strtotime($order['created_at'])); ?></div>
                                </div>
                                <div class="col-12">
                                    <div class="info-label">Son Güncelleme</div>
                                    <div class="info-value"><?php echo date('d.m.Y H:i:s', strtotime($order['updated_at'])); ?></div>
                                </div>
                                <div class="col-12">
                                    <div class="info-label">Ödeme Şekli</div>
                                    <div class="info-value">
                                        <?php echo getPaymentBadge($order['payment_type']); ?>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="info-label">Sipariş Tutarı</div>
                                    <div class="info-value text-success fs-4"><?php echo number_format($order['product_price'], 2, ',', '.'); ?> ₺</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card detail-card mb-4">
                        <div class="card-header bg-danger bg-opacity-10">
                            <h6 class="mb-0 fw-bold text-danger"><i class="fas fa-exclamation-triangle me-2"></i>Tehlikeli İşlemler</h6>
                        </div>
                        <div class="card-body p-4">
                            <button type="button" class="btn btn-outline-danger w-100" data-bs-toggle="modal" data-bs-target="#deleteModal">
                                <i class="fas fa-trash me-1"></i>Bu Siparişi Sil
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-8">
                    <form method="POST">
                        <input type="hidden" name="action" value="update">
                        
                        <div class="card detail-card mb-4">
                            <div class="card-header">
                                <h6 class="mb-0 fw-bold"><i class="fas fa-box me-2 text-primary"></i>Ürün & Durum Bilgileri</h6>
                            </div>
                            <div class="card-body p-4">
                                <div class="row g-3">
                                    <div class="col-md-8">
                                        <label class="form-label">Ürün</label>
                                        <select name="product_id" class="form-select" required>
                                            <?php global $products; foreach ($products as $pid => $pdata): ?>
                                                <option value="<?php echo $pid; ?>" <?php echo ($order['product_id'] == $pid) ? 'selected' : ''; ?>>
                                                    <?php echo $pdata['name']; ?> - <?php echo number_format($pdata['price'], 2, ',', '.'); ?> ₺
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Tutar (₺)</label>
                                        <input type="text" name="product_price" class="form-control" value="<?php echo number_format($order['product_price'], 2, ',', ''); ?>">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Sipariş Durumu</label>
                                        <select name="status" class="form-select" required>
                                            <option value="pending" <?php echo ($order['status'] == 'pending') ? 'selected' : ''; ?>>⏳ Onay Bekleyen</option>
                                            <option value="approved" <?php echo ($order['status'] == 'approved') ? 'selected' : ''; ?>>✅ Onaylanan</option>
                                            <option value="shipped" <?php echo ($order['status'] == 'shipped') ? 'selected' : ''; ?>>🚚 Kargoda</option>
                                            <option value="delivered" <?php echo ($order['status'] == 'delivered') ? 'selected' : ''; ?>>🏠 Teslim Edilen</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Kargo Takip Numarası</label>
                                        <input type="text" name="cargo_no" class="form-control" value="<?php echo htmlspecialchars($order['cargo_no']); ?>" placeholder="Kargo takip no girin">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card detail-card mb-4">
                            <div class="card-header">
                                <h6 class="mb-0 fw-bold"><i class="fas fa-user me-2 text-primary"></i>Müşteri Bilgileri</h6>
                            </div>
                            <div class="card-body p-4">
                                <div class="row g-3">
                                    <div class="col-md-12">
                                        <label class="form-label">Adı Soyadı</label>
                                        <input type="text" name="customer_name" class="form-control" value="<?php echo htmlspecialchars($order['customer_name']); ?>" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Telefon Numarası</label>
                                        <input type="tel" name="customer_phone" class="form-control" value="<?php echo htmlspecialchars($order['customer_phone']); ?>" required>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">İl</label>
                                        <input type="text" name="customer_city" class="form-control" value="<?php echo htmlspecialchars($order['customer_city']); ?>" required>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">İlçe</label>
                                        <input type="text" name="customer_district" class="form-control" value="<?php echo htmlspecialchars($order['customer_district']); ?>" required>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Açık Adres</label>
                                        <textarea name="customer_address" class="form-control" rows="3" required><?php echo htmlspecialchars($order['customer_address']); ?></textarea>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Ödeme Şekli</label>
                                        <select name="payment_type" class="form-select" required>
                                            <option value="kapidanakit" <?php echo ($order['payment_type'] == 'kapidanakit') ? 'selected' : ''; ?>>Kapıda Nakit</option>
                                            <option value="kapidakart" <?php echo ($order['payment_type'] == 'kapidakart') ? 'selected' : ''; ?>>Kapıda Kredi Kartı</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card detail-card mb-4">
                            <div class="card-header">
                                <h6 class="mb-0 fw-bold"><i class="fas fa-sticky-note me-2 text-primary"></i>Yönetici Notları</h6>
                            </div>
                            <div class="card-body p-4">
                                <textarea name="notes" class="form-control" rows="3" placeholder="Sipariş hakkında notlarınız..."><?php echo htmlspecialchars($order['notes']); ?></textarea>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2 justify-content-end">
                            <a href="index.php" class="btn btn-lg btn-outline-secondary">
                                <i class="fas fa-times me-1"></i>İptal
                            </a>
                            <button type="submit" class="btn btn-lg btn-primary px-5">
                                <i class="fas fa-save me-1"></i>Değişiklikleri Kaydet
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Siparişi Sil</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center py-4">
                <i class="fas fa-trash fa-4x text-danger mb-3"></i>
                <p class="mb-0">Bu siparişi silmek istediğinize emin misiniz?</p>
                <p class="text-muted small"><strong><?php echo $order['order_no']; ?></strong> - <?php echo $order['customer_name']; ?></p>
                <p class="text-danger fw-bold small">Bu işlem geri alınamaz!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Vazgeç</button>
                <form method="POST" style="display:inline;">
                    <input type="hidden" name="action" value="delete">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-1"></i>Evet, Sil
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
