<?php
/**
 * Orders API Routes
 * 
 * Handles CRUD operations for orders and order management.
 */

require_once '../lib/Auth.php';
require_once '../lib/Validation.php';

$auth = new Auth();
$validation = new Validation();
$response = new Response();
$db = getDB();

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$id = $_GET['id'] ?? null;
$action = $_GET['action'] ?? '';

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if ($id) {
            // Get single order with items
            $stmt = $db->prepare("
                SELECT o.*, u.name as customer_name, u.email as customer_email, u.phone as customer_phone
                FROM orders o 
                LEFT JOIN users u ON o.customer_id = u.id 
                WHERE o.id = ?
            ");
            $stmt->execute([$id]);
            $order = $stmt->fetch();
            
            if (!$order) {
                $response->notFound('Order not found');
            }
            
            // Get order items
            $stmt = $db->prepare("
                SELECT oi.*, p.name as product_name, p.image_url as product_image
                FROM order_items oi 
                JOIN products p ON oi.product_id = p.id 
                WHERE oi.order_id = ?
            ");
            $stmt->execute([$id]);
            $order['items'] = $stmt->fetchAll();
            
            $response->success($order);
            
        } else {
            // Get all orders with filtering and pagination
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = min(50, max(1, intval($_GET['limit'] ?? 20)));
            $offset = ($page - 1) * $limit;
            
            $status = $_GET['status'] ?? null;
            $customer_id = $_GET['customer_id'] ?? null;
            $date_from = $_GET['date_from'] ?? null;
            $date_to = $_GET['date_to'] ?? null;
            
            $where_conditions = [];
            $params = [];
            
            if ($status) {
                $where_conditions[] = "o.status = ?";
                $params[] = $status;
            }
            
            if ($customer_id) {
                $where_conditions[] = "o.customer_id = ?";
                $params[] = $customer_id;
            }
            
            if ($date_from) {
                $where_conditions[] = "DATE(o.created_at) >= ?";
                $params[] = $date_from;
            }
            
            if ($date_to) {
                $where_conditions[] = "DATE(o.created_at) <= ?";
                $params[] = $date_to;
            }
            
            $where_clause = $where_conditions ? "WHERE " . implode(' AND ', $where_conditions) : "";
            
            // Get orders
            $stmt = $db->prepare("
                SELECT o.*, u.name as customer_name 
                FROM orders o 
                LEFT JOIN users u ON o.customer_id = u.id 
                $where_clause 
                ORDER BY o.created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            $orders = $stmt->fetchAll();
            
            // Get total count
            $stmt = $db->prepare("SELECT COUNT(*) as total FROM orders o $where_clause");
            $count_params = array_slice($params, 0, count($params) - 2);
            $stmt->execute($count_params);
            $total = $stmt->fetch()['total'];
            
            $response->success([
                'orders' => $orders,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'pages' => ceil($total / $limit)
                ]
            ]);
        }
        break;
        
    case 'POST':
        // Create new order - any authenticated user can create orders
        $user_data = $auth->protectRoute();
        
        $validation_result = $validation->validateOrder($input);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            // Generate order number
            $stmt = $db->prepare("CALL GenerateOrderNumber(?)");
            $order_number = '';
            $stmt->bindParam(1, $order_number, PDO::PARAM_STR, 20);
            $stmt->execute();
            $stmt->closeCursor();
            
            // Calculate total amount
            $total_amount = 0;
            foreach ($input['products'] as $product) {
                $total_amount += $product['price'] * $product['quantity'];
            }
            
            // Create order
            $stmt = $db->prepare("
                INSERT INTO orders (
                    order_number, customer_id, customer_name, customer_email, 
                    customer_phone, customer_address, total_amount, notes
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $order_number,
                $user_data['user_id'] ?? null,
                $validation->sanitize($input['customer_name']),
                $validation->sanitize($input['customer_email']),
                $validation->sanitize($input['customer_phone']),
                $validation->sanitize($input['customer_address'] ?? ''),
                $total_amount,
                $validation->sanitize($input['notes'] ?? '')
            ]);
            
            $order_id = $db->lastInsertId();
            
            // Create order items
            foreach ($input['products'] as $product) {
                $stmt = $db->prepare("
                    INSERT INTO order_items (order_id, product_id, quantity, unit_price, total_price)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $order_id,
                    $product['product_id'],
                    $product['quantity'],
                    $product['price'],
                    $product['price'] * $product['quantity']
                ]);
            }
            
            $response->success(['order_id' => $order_id, 'order_number' => $order_number], 'Order created successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to create order: ' . $e->getMessage());
        }
        break;
        
    case 'PUT':
        // Update order status
        $user_data = $auth->protectRoute('admin', 'orders', 'edit');
        
        if (!$id) {
            $response->error('Order ID is required', 400);
        }
        
        $required_fields = ['status'];
        $validation_result = $validation->validateRequired($input, $required_fields);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            $stmt = $db->prepare("UPDATE orders SET status = ?, notes = ? WHERE id = ?");
            $stmt->execute([
                $input['status'],
                $validation->sanitize($input['notes'] ?? ''),
                $id
            ]);
            
            $response->success(null, 'Order updated successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to update order: ' . $e->getMessage());
        }
        break;
        
    case 'DELETE':
        // Cancel order (soft delete by changing status)
        $user_data = $auth->protectRoute('admin', 'orders', 'delete');
        
        if (!$id) {
            $response->error('Order ID is required', 400);
        }
        
        try {
            $stmt = $db->prepare("UPDATE orders SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$id]);
            
            $response->success(null, 'Order cancelled successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to cancel order: ' . $e->getMessage());
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}