<?php
require_once 'check_auth.php';

$type = isset($_GET['type']) ? cleanInput($_GET['type']) : 'all';
$status_filter = isset($_GET['status']) ? cleanInput($_GET['status']) : '';
$search = isset($_GET['search']) ? cleanInput($_GET['search']) : '';

$where = [];
$params = [];

switch ($type) {
    case 'pending':
        $where[] = "status = 'pending'";
        $filename = 'onay-bekleyen-siparisler';
        break;
    case 'approved':
        $where[] = "status = 'approved'";
        $filename = 'onaylanan-siparisler';
        break;
    case 'shipped':
        $where[] = "status = 'shipped'";
        $filename = 'kargodaki-siparisler';
        break;
    case 'delivered':
        $where[] = "status = 'delivered'";
        $filename = 'teslim-edilen-siparisler';
        break;
    case 'all':
    default:
        if (!empty($status_filter) && $status_filter != 'all') {
            $where[] = "status = ?";
            $params[] = $status_filter;
        }
        if (!empty($search)) {
            $where[] = "(order_no LIKE ? OR customer_name LIKE ? OR customer_phone LIKE ?)";
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }
        $filename = 'tum-siparisler';
        break;
}

$whereSql = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : '';

try {
    $stmt = $pdo->prepare("SELECT * FROM orders" . $whereSql . " ORDER BY created_at DESC");
    $stmt->execute($params);
    $orders = $stmt->fetchAll();
} catch(PDOException $e) {
    die("Sorgu hatası: " . $e->getMessage());
}

$filename .= '-' . date('Ymd-His') . '.xls';

header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

echo "\xEF\xBB\xBF";
?>
<!DOCTYPE html>
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--[if gte mso 9]><xml>
<x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Siparişler</x:Name>
<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>
</xml><![endif]-->
<style>
table { border-collapse: collapse; }
th { background-color: #4472C4; color: white; font-weight: bold; padding: 10px; border: 1px solid #ddd; text-align: left; }
td { padding: 8px; border: 1px solid #ddd; }
tr:nth-child(even) { background-color: #f2f2f2; }
.status-pending { background-color: #fff3cd; color: #856404; }
.status-approved { background-color: #d1ecf1; color: #0c5460; }
.status-shipped { background-color: #cce5ff; color: #004085; }
.status-delivered { background-color: #d4edda; color: #155724; }
</style>
</head>
<body>
<table border="1">
    <thead>
        <tr>
            <th>#</th>
            <th>Sipariş No</th>
            <th>Sipariş Tarihi</th>
            <th>Ad Soyad</th>
            <th>Telefon</th>
            <th>İl</th>
            <th>İlçe</th>
            <th>Adres</th>
            <th>Ürün</th>
            <th>Tutar (₺)</th>
            <th>Ödeme Şekli</th>
            <th>Durum</th>
            <th>Kargo No</th>
            <th>Notlar</th>
            <th>Son Güncelleme</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($orders)): ?>
        <tr>
            <td colspan="15" align="center">Kayıtlı sipariş bulunamadı.</td>
        </tr>
        <?php else: ?>
        <?php $i = 1; $total = 0; foreach ($orders as $order): $total += (float)$order['product_price']; ?>
        <tr class="status-<?php echo $order['status']; ?>">
            <td><?php echo $i++; ?></td>
            <td><?php echo $order['order_no']; ?></td>
            <td><?php echo date('d.m.Y H:i', strtotime($order['created_at'])); ?></td>
            <td><?php echo $order['customer_name']; ?></td>
            <td><?php echo $order['customer_phone']; ?></td>
            <td><?php echo $order['customer_city']; ?></td>
            <td><?php echo $order['customer_district']; ?></td>
            <td style="mso-number-format:'\@';"><?php echo $order['customer_address']; ?></td>
            <td><?php echo $order['product_name']; ?></td>
            <td align="right"><?php echo number_format($order['product_price'], 2, ',', '.'); ?></td>
            <td><?php echo getPaymentLabel($order['payment_type']); ?></td>
            <td><?php echo getStatusLabel($order['status']); ?></td>
            <td><?php echo $order['cargo_no']; ?></td>
            <td><?php echo $order['notes']; ?></td>
            <td><?php echo date('d.m.Y H:i', strtotime($order['updated_at'])); ?></td>
        </tr>
        <?php endforeach; ?>
        <tr style="background-color: #4472C4; color: white; font-weight: bold;">
            <td colspan="9" align="right">TOPLAM:</td>
            <td align="right"><?php echo number_format($total, 2, ',', '.'); ?> ₺</td>
            <td colspan="5">Toplam Sipariş: <?php echo count($orders); ?></td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>
</body>
</html>
