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

class CartController {
    private $db;
    private $cart;

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

    public function getCart() {
        // Get user ID from token (simplified auth check)
        $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'];

        $stmt = $this->cart->getCart($user_id);
        $num = $stmt->rowCount();

        if($num > 0) {
            $cart_arr = array();
            $cart_arr["items"] = array();
            $total = 0;

            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                extract($row);

                $item = array(
                    "id" => $id,
                    "product_id" => $product_id,
                    "name" => $name,
                    "price" => $price,
                    "image" => $image,
                    "quantity" => $quantity,
                    "subtotal" => $price * $quantity
                );

                $total += $price * $quantity;
                array_push($cart_arr["items"], $item);
            }

            $cart_arr["total"] = $total;

            http_response_code(200);
            echo json_encode($cart_arr);
        } else {
            http_response_code(200);
            echo json_encode(array("items" => array(), "total" => 0));
        }
    }

    public function addToCart() {
        $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);
        $this->cart->user_id = $user_data['user_id'];

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

        if(!empty($data->product_id) && !empty($data->quantity)) {
            $this->cart->product_id = $data->product_id;
            $this->cart->quantity = $data->quantity;

            if($this->cart->addToCart()) {
                http_response_code(201);
                echo json_encode(array("message" => "Item added to cart."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to add item to cart."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Data incomplete."));
        }
    }

    public function updateCartItem($params) {
        $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);
        $this->cart->user_id = $user_data['user_id'];
        $this->cart->id = $params['id'];

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

        if(!empty($data->quantity)) {
            $this->cart->quantity = $data->quantity;

            if($this->cart->updateQuantity()) {
                http_response_code(200);
                echo json_encode(array("message" => "Cart item updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update cart item."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Data incomplete."));
        }
    }

    public function removeFromCart($params) {
        $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);
        $this->cart->user_id = $user_data['user_id'];
        $this->cart->id = $params['id'];

        if($this->cart->removeFromCart()) {
            http_response_code(200);
            echo json_encode(array("message" => "Item removed from cart."));
        } else {
            http_response_code(503);
            echo json_encode(array("message" => "Unable to remove item from cart."));
        }
    }
}
?>