<?php
namespace App\Controllers;

use App\Models\OrderModel;
use App\Models\PaymentModel;
use CodeIgniter\Controller;

class Order extends BaseController
{
    protected $orderModel;
    protected $paymentModel;
    protected $session;

    public function __construct()
    {
        $this->orderModel = new OrderModel();
        $this->paymentModel = new PaymentModel();
        $this->session = session();
        helper(['url', 'form']);

        // Block access if not logged in
        if (!$this->session->get('isLoggedIn')) {
            return redirect()->to(base_url('authController'))->send();
        }
    }

    /** Products page */
    public function index()
    {
        $userId = $this->session->get('user_id');
        $productsByCategory = $this->orderModel->getAllProductsByCategory();

        return view('orders', [
            'categories' => $productsByCategory,
            'cart_count' => $this->orderModel->getCartCount($userId),
            'user_phone' => $this->session->get('phone'),
            'user_name'  => $this->session->get('name'),
            'user_apartName' => $this->session->get('apartName') ?? 'Select Apartment'
        ]);
    }

    /** Add item to cart */
    public function addToCart()
    {
        if (!$this->request->isAJAX()) return $this->response->setStatusCode(400);

        $productId = $this->request->getPost('product_id');
        $variantId = $this->request->getPost('variant_id');
        $quantity  = $this->request->getPost('quantity') ?? 1;
        $userId    = $this->session->get('user_id');

        $this->orderModel->addToCartItem($productId, $variantId, $quantity, $userId);

        return $this->response->setJSON([
            'success' => true,
            'cart_count' => $this->orderModel->getCartCount($userId)
        ]);
    }

    /** Cart page */
    public function cart()
    {
        $userId = $this->session->get('user_id');
        $cartItems = $this->orderModel->getCartItems($userId);

        $total = array_reduce($cartItems, fn($sum, $item) => $sum + ($item['offer_price'] * $item['quantity']), 0);
        $deliveryCharge = 100; 
        $grandTotal = $total + $deliveryCharge;

        return view('cart', [
            'cartItems' => $cartItems,
            'total' => $total,
            'deliveryCharge' => $deliveryCharge,
            'grandTotal' => $grandTotal,
            'user_phone' => $this->session->get('phone'),
            'user_apartName' => $this->session->get('apartName'),
        ]);
    }

    /** Remove item from cart */
    public function removeItem($id)
    {
        if (!$this->request->isAJAX()) return $this->response->setStatusCode(400);

        $userId = $this->session->get('user_id');
        $cartItem = $this->orderModel->where(['id'=>$id, 'user_id'=>$userId])->first();

        if($cartItem){
            $this->orderModel->delete($id);

            $cartItems = $this->orderModel->getCartItems($userId);
            $total = array_reduce($cartItems, fn($sum, $item) => $sum + ($item['offer_price'] * $item['quantity']), 0);
            $deliveryCharge = 100;
            $grandTotal = $total + $deliveryCharge;

            return $this->response->setJSON([
                'success' => true,
                'total' => $total,
                'deliveryCharge' => $deliveryCharge,
                'grandTotal' => $grandTotal,
                'cart_count' => $this->orderModel->getCartCount($userId)
            ]);
        }

        return $this->response->setJSON(['success' => false]);
    }

    /** Checkout page */
    public function checkout()
    {
        $userId = $this->session->get('user_id');
        $cartItems = $this->orderModel->getCartItems($userId);
        if(empty($cartItems)) return redirect()->to(base_url('order/cart'));

        $total = array_reduce($cartItems, fn($sum, $item) => $sum + ($item['offer_price'] * $item['quantity']), 0);
        $deliveryCharge = 100;
        $grandTotal = $total + $deliveryCharge;

        return view('checkout', [
            'cartItems' => $cartItems,
            'total' => $total,
            'deliveryCharge' => $deliveryCharge,
            'grandTotal' => $grandTotal
        ]);
    }

    /** Place order */
public function placeOrder()
{
    try {
        $post = $this->request->getPost();
        $checkout = json_decode($post['checkout'] ?? '{}', true);
        $cartItems = json_decode($post['cartItems'] ?? '[]', true);
        $deliveryCharge = $post['deliveryCharge'] ?? 0;

        if(empty($cartItems)){
            return $this->response->setJSON(['success'=>false,'error'=>'Cart is empty']);
        }

        // Calculate total
        $totalAmount = array_reduce($cartItems, function($sum, $item){
            return $sum + ((float)$item['offer_price'] * (int)$item['quantity']);
        }, 0);
        $totalAmount += (float)$deliveryCharge;

        // Save order
        $orderData = [
            'customer_name' => $checkout['name'] ?? '',
            'email' => $checkout['email'] ?? '',
            'phone' => $checkout['phone'] ?? '',
            'apartment_id' => $checkout['apartment_id'] ?? '',
            'address' => $checkout['address'] ?? '',
            'payment_method' => $checkout['payment'] ?? 'COD',
            'delivery_charge' => $deliveryCharge,
            'total_amount' => $totalAmount,
            'status' => 'Pending'
        ];

        $order_id = $this->orderModel->insertOrder($orderData, $cartItems);

        return $this->response->setJSON([
            'success' => true,
            'order_id' => $order_id,
            'totalAmount' => $totalAmount
        ]);

    } catch (\Exception $e) {
        return $this->response->setJSON([
            'success' => false,
            'error' => 'Internal Server Error: '.$e->getMessage()
        ]);
    }
}


    /** Get all apartments */
    public function getApartments() 
    {
        $db = \Config\Database::connect();
        $apartments = $db->table('apartmentdetails')
                         ->select('id, apartName')
                         ->get()
                         ->getResultArray();
        return $this->response->setJSON($apartments);
    }

    /** Get apartment address */
    public function getApartmentAddress($id = null) 
    {
        if(!$id) return $this->response->setJSON(['apartAddress' => '']);

        $db = \Config\Database::connect();
        $address = $db->table('apartmentdetails')
                      ->select('apartAddress')
                      ->where('id', $id)
                      ->get()
                      ->getRowArray();

        return $this->response->setJSON($address);
    }
}
