<?php
/**
 * Orders API Endpoint
 * Fetches orders from database with pagination and search
 */

require_once '../../includes/db_connection.php';
require_once '../includes/auth.php';

// Require authentication
requireAuth();

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

// Handle POST requests (Actions)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db = Database::getInstance()->getConnection();
        
        $action = $_POST['action'] ?? '';
        $id = $_POST['id'] ?? null;
        
        if (!$id) {
            throw new Exception('Order ID is required');
        }

        // --- ACTIONS ---

        // Fulfill Order (Simple)
        if ($action === 'fulfill') {
            $log = "\n[" . date('M d, Y g:i A') . "] Order fulfilled by admin";
            $stmt = $db->prepare("UPDATE orders SET fulfillment_status = 'fulfilled', delivery_status = 'processing', notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$log, $id])) {
                echo json_encode(['success' => true, 'message' => 'Order fulfilled successfully']);
            } else {
                throw new Exception('Failed to fulfill order');
            }
        } 
        // Hold Order
        elseif ($action === 'hold') {
            $log = "\n[" . date('M d, Y g:i A') . "] Order placed on HOLD by admin";
            $stmt = $db->prepare("UPDATE orders SET delivery_status = 'on_hold', notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$log, $id])) {
                echo json_encode(['success' => true, 'message' => 'Order placed on hold successfully']);
            } else {
                throw new Exception('Failed to place order on hold');
            }
        }
        // Refund Order
        elseif ($action === 'refund') {
            $log = "\n[" . date('M d, Y g:i A') . "] Order REFUNDED by admin";
            $stmt = $db->prepare("UPDATE orders SET payment_status = 'refunded', delivery_status = 'cancelled', fulfillment_status = 'unfulfilled', notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$log, $id])) {
                echo json_encode(['success' => true, 'message' => 'Order refunded successfully']);
            } else {
                throw new Exception('Failed to refund order');
            }
        }
        // Cancel Order
        elseif ($action === 'cancel') {
            $log = "\n[" . date('M d, Y g:i A') . "] Order CANCELLED by admin";
            $stmt = $db->prepare("UPDATE orders SET delivery_status = 'cancelled', fulfillment_status = 'unfulfilled', notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$log, $id])) {
                echo json_encode(['success' => true, 'message' => 'Order cancelled successfully']);
            } else {
                throw new Exception('Failed to cancel order');
            }
        }
        // Add Note
        elseif ($action === 'add_note') {
            $note = trim($_POST['note'] ?? '');
            if (empty($note)) throw new Exception('Note cannot be empty');
            
            // Append note with timestamp
            $timestamp = date('M d, Y g:i A');
            $append = "\n[{$timestamp}] Note: {$note}";
            
            $stmt = $db->prepare("UPDATE orders SET notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$append, $id])) {
                echo json_encode(['success' => true, 'message' => 'Note added successfully']);
            } else {
                throw new Exception('Failed to add note');
            }
        }
        
        // Add Tracking Number
        elseif ($action === 'add_tracking') {
            $tracking = trim($_POST['tracking_number'] ?? '');
            if (empty($tracking)) throw new Exception('Tracking number cannot be empty');
            
            $timestamp = date('M d, Y g:i A');
            $log = "\n[{$timestamp}] Tracking Number added: {$tracking}";
            $log .= "\n[{$timestamp}] Order status updated to In Transit";

            // Update tracking number and force delivery status to 'in_transit'
            $stmt = $db->prepare("UPDATE orders SET tracking_number = ?, delivery_status = 'in_transit', notes = CONCAT(COALESCE(notes, ''), ?), updated_at = NOW() WHERE id = ?");
            if ($stmt->execute([$tracking, $log, $id])) {
                echo json_encode(['success' => true, 'message' => 'Tracking number added successfully']);
            } else {
                throw new Exception('Failed to add tracking number');
            }
        }
        
        // Update Address
        elseif ($action === 'update_address') {
            $type = $_POST['type'] ?? 'shipping'; // shipping or billing
            $line1 = $_POST['address_line1'] ?? '';
            $city = $_POST['city'] ?? '';
            // ... (Basic implementation for now, expandable)
            // For now, let's keep it simple and safe.
             throw new Exception('Address update not yet implemented safely.');
        }

        else {
             throw new Exception("Invalid action: $action");
        }
        exit;

    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit;
    }
}

// Handle GET Requests
// (Implicitly handled if we reach here)

try {
    $db = Database::getInstance()->getConnection();
    
    // Get parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';
    $offset = ($page - 1) * $limit;
    
    // Build query
    $where = [];
    $params = [];
    
    if (!empty($search)) {
        $where[] = "(order_number LIKE ? OR customer_first_name LIKE ? OR customer_last_name LIKE ? OR customer_email LIKE ?)";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
        $params[] = "%{$search}%";
    }
    
    if (!empty($status)) {
        $where[] = "payment_status = ?";
        $params[] = $status;
    }
    
    $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total FROM orders $whereClause";
    $stmt = $db->prepare($countQuery);
    $stmt->execute($params);
    $totalOrders = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get orders with item counts
    $query = "
        SELECT 
            o.id,
            o.order_number,
            o.customer_first_name,
            o.customer_last_name,
            o.total_amount,
            o.payment_status,
            o.fulfillment_status,
            o.delivery_status,
            o.delivery_method,
            o.created_at,
            (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as item_count
        FROM orders o
        $whereClause
        ORDER BY o.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format orders
    $formattedOrders = [];
    foreach ($orders as $order) {
        $formattedOrders[] = [
            'id' => $order['id'],
            'order_number' => $order['order_number'],
            'customer_name' => $order['customer_first_name'] . ' ' . $order['customer_last_name'],
            'total_amount' => number_format($order['total_amount'], 2),
            'payment_status' => $order['payment_status'],
            'fulfillment_status' => $order['fulfillment_status'],
            'delivery_status' => $order['delivery_status'],
            'delivery_method' => ucfirst($order['delivery_method']),
            'item_count' => $order['item_count'],
            'created_at' => date('M d, Y \a\t h:i A', strtotime($order['created_at']))
        ];
    }
    
    // Calculate pagination
    $totalPages = ceil($totalOrders / $limit);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $formattedOrders,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_orders' => $totalOrders,
            'per_page' => $limit,
            'has_next' => $page < $totalPages,
            'has_prev' => $page > 1
        ]
    ]);
    
} catch (Exception $e) {
    error_log('Orders API error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch orders'
    ]);
}
?>
