<?php
/**
 * Tom's Java Jive - Orders API
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

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

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_POST['action'] ?? '';

switch ($method) {
    case 'GET':
        // Get order(s)
        $orderId = $_GET['id'] ?? '';
        $orderNumber = $_GET['number'] ?? '';
        
        if ($orderId) {
            $order = db()->fetch(
                "SELECT * FROM orders WHERE order_id = :id",
                ['id' => $orderId]
            );
            
            if (!$order) {
                jsonResponse(['error' => 'Order not found'], 404);
            }
            
            $order['items'] = json_decode($order['items'], true);
            $order['shipping_address'] = json_decode($order['shipping_address'], true);
            unset($order['id']);
            
            jsonResponse($order);
        } elseif ($orderNumber) {
            $email = $_GET['email'] ?? '';
            
            $order = db()->fetch(
                "SELECT * FROM orders WHERE order_number = :num AND customer_email = :email",
                ['num' => $orderNumber, 'email' => strtolower($email)]
            );
            
            if (!$order) {
                jsonResponse(['error' => 'Order not found'], 404);
            }
            
            $order['items'] = json_decode($order['items'], true);
            $order['shipping_address'] = json_decode($order['shipping_address'], true);
            unset($order['id']);
            
            jsonResponse($order);
        } else {
            // List orders (admin only or customer's own)
            $customer = CustomerAuth::getUser();
            
            if ($customer) {
                $orders = db()->fetchAll(
                    "SELECT order_id, order_number, total, payment_status, order_status, created_at 
                     FROM orders WHERE customer_id = :cid ORDER BY created_at DESC LIMIT 50",
                    ['cid' => $customer['customer_id']]
                );
            } else {
                jsonResponse(['error' => 'Authentication required'], 401);
            }
            
            jsonResponse(['orders' => $orders]);
        }
        break;
        
    case 'POST':
        // Update order status (admin)
        if ($action === 'update_status') {
            // Admin check would go here
            $orderId = $input['order_id'] ?? '';
            $status = $input['status'] ?? '';
            $trackingNumber = $input['tracking_number'] ?? null;
            
            if (empty($orderId) || empty($status)) {
                jsonResponse(['error' => 'Order ID and status required'], 400);
            }
            
            $validStatuses = ['pending', 'confirmed', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'];
            if (!in_array($status, $validStatuses)) {
                jsonResponse(['error' => 'Invalid status'], 400);
            }
            
            $updateData = ['order_status' => $status];
            if ($trackingNumber) {
                $updateData['tracking_number'] = $trackingNumber;
            }
            
            db()->update('orders', $updateData, 'order_id = :id', ['id' => $orderId]);
            
            // If status is shipped or delivered, send email
            $order = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $orderId]);
            if ($order && in_array($status, ['shipped', 'delivered'])) {
                sendStatusUpdateEmail($order, $status, $trackingNumber);
            }
            
            jsonResponse(['success' => true, 'status' => $status]);
        }
        
        // Cancel order
        if ($action === 'cancel') {
            $orderId = $input['order_id'] ?? '';
            $customer = CustomerAuth::getUser();
            
            if (!$customer) {
                jsonResponse(['error' => 'Authentication required'], 401);
            }
            
            $order = db()->fetch(
                "SELECT * FROM orders WHERE order_id = :id AND customer_id = :cid",
                ['id' => $orderId, 'cid' => $customer['customer_id']]
            );
            
            if (!$order) {
                jsonResponse(['error' => 'Order not found'], 404);
            }
            
            if (!in_array($order['order_status'], ['pending', 'confirmed'])) {
                jsonResponse(['error' => 'This order cannot be cancelled'], 400);
            }
            
            db()->update('orders',
                ['order_status' => 'cancelled'],
                'order_id = :id',
                ['id' => $orderId]
            );
            
            // Restore stock
            $items = json_decode($order['items'], true) ?? [];
            foreach ($items as $item) {
                db()->query(
                    "UPDATE products SET stock = stock + :qty WHERE product_id = :id",
                    ['qty' => $item['quantity'], 'id' => $item['product_id']]
                );
            }
            
            jsonResponse(['success' => true]);
        }
        
        jsonResponse(['error' => 'Invalid action'], 400);
        break;
        
    default:
        jsonResponse(['error' => 'Method not allowed'], 405);
}

function sendStatusUpdateEmail($order, $status, $trackingNumber = null) {
    $statusMessages = [
        'shipped' => 'Your order has been shipped!',
        'delivered' => 'Your order has been delivered!'
    ];
    
    $tracking = $trackingNumber ? "<p><strong>Tracking #:</strong> {$trackingNumber}</p>" : '';
    
    $html = <<<HTML
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <div style="background: #8B4513; color: white; padding: 20px; text-align: center;">
            <h1 style="margin: 0;">Tom's Java Jive</h1>
        </div>
        <div style="padding: 30px; background: #FDFBF7;">
            <h2>{$statusMessages[$status]}</h2>
            <p>Hi {$order['customer_name']},</p>
            <p>Order <strong>#{$order['order_number']}</strong> has been updated to: <strong>{$status}</strong></p>
            {$tracking}
        </div>
    </div>
    HTML;
    
    sendEmail($order['customer_email'], "Order Update - #{$order['order_number']}", $html);
}
