<?php
/**
 * Admin Orders API
 * Order management for admin
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../includes/Auth.php';
require_once __DIR__ . '/../../includes/Order.php';

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

// Check admin authentication
$auth = new Auth();
if (!$auth->isAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$order = new Order();
$db = Database::getInstance();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                $page = $_GET['page'] ?? 1;
                $perPage = $_GET['per_page'] ?? 20;
                $status = $_GET['status'] ?? null;
                
                $sql = "SELECT o.*, u.first_name, u.last_name, u.email, u.phone,
                               COUNT(oi.id) as items_count
                        FROM orders o
                        LEFT JOIN users u ON o.user_id = u.id
                        LEFT JOIN order_items oi ON o.id = oi.order_id
                        WHERE 1=1";
                $params = [];
                
                if ($status) {
                    $sql .= " AND o.order_status = ?";
                    $params[] = $status;
                }
                
                $sql .= " GROUP BY o.id ORDER BY o.created_at DESC";
                $sql .= " LIMIT ? OFFSET ?";
                $params[] = $perPage;
                $params[] = ($page - 1) * $perPage;
                
                $orders = $db->fetchAll($sql, $params);
                
                // Get total count
                $countSql = "SELECT COUNT(DISTINCT o.id) as total FROM orders o WHERE 1=1";
                $countParams = [];
                if ($status) {
                    $countSql .= " AND o.order_status = ?";
                    $countParams[] = $status;
                }
                $totalResult = $db->fetchOne($countSql, $countParams);
                $total = $totalResult['total'] ?? 0;
                
                echo json_encode([
                    'success' => true,
                    'orders' => $orders,
                    'total' => $total,
                    'page' => $page,
                    'per_page' => $perPage
                ]);
            } elseif ($action === 'get') {
                $id = $_GET['id'] ?? 0;
                $orderData = $order->getOrderById($id);
                
                if ($orderData) {
                    $orderItems = $order->getOrderItems($id);
                    $orderData['items'] = $orderItems;
                    echo json_encode(['success' => true, 'order' => $orderData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Order not found']);
                }
            }
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'update-status') {
                $id = $data['id'] ?? 0;
                $status = $data['status'] ?? '';
                
                $db->execute(
                    "UPDATE orders SET order_status = ?, updated_at = NOW() WHERE id = ?",
                    [$status, $id]
                );
                
                echo json_encode(['success' => true]);
            } elseif ($action === 'update-payment-status') {
                $id = $data['id'] ?? 0;
                $paymentStatus = $data['payment_status'] ?? '';
                
                $db->execute(
                    "UPDATE orders SET payment_status = ?, updated_at = NOW() WHERE id = ?",
                    [$paymentStatus, $id]
                );
                
                echo json_encode(['success' => true]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

