<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Products extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('products_m');
        $this->load->model('categories_m');
    }

    /**
     * Product listing page
     */
    public function index() {
        $category = $this->input->get('category');
        $search = $this->input->get('name');
        $sort = $this->input->get('sort');
        
        // Determine sorting
        $order_by = 'productDate';
        $order = 'DESC';
        
        switch ($sort) {
            case 'latest':
                $order_by = 'productDate';
                $order = 'DESC';
                break;
            case 'price_low':
                $order_by = 'amount';
                $order = 'ASC';
                break;
            case 'price_high':
                $order_by = 'amount';
                $order = 'DESC';
                break;
            case 'name_asc':
                $order_by = 'name';
                $order = 'ASC';
                break;
            case 'name_desc':
                $order_by = 'name';
                $order = 'DESC';
                break;
        }
        
        if ($search) {
            $this->data['products'] = $this->products_m->searchProducts($search);
            $this->data['page_title'] = 'Search Results: ' . htmlspecialchars($search);
        } elseif ($category) {
            $this->data['products'] = $this->products_m->getByCategory($category);
            $cat = $this->categories_m->getOne(['categoryUnique' => $category]);
            $this->data['page_title'] = $cat ? $cat->category_name : 'Shop';
        } else {
            $this->data['products'] = $this->products_m->getActiveProducts(null, $order_by, $order);
            $this->data['page_title'] = 'Shop';
        }
        
        // Apply sorting to results if needed (for search/category results)
        if ($sort && ($search || $category)) {
            $products = $this->data['products'];
            usort($products, function($a, $b) use ($order_by, $order) {
                if ($order == 'ASC') {
                    return $a->$order_by <=> $b->$order_by;
                } else {
                    return $b->$order_by <=> $a->$order_by;
                }
            });
            $this->data['products'] = $products;
        }
        
        $this->data['categories'] = $this->categories_m->getAll();
        $this->data['content'] = 'products/index';
        $this->load->view('_layout', $this->data);
    }

    /**
     * Single product view page
     */
    public function view($slug = null, $productUnique = null) {
        if (!$slug || !$productUnique) {
            redirect('products');
        }

        // Get product details
        $product = $this->products_m->getBySlug($slug, $productUnique);
        
        if (!$product) {
            redirect('products');
        }

        // Get product gallery photos
        $photos = $this->products_m->getProductPhotos($productUnique);
        
        // Get product sizes and colors
        $sizes = [];
        $colors = [];
        
        if ($product->sizes) {
            $sizeUniques = explode(',', $product->sizes);
            foreach ($sizeUniques as $sizeUnique) {
                $size = $this->db->where('sizeUnique', trim($sizeUnique))->get('sizes')->row();
                if ($size) {
                    $sizes[] = $size;
                }
            }
        }
        
        if ($product->colors) {
            $colorUniques = explode(',', $product->colors);
            foreach ($colorUniques as $colorUnique) {
                $color = $this->db->where('colorUnique', trim($colorUnique))->get('colors')->row();
                if ($color) {
                    $colors[] = $color;
                }
            }
        }

        // Get product reviews
        $reviews = $this->products_m->getProductReviews($productUnique);
        $rating_data = $this->products_m->getAverageRating($productUnique);

        // Get related products (same category)
        $related_products = $this->products_m->getByCategory($product->categoryUnique, 4);
        // Remove current product from related
        $related_products = array_filter($related_products, function($p) use ($productUnique) {
            return $p->productUnique !== $productUnique;
        });

        // Pass data to view
        $this->data['product'] = $product;
        $this->data['photos'] = $photos;
        $this->data['sizes'] = $sizes;
        $this->data['colors'] = $colors;
        $this->data['reviews'] = $reviews;
        $this->data['average_rating'] = $rating_data->average_rating ?? 0;
        $this->data['total_reviews'] = $rating_data->total_reviews ?? 0;
        $this->data['related_products'] = array_slice(array_values($related_products), 0, 4);
        
        $this->data['content'] = 'products/view';
        $this->load->view('_layout', $this->data);
    }

    /**
     * Add to cart via AJAX
     */
    public function add_to_cart() {
        $productUnique = $this->input->post('productUnique');
        $quantity = $this->input->post('quantity') ?: 1;
        $size = $this->input->post('size');
        $color = $this->input->post('color');

        if (!$productUnique) {
            echo json_encode(['status' => 'error', 'message' => 'Product not found']);
            return;
        }

        $product = $this->products_m->getByUnique($productUnique);
        if (!$product) {
            echo json_encode(['status' => 'error', 'message' => 'Product not found']);
            return;
        }

        $userUnique = getUserUnique();
        
        // Check if product already in cart
        $existingCart = $this->cart_m->getOne([
            'productUnique' => $productUnique,
            'userUnique' => $userUnique,
            'size' => $size,
            'color' => $color,
            'status' => 0
        ]);

        if ($existingCart) {
            // Update quantity
            $newQty = $existingCart->quantity + $quantity;
            $this->cart_m->update($existingCart->cartId, ['quantity' => $newQty]);
        } else {
            // Get current exchange rate
            $rate = 1; // Default rate
            
            // Add new cart item
            $cartData = [
                'cartUnique' => Unique::generate(),
                'productUnique' => $productUnique,
                'userUnique' => $userUnique,
                'quantity' => $quantity,
                'price' => $product->amount,
                'size' => $size ? $size : '',
                'color' => $color ? $color : '',
                'cart_rate' => $rate,
                'cart_currency' => 'USD',
                'transactionUnique' => '',
                'status' => 0
            ];
            $this->cart_m->insert($cartData);
        }

        // Get updated cart items and count
        $carts = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        $cartCount = count($carts);
        
        // Generate updated cart sidebar HTML
        $cartHtml = $this->load->view('layout/_cart_sidebar', ['carts' => $carts], true);

        echo json_encode([
            'status' => 'success',
            'message' => 'Product added to cart!',
            'cart_count' => $cartCount,
            'cart_html' => $cartHtml
        ]);
    }

    /**
     * Update cart quantity via AJAX
     */
    public function update_to_cart() {
        $cartId = $this->input->post('cartId');
        $quantity = $this->input->post('quantity');

        if (!$cartId || !$quantity) {
            echo json_encode(['status' => 0, 'message' => 'Invalid request']);
            return;
        }

        $this->cart_m->update($cartId, ['quantity' => $quantity]);
        
        // Get updated cart HTML
        $userUnique = getUserUnique();
        $carts = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        
        $html = $this->load->view('layout/_cart_sidebar', ['carts' => $carts], true);

        echo json_encode([
            'status' => 1, 
            'message' => 'Pre-order updated',
            'html' => $html
        ]);
    }

    /**
     * Remove from cart via AJAX
     */
    public function remove_from_cart() {
        $cartId = $this->input->post('cartId');

        if (!$cartId) {
            echo json_encode(['status' => 0, 'message' => 'Invalid request']);
            return;
        }

        $this->cart_m->delete($cartId);
        
        // Get updated cart count and HTML
        $userUnique = getUserUnique();
        $carts = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        $count = count($carts);
        
        // Generate updated cart HTML
        $html = $this->load->view('layout/_cart_sidebar', ['carts' => $carts], true);

        echo json_encode([
            'status' => 1, 
            'message' => 'Item removed from pre-order',
            'count' => $count,
            'html' => $html
        ]);
    }

    /**
     * Cart page
     */
    public function cart() {
        $userUnique = getUserUnique();
        $this->data['cart_items'] = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        $this->data['content'] = 'products/cart';
        $this->load->view('_layout', $this->data);
    }

    /**
     * Clear all cart items via AJAX
     */
    public function clear_cart() {
        $userUnique = getUserUnique();
        
        if (!$userUnique) {
            echo json_encode(['status' => 'error', 'message' => 'User not found']);
            return;
        }

        // Delete all cart items for this user
        $this->db->where('userUnique', $userUnique);
        $this->db->where('status', 0);
        $this->db->delete('cart');

        echo json_encode(['status' => 'success', 'message' => 'Cart cleared']);
    }

    /**
     * Apply coupon code via AJAX
     */
    public function apply_coupon() {
        $coupon_code = $this->input->post('coupon_code');
        
        if (!$coupon_code) {
            echo json_encode(['status' => 'error', 'message' => 'Please enter a coupon code']);
            return;
        }

        // Check if coupon exists and is valid
        $coupon = $this->db->where('coupon_code', $coupon_code)
                           ->where('coupon_status', 1)
                           ->get('coupons')
                           ->row();

        if (!$coupon) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid or expired coupon code']);
            return;
        }

        // Check if coupon has uses remaining
        if ($coupon->coupon_uses_max > 0 && $coupon->coupon_uses >= $coupon->coupon_uses_max) {
            echo json_encode(['status' => 'error', 'message' => 'This coupon has reached its usage limit']);
            return;
        }

        // Check expiry date if set
        if ($coupon->coupon_expiry && strtotime($coupon->coupon_expiry) < time()) {
            echo json_encode(['status' => 'error', 'message' => 'This coupon has expired']);
            return;
        }

        // Store coupon in session for checkout
        $_SESSION['applied_coupon'] = [
            'code' => $coupon->coupon_code,
            'discount' => $coupon->coupon_discount,
            'type' => $coupon->coupon_type // 'percentage' or 'fixed'
        ];

        // Calculate discount
        $userUnique = getUserUnique();
        $cart_items = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        
        $subtotal = 0;
        foreach ($cart_items as $item) {
            $item_price = $item->amount;
            if ($item->discount_percentage) {
                $item_price = $item->amount - ($item->amount * ($item->discount_percentage / 100));
            }
            $subtotal += $item_price * $item->quantity;
        }

        $discount_amount = 0;
        if ($coupon->coupon_type == 'percentage') {
            $discount_amount = $subtotal * ($coupon->coupon_discount / 100);
        } else {
            $discount_amount = $coupon->coupon_discount;
        }

        $new_total = max(0, $subtotal - $discount_amount);

        echo json_encode([
            'status' => 'success',
            'message' => 'Coupon applied successfully!',
            'discount' => number_format($discount_amount, 2),
            'new_total' => number_format($new_total, 2)
        ]);
    }

    /**
     * Process cart / Checkout page
     */
    public function process() {
        $userUnique = getUserUnique();
        
        if (!$userUnique) {
            redirect('products/cart');
        }

        $cart_items = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        
        if (!$cart_items || count($cart_items) == 0) {
            redirect('products/cart');
        }

        $this->data['cart_items'] = $cart_items;
        $this->data['content'] = 'products/checkout';
        $this->load->view('_layout', $this->data);
    }

    /**
     * Place order - process the checkout form
     */
    public function place_order() {
        $userUnique = getUserUnique();
        
        if (!$userUnique) {
            $this->session->set_flashdata('error', 'Session expired. Please try again.');
            redirect('products/cart');
        }

        // Get cart items
        $cart_items = $this->cart_m->getCartItems(['cart.userUnique' => $userUnique, 'cart.status' => 0]);
        
        if (!$cart_items || count($cart_items) == 0) {
            $this->session->set_flashdata('error', 'Your cart is empty.');
            redirect('products/cart');
        }

        // Validate required fields
        $first_name = $this->input->post('first_name');
        $last_name = $this->input->post('last_name');
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $street_address = $this->input->post('street_address');
        $apt_suite = $this->input->post('apt_suite');
        $city = $this->input->post('city');
        $state = $this->input->post('state');
        $zip = $this->input->post('zip');
        $country = $this->input->post('country');
        $order_notes = $this->input->post('order_notes');
        $payment_method = $this->input->post('payment_method');

        if (!$first_name || !$last_name || !$email || !$phone || !$street_address || !$city || !$state || !$zip || !$country) {
            $this->session->set_flashdata('error', 'Please fill in all required fields.');
            redirect('products/process');
        }

        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->session->set_flashdata('error', 'Please enter a valid email address.');
            redirect('products/process');
        }

        // Calculate totals
        $subtotal = 0;
        foreach ($cart_items as $item) {
            $item_price = $item->amount;
            if ($item->discount_percentage) {
                $item_price = $item->amount - ($item->amount * ($item->discount_percentage / 100));
            }
            $subtotal += $item_price * $item->quantity;
        }

        // Apply coupon if any
        $coupon_discount = 0;
        $coupon_percentage = 0;
        $couponUnique = '';
        
        if (isset($_SESSION['applied_coupon']) && $_SESSION['applied_coupon']) {
            $coupon = $_SESSION['applied_coupon'];
            if ($coupon['type'] == 'percentage') {
                $coupon_discount = $subtotal * ($coupon['discount'] / 100);
                $coupon_percentage = $coupon['discount'];
            } else {
                $coupon_discount = $coupon['discount'];
            }
            $couponUnique = $coupon['code'];
        }

        $final_amount = max(0, $subtotal - $coupon_discount);

        // Generate order ID
        $orderId = 'ORD-' . strtoupper(Unique::ref()) . '-' . date('Ymd');
        $checkUnique = Unique::generate();
        $transactionUnique = Unique::generate();

        // Create transaction record
        $transactionData = [
            'orderId' => $orderId,
            'userUnique' => $userUnique,
            'firstname' => $first_name,
            'lastname' => $last_name,
            'email' => $email,
            'phone' => $phone,
            'zipCode' => $zip,
            'city' => $city,
            'country' => $country,
            'address' => $street_address . ($apt_suite ? ', ' . $apt_suite : '') . ', ' . $city . ', ' . $state . ' ' . $zip,
            'amount' => $subtotal,
            'finalAmount' => $final_amount,
            'checkUnique' => $checkUnique,
            'status' => 'pending',
            'transactionUnique' => $transactionUnique,
            'couponUnique' => $couponUnique,
            'coupon_percentage' => $coupon_percentage,
            'vat' => 0,
            'delivery_fee' => 0,
            'delivery_type' => 'standard',
            'order_currency' => 'USD',
            'payment_method' => $payment_method ?: 'card',
            'transaction_status' => 'pending',
            'company' => '',
            'apartment' => $apt_suite,
            'order_status' => 'pending',
            'deleted' => 0
        ];

        $this->transactions_m->insert($transactionData);

        // Update cart items with transaction reference
        foreach ($cart_items as $item) {
            $this->cart_m->update($item->cartId, [
                'transactionUnique' => $transactionUnique,
                'status' => 1 // Mark as processed
            ]);
        }

        // Clear applied coupon
        unset($_SESSION['applied_coupon']);

        // Store order info in session for confirmation page
        $_SESSION['last_order'] = [
            'orderId' => $orderId,
            'transactionUnique' => $transactionUnique,
            'email' => $email,
            'total' => $final_amount
        ];

        // For now, we'll simulate a successful payment
        // In production, you would integrate with a payment gateway here
        
        // Redirect to confirmation page
        $this->session->set_flashdata('success', 'Your pre-order has been placed successfully!');
        redirect('products/order_confirmation/' . $transactionUnique);
    }

    /**
     * Order confirmation page
     */
    public function order_confirmation($transactionUnique = null) {
        if (!$transactionUnique) {
            redirect('products');
        }

        // Get order details
        $order = $this->transactions_m->getOne(['transactionUnique' => $transactionUnique]);
        
        if (!$order) {
            $this->session->set_flashdata('error', 'Order not found.');
            redirect('products');
        }

        // Get order items
        $order_items = $this->cart_m->getCartItems([
            'cart.transactionUnique' => $transactionUnique,
            'cart.status' => 1
        ]);

        $this->data['order'] = $order;
        $this->data['order_items'] = $order_items;
        $this->data['content'] = 'products/order_confirmation';
        $this->load->view('_layout', $this->data);
    }

    /**
     * My orders page
     */
    public function my_orders() {
        $userUnique = getUserUnique();
        
        if (!$userUnique) {
            redirect('auth/login');
        }

        $orders = $this->transactions_m->getFilter(
            ['userUnique' => $userUnique, 'deleted' => 0],
            'checkDate',
            'DESC'
        );

        $this->data['orders'] = $orders;
        $this->data['content'] = 'products/my_orders';
        $this->load->view('_layout', $this->data);
    }

    /**
     * View single order
     */
    public function order_details($transactionUnique = null) {
        $userUnique = getUserUnique();
        
        if (!$userUnique || !$transactionUnique) {
            redirect('products/my_orders');
        }

        $order = $this->transactions_m->getOne([
            'transactionUnique' => $transactionUnique,
            'userUnique' => $userUnique
        ]);
        
        if (!$order) {
            $this->session->set_flashdata('error', 'Order not found.');
            redirect('products/my_orders');
        }

        $order_items = $this->cart_m->getCartItems([
            'cart.transactionUnique' => $transactionUnique,
            'cart.status' => 1
        ]);

        $this->data['order'] = $order;
        $this->data['order_items'] = $order_items;
        $this->data['content'] = 'products/order_details';
        $this->load->view('_layout', $this->data);
    }
}

