<?php
require_once __DIR__ . '/../models/order.php';
require_once __DIR__ . '/../models/cart.php';

class OrderController {
    private $db;
    private $order;
    private $cart;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
        $this->order = new Order($this->db);
        $this->cart = new Cart($this->db);
    }

    public function createOrder() {
        $headers = getallheaders();
        if(!isset($headers['Authorization'])) {
            http_response_code(401);
            echo json_encode(array("message" => "Access denied."));
            return;
        }

        $token = str_replace('Bearer ', '', $headers['Authorization']);
        $user_data = json_decode(base64_decode($token), true);
        $user_id = $user_data['user_id'];

        $data = json_decode(file_get_contents("php://input"));

        if(empty($data->shipping_address)) {
            http_response_code(400);
            echo json_encode(array("message" => "Shipping address is required."));
            return;
        }

        // Get cart items
        $stmt = $this->cart->getCart($user_id);
        $cart_items = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $cart_items[] = array(
                'product_id' => $row['product_id'],
                'quantity' => $row['quantity'],
                'price' => $row['price']
            );
        }

        if(empty($cart_items)) {
            http_response_code(400);
            echo json_encode(array("message" => "Cart is empty."));
            return;
        }

        $this->order->user_id = $user_id;
        $this->order->status = 'pending';
        $this->order->shipping_address = $data->shipping_address;

        $order_id = $this->order->create($cart_items);

        if($order_id) {
            http_response_code(201);
            echo json_encode(array(
                "message" => "Order created successfully.",
                "order_id" => $order_id
            ));
        } else {
            http_response_code(503);
            echo json_encode(array("message" => "Unable to create order."));
        }
    }
}
?>