<?php
namespace App\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\Settings;
use App\Models\Order;

class CartController extends Controller {

    public function view() {
        $categories = Category::all(['parent_slug' => null]);
        $cartItems = $this->getCartItems();

        $customer = $this->session->get('customer_user');
        $user = null;
        if ($customer) {
            $user = \App\Models\User::find($customer['id']);
        }

        $this->response->render('client/cart', [
            'categories' => $categories,
            'cartItems' => $cartItems,
            'user' => $user,
            'title' => 'Sepetim - ' . Settings::get('store_name')
        ]);
    }

    public function checkout() {
        $categories = Category::all(['parent_slug' => null]);
        $cartItems = $this->getCartItems();
        
        if (empty($cartItems)) {
            $this->response->redirect('cart');
        }

        $customer = $this->session->get('customer_user');
        $user = null;
        if ($customer) {
            $user = \App\Models\User::find($customer['id']);
        }

        $shippingMethods = \App\Models\Settings::get('shipping_methods', [['name' => 'Standart Kargo', 'cost' => '50.00']]);
        $paymentMethods = \App\Models\Settings::get('payment_methods', [
            'credit_card' => ['enabled' => '1'],
            'bank_transfer' => ['enabled' => '1', 'description' => ''],
            'cash_on_delivery' => ['enabled' => '0', 'extra_fee' => '20.00']
        ]);

        $this->response->render('client/checkout', [
            'categories' => $categories,
            'cartItems' => $cartItems,
            'user' => $user,
            'shippingMethods' => $shippingMethods,
            'paymentMethods' => $paymentMethods,
            'title' => 'Ödeme Yap - ' . \App\Models\Settings::get('store_name')
        ]);
    }

    public function add() {
        $data = $this->request->getJsonBody();
        $productId = isset($data['product_id']) ? $data['product_id'] : '';
        $qty = (int)(isset($data['quantity']) ? $data['quantity'] : 1);

        if (!$productId) {
            return $this->response->json(['success' => false, 'message' => 'Geçersiz Ürün']);
        }

        $product = Product::find($productId);
        if (!$product) {
            return $this->response->json(['success' => false, 'message' => 'Ürün bulunamadı']);
        }

        $this->session->addToCart($productId, $qty);
        
        $cart = $this->session->getCart();
        $totalItems = array_sum($cart);
        
        return $this->response->json([
            'success' => true, 
            'message' => 'Ürün sepete eklendi',
            'total_items' => $totalItems
        ]);
    }

    public function update() {
        $data = $this->request->getJsonBody();
        $productId = isset($data['product_id']) ? $data['product_id'] : '';
        $qty = (int)(isset($data['quantity']) ? $data['quantity'] : 0);

        if (!$productId) {
            return $this->response->json(['success' => false, 'message' => 'Geçersiz veri']);
        }

        $this->session->updateCart($productId, $qty);
        
        $cart = $this->session->getCart();
        $totalItems = array_sum($cart);

        return $this->response->json([
            'success' => true,
            'message' => 'Sepet güncellendi',
            'total_items' => $totalItems
        ]);
    }

    public function submitOrder() {
        $body = $this->request->getBody();
        $name    = isset($body['customer_name'])    ? trim($body['customer_name'])    : '';
        $email   = isset($body['customer_email'])   ? trim($body['customer_email'])   : '';
        $phone   = isset($body['customer_phone'])   ? trim($body['customer_phone'])   : '';
        $address = isset($body['customer_address']) ? trim($body['customer_address']) : '';
        $shippingMethodName = isset($body['shipping_method']) ? $body['shipping_method'] : '';
        $paymentMethod = isset($body['payment_method']) ? $body['payment_method'] : 'credit_card';

        // Get shipping cost by matching name
        $shippingMethods = \App\Models\Settings::get('shipping_methods', [['name' => 'Standart Kargo', 'cost' => '50.00']]);
        $selectedShipping = $shippingMethods[0] ?? ['name' => 'Standart Kargo', 'cost' => '50.00'];
        foreach ($shippingMethods as $sm) {
            if (($sm['name'] ?? '') === $shippingMethodName) {
                $selectedShipping = $sm;
                break;
            }
        }
        $shippingCost = (float)($selectedShipping['cost'] ?? 0);
        $shippingName = $selectedShipping['name'] ?? 'Bilinmiyor';

        $paymentMethodsSettings = \App\Models\Settings::get('payment_methods', [
            'credit_card' => ['enabled' => '1'],
            'bank_transfer' => ['enabled' => '1', 'description' => ''],
            'cash_on_delivery' => ['enabled' => '0', 'extra_fee' => '20.00']
        ]);

        // Load user for logged-in customers
        $customer = $this->session->get('customer_user');
        $user = null;
        if ($customer) {
            $user = \App\Models\User::find($customer['id']);
        }

        if (empty($name) || empty($phone) || empty($address)) {
            $categories = \App\Models\Category::all(['parent_slug' => null]);
            $cartItems = $this->getCartItems();
            return $this->response->render('client/checkout', [
                'categories' => $categories,
                'cartItems' => $cartItems,
                'user' => $user,
                'shippingMethods' => $shippingMethods,
                'paymentMethods' => $paymentMethodsSettings,
                'error' => 'Lütfen gerekli tüm alanları doldurun.',
                'title' => 'Ödeme Yap - ' . \App\Models\Settings::get('store_name')
            ]);
        }

        $cartItems = $this->getCartItems();
        if (empty($cartItems)) {
            $this->response->redirect('cart');
        }

        // Calculate total
        $subtotalAmount = 0;
        $items = [];
        foreach ($cartItems as $item) {
            $itemSub = $item['product']->getConvertedPrice() * $item['quantity'];
            $subtotalAmount += $itemSub;
            $items[] = [
                'product_id' => $item['product']->id,
                'name' => $item['product']->name,
                'price' => $item['product']->price,
                'currency' => $item['product']->currency,
                'quantity' => $item['quantity'],
                'subtotal' => $itemSub
            ];
        }

        // $paymentMethodsSettings already loaded above

        $paymentFee = 0;
        $orderStatus = 'pending';

        if ($paymentMethod === 'cash_on_delivery') {
            $paymentFee = (float)($paymentMethodsSettings['cash_on_delivery']['extra_fee'] ?? 0);
            $orderStatus = 'processing';
        } elseif ($paymentMethod === 'bank_transfer') {
            $orderStatus = 'pending_payment';
        } elseif ($paymentMethod === 'credit_card') {
            $ccNumber = isset($body['cc_number']) ? preg_replace('/\D/', '', $body['cc_number']) : '';
            $ccName   = isset($body['cc_name'])   ? trim($body['cc_name']) : '';
            $ccExpiry = isset($body['cc_expiry'])  ? trim($body['cc_expiry']) : '';
            $ccCvv    = isset($body['cc_cvv'])     ? trim($body['cc_cvv']) : '';

            if (empty($ccNumber) || empty($ccName) || empty($ccExpiry) || empty($ccCvv)) {
                $categories = \App\Models\Category::all(['parent_slug' => null]);
                return $this->response->render('client/checkout', [
                    'categories' => $categories,
                    'cartItems' => $cartItems,
                    'user' => $user,
                    'shippingMethods' => $shippingMethods,
                    'paymentMethods' => $paymentMethodsSettings,
                    'error' => 'Lütfen kredi kartı bilgilerini eksiksiz girin.',
                    'title' => 'Ödeme Yap - ' . \App\Models\Settings::get('store_name')
                ]);
            }

            // Parse expiry AA/YY
            $expiryParts = explode('/', $ccExpiry);
            $expMonth = $expiryParts[0] ?? '01';
            $expYear  = isset($expiryParts[1]) ? '20' . $expiryParts[1] : '2030';

            // Process payment via iyzico
            $paymentService = new \App\Services\PaymentService();
            
            $totalAmount = $subtotalAmount + $shippingCost + $paymentFee;

            $paymentResult = $paymentService->pay(
                [
                    'holder_name'  => $ccName,
                    'card_number'  => $ccNumber,
                    'expire_month' => $expMonth,
                    'expire_year'  => $expYear,
                    'cvc'          => $ccCvv,
                ],
                [
                    'order_id'         => 'EVR' . time(),
                    'total'            => $totalAmount,
                    'shipping_cost'    => $shippingCost,
                    'payment_fee'      => $paymentFee,
                    'items'            => $items,
                    'customer_name'    => $name,
                    'customer_email'   => $email,
                    'customer_phone'   => $phone,
                    'customer_address' => $address,
                    'customer_ip'      => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
                ]
            );

            if (!$paymentResult['success']) {
                $categories = \App\Models\Category::all(['parent_slug' => null]);
                return $this->response->render('client/checkout', [
                    'categories' => $categories,
                    'cartItems' => $cartItems,
                    'user' => $user,
                    'shippingMethods' => $shippingMethods,
                    'paymentMethods' => $paymentMethodsSettings,
                    'error' => $paymentResult['message'],
                    'title' => 'Ödeme Yap - ' . \App\Models\Settings::get('store_name')
                ]);
            }

            $orderStatus = 'processing';
            $iyzicoPaymentId = $paymentResult['payment_id'];
        }

        $totalAmount = $subtotalAmount + $shippingCost + $paymentFee;

        // Save order
        $order = new \App\Models\Order([
            'user_id' => $user ? $user->id : null,
            'customer_name' => $name,
            'customer_email' => $email,
            'customer_phone' => $phone,
            'customer_address' => $address,
            'items' => $items,
            'subtotal' => $subtotalAmount,
            'shipping_cost' => $shippingCost,
            'payment_fee' => $paymentFee,
            'shipping_method' => $shippingName,
            'payment_method' => $paymentMethod,
            'payment_id' => $iyzicoPaymentId ?? null,
            'total' => $totalAmount,
            'currency' => \App\Services\CurrencyService::getCurrentCurrency(),
            'status' => $orderStatus,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        $order->save();
        $this->session->clearCart();

        $customer = $this->session->get('customer_user');
        $user = null;
        if ($customer) {
            $user = \App\Models\User::find($customer['id']);
        }

        $categories = Category::all(['parent_slug' => null]);
        $this->response->render('client/success', [
            'categories' => $categories,
            'orderId' => $order->id,
            'order' => $order,
            'user' => $user,
            'title' => 'Sipariş Alındı - ' . Settings::get('store_name')
        ]);
    }

    protected function getCartItems() {
        $cart = $this->session->getCart();
        $items = [];
        foreach ($cart as $productId => $qty) {
            $product = Product::find($productId);
            if ($product) {
                $items[] = [
                    'product' => $product,
                    'quantity' => $qty
                ];
            }
        }
        return $items;
    }
}
