<?php
require_once 'config.php';
require_once 'auth.php';
requireAuth();

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

// === GET ORDERS ===
if ($action === 'get_orders') {
    $filter = $_GET['filter'] ?? 'all';
    $search = $_GET['search'] ?? '';
    $sort = $_GET['sort'] ?? 'newest';
    
    // Fetch orders from Cockpit
    $orders = cockpitRequest(
        "/api/collections/get/" . COCKPIT_ORDERS_COLLECTION . "?api_key=" . COCKPIT_API_KEY,
        'POST',
        ['filter' => [], 'sort' => ['tanggal' => -1]]
    );
    
    $orders = $orders['documents'] ?? [];
    
    // Filter by status
    if ($filter !== 'all') {
        $orders = array_filter($orders, function($o) use ($filter) {
            $statusMap = [
                'diterima' => ['diterima', 'baru'],
                'packing' => ['packing', 'proses'],
                'kurir' => ['kurir', 'diserahkan'],
                'perjalanan' => ['perjalanan', 'dikirim', 'shipping'],
                'selesai' => ['selesai', 'delivered'],
                'batal' => ['batal', 'cancelled']
            ];
            $orderStatus = strtolower($o['status'] ?? 'baru');
            return in_array($orderStatus, $statusMap[$filter] ?? [$filter]);
        });
    }
    
    // Search
    if ($search) {
        $search = strtolower($search);
        $orders = array_filter($orders, function($o) use ($search) {
            return stripos($o['nama_pembeli'] ?? '', $search) !== false ||
                   stripos($o['_id'] ?? '', $search) !== false ||
                   stripos($o['daftar_barang'] ?? '', $search) !== false;
        });
    }
    
    // Sort
    if ($sort === 'oldest') {
        usort($orders, fn($a,$b) => strtotime($a['tanggal'] ?? 0) <=> strtotime($b['tanggal'] ?? 0));
    } elseif ($sort === 'highest') {
        usort($orders, fn($a,$b) => ($b['total_harga'] ?? 0) <=> ($a['total_harga'] ?? 0));
    }
    
    // Format response
    $formatted = array_map(function($o) {
        // Parse daftar_barang untuk ambil produk
        $produkList = [];
        if (!empty($o['daftar_barang'])) {
            $lines = explode("\n", $o['daftar_barang']);
            foreach ($lines as $line) {
                if (preg_match('/^-\s*(.+?)\s*\((\d+)x\)/', trim($line), $m)) {
                    $produkList[] = ['nama' => $m[1], 'qty' => (int)$m[2]];
                }
            }
        }
        
        // Extract shipping info
        preg_match('/Kurir:\s*(.+)/', $o['daftar_barang'] ?? '', $kurirMatch);
        preg_match('/Ongkir:\s*Rp\s*([\d\.]+)/', $o['daftar_barang'] ?? '', $ongkirMatch);
        
        return [
            'id' => $o['_id'] ?? '',
            'order_id' => $o['external_id'] ?? ('ORD-' . substr($o['_id'] ?? '', -8)),
            'nama' => $o['nama_pembeli'] ?? '-',
            'wa' => $o['wa'] ?? $o['no_hp'] ?? '-',
            'alamat' => $o['alamat'] ?? '-',
            'kota' => $o['kota'] ?? '-',
            'produk' => $produkList,
            'total' => $o['total_harga'] ?? 0,
            'ongkir' => isset($ongkirMatch[1]) ? (int)str_replace('.', '', $ongkirMatch[1]) : 0,
            'kurir' => $kurirMatch[1] ?? '-',
            'tanggal' => $o['tanggal'] ?? '',
            'status' => strtolower($o['status'] ?? 'baru'),
            'catatan' => $o['catatan'] ?? '',
            'invoice_url' => $o['invoice_url'] ?? ''
        ];
    }, array_values($orders));
    
    // Stats
    $stats = [
        'baru' => count(array_filter($formatted, fn($o) => in_array($o['status'], ['baru','diterima']))),
        'packing' => count(array_filter($formatted, fn($o) => in_array($o['status'], ['packing','proses']))),
        'kurir' => count(array_filter($formatted, fn($o) => in_array($o['status'], ['kurir','diserahkan']))),
        'dikirim' => count(array_filter($formatted, fn($o) => in_array($o['status'], ['perjalanan','dikirim','shipping']))),
        'selesai' => count(array_filter($formatted, fn($o) => $o['status'] === 'selesai')),
        'batal' => count(array_filter($formatted, fn($o) => in_array($o['status'], ['batal','cancelled'])))
    ];
    
    echo json_encode(['success' => true, 'orders' => $formatted, 'stats' => $stats]);
    exit;
}

// === UPDATE ORDER STATUS ===
if ($action === 'update_status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $orderId = $input['order_id'] ?? '';
    $newStatus = $input['status'] ?? '';
    $note = $input['note'] ?? '';
    
    if (!$orderId || !$newStatus) {
        echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
        exit;
    }
    
    // Fetch current order
    $current = cockpitRequest(
        "/api/collections/get/" . COCKPIT_ORDERS_COLLECTION . "?api_key=" . COCKPIT_API_KEY . "&filter={_id:'$orderId'}",
        'GET'
    );
    $order = $current['documents'][0] ?? null;
    
    if (!$order) {
        echo json_encode(['success' => false, 'message' => 'Pesanan tidak ditemukan']);
        exit;
    }
    
    // Update status in Cockpit
    $updateData = [
        'data' => [
            '_id' => $orderId,
            'status' => $newStatus,
            'status_history' => array_merge(
                $order['status_history'] ?? [],
                [[
                    'status' => $newStatus,
                    'timestamp' => date('c'),
                    'note' => $note,
                    'admin' => $_SESSION['admin_username'] ?? 'admin'
                ]]
            ),
            'updated_at' => date('c')
        ]
    ];
    
    $result = cockpitRequest(
        "/api/collections/save/" . COCKPIT_ORDERS_COLLECTION . "?api_key=" . COCKPIT_API_KEY,
        'POST',
        $updateData
    );
    
    if (isset($result['_id'])) {
        // Send Telegram notification
        $statusLabel = [
            'diterima' => '✅ Diterima',
            'packing' => '📦 Packing',
            'kurir' => '🚚 Diserahkan ke Kurir',
            'perjalanan' => '🚛 Dalam Perjalanan',
            'selesai' => '🎉 Selesai',
            'batal' => '❌ Dibatalkan'
        ][$newStatus] ?? $newStatus;
        
        $msg = "🔄 *Status Pesanan Diupdate*\n" .
               "🆔 Order: {$order['external_id'] ?? $orderId}\n" .
               "👤 Pelanggan: {$order['nama_pembeli']}\n" .
               "📊 Status Baru: $statusLabel\n" .
               ($note ? "📝 Catatan: $note\n" : "") .
               "🕐 Waktu: " . date('d/m/Y H:i:s');
        
        sendTelegram($msg);
        
        echo json_encode(['success' => true, 'message' => 'Status berhasil diperbarui']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal update ke Cockpit']);
    }
    exit;
}

// === SEND WA NOTIFICATION ===
if ($action === 'send_wa' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $wa = $input['wa'] ?? '';
    $orderId = $input['order_id'] ?? '';
    $status = $input['status'] ?? '';
    
    $statusText = [
        'diterima' => 'Pesanan Anda telah kami terima dan sedang diverifikasi.',
        'packing' => 'Pesanan Anda sedang dalam proses packing.',
        'kurir' => 'Pesanan Anda telah diserahkan ke kurir.',
        'perjalanan' => 'Pesanan Anda sedang dalam perjalanan.',
        'selesai' => 'Pesanan Anda telah diterima. Terima kasih!',
        'batal' => 'Pesanan Anda telah dibatalkan.'
    ][$status] ?? 'Status pesanan Anda telah diperbarui.';
    
    $message = "Halo, ini dari *Nadhief Herbal* 🌿\n\n" .
               "Pesanan *$orderId*:\n" .
               "$statusText\n\n" .
               "Cek status lengkap: " . ADMIN_BASE_URL . "/track?id=" . urlencode($orderId) . "\n\n" .
               "Balas chat ini jika ada pertanyaan. Terima kasih!";
    
    // Gunakan API WA Gateway (opsional) atau redirect ke wa.me
    $waLink = "https://wa.me/62" . ltrim($wa, '0') . "?text=" . urlencode($message);
    
    echo json_encode(['success' => true, 'wa_link' => $waLink]);
    exit;
}

// Default response
echo json_encode(['success' => false, 'message' => 'Action tidak valid']);
?>