<?php

namespace App\Controllers;

use App\Models\OrderModel;
use App\Models\OrderItemModel;
use App\Models\ProductModel;
use App\Models\UserModel;

class OrderController extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $userId = $this->request->getVar('user_id');
        $koperasiId = $this->request->getVar('koperasi_id');

        if ($userId) {
            // Customer's orders
            $builder = $db->table('orders o');
            $builder->select('o.*, k.nama_koperasi, k.logo as koperasi_logo, COUNT(oi.id) as total_items');
            $builder->join('koperasi k', 'k.id = o.koperasi_id');
            $builder->join('order_items oi', 'oi.order_id = o.id', 'left');
            $builder->where('o.customer_id', $userId);
            $builder->groupBy('o.id');
            $builder->orderBy('o.id', 'DESC');
            $orders = $builder->get()->getResultArray();
        } else if ($koperasiId) {
            // Cooperative's orders
            $builder = $db->table('orders o');
            $builder->select('o.*, u.nama as customer_name, COUNT(oi.id) as total_items');
            $builder->join('order_items oi', 'oi.order_id = o.id');
            $builder->join('users u', 'u.id = o.customer_id');
            $builder->where('o.koperasi_id', $koperasiId);
            $builder->groupBy('o.id');
            $builder->orderBy('o.id', 'DESC');
            $orders = $builder->get()->getResultArray();
        } else {
            // Super Admin / Admin Dinas: list all orders
            $builder = $db->table('orders o');
            $builder->select('o.*, u.nama as customer_name, k.nama_koperasi');
            $builder->join('users u', 'u.id = o.customer_id');
            $builder->join('koperasi k', 'k.id = o.koperasi_id');
            $builder->orderBy('o.id', 'DESC');
            $orders = $builder->get()->getResultArray();
        }

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $orders
        ]);
    }

    public function show($id)
    {
        $db = \Config\Database::connect();
        
        $order = $db->table('orders o')
            ->select('o.*, u.nama as customer_name, u.email as customer_email, u.phone as customer_phone, k.nama_koperasi, k.logo as koperasi_logo')
            ->join('users u', 'u.id = o.customer_id')
            ->join('koperasi k', 'k.id = o.koperasi_id')
            ->where('o.id', $id)
            ->get()
            ->getRowArray();

        if (!$order) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Pesanan tidak ditemukan'
            ])->setStatusCode(404);
        }

        // Get items in this order
        $items = $db->table('order_items oi')
            ->select('oi.*, p.nama_produk as product_name, p.foto as product_image')
            ->join('products p', 'p.id = oi.product_id')
            ->where('oi.order_id', $id)
            ->get()
            ->getResultArray();

        return $this->response->setJSON([
            'status' => 'success',
            'order' => $order,
            'items' => $items
        ]);
    }

    public function create()
    {
        $db = \Config\Database::connect();
        $orderModel = new OrderModel();
        $orderItemModel = new OrderItemModel();
        $productModel = new ProductModel();

        $rules = [
            'user_id' => 'required',
            'koperasi_id' => 'required',
            'items' => 'required', // JSON array of {product_id, qty}
            'shipping_courier' => 'required',
            'shipping_address' => 'required',
            'total_amount' => 'required|numeric'
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Validasi gagal',
                'errors' => $this->validator->getErrors()
            ])->setStatusCode(400);
        }

        $customerId = $this->request->getVar('user_id');
        $koperasiId = $this->request->getVar('koperasi_id');
        $items = json_decode($this->request->getVar('items'), true);
        $shippingCourier = $this->request->getVar('shipping_courier');
        $shippingAddress = $this->request->getVar('shipping_address');
        $totalAmount = $this->request->getVar('total_amount');
        $shippingCost = $this->request->getVar('shipping_cost') ?: 15000.00;

        if (empty($items)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Keranjang belanja kosong'
            ])->setStatusCode(400);
        }

        // Verify stock and calculate details
        $subtotal = 0;
        $productDetails = [];

        foreach ($items as $item) {
            $product = $productModel->find($item['product_id']);
            if (!$product) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Produk ID ' . $item['product_id'] . ' tidak ditemukan'
                ])->setStatusCode(404);
            }
            if ($product['stok'] < $item['qty']) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'Stok produk "' . $product['nama_produk'] . '" tidak mencukupi (Stok: ' . $product['stok'] . ')'
                ])->setStatusCode(400);
            }

            $subtotal += $product['harga'] * $item['qty'];
            $productDetails[] = [
                'product' => $product,
                'qty' => $item['qty'],
                'price' => $product['harga']
            ];
        }

        $db->transStart();

        $paymentMethod = $this->request->getVar('payment_method') ?: 'saldo';

        // Create Order
        $invoice = 'INV-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
        $orderData = [
            'invoice' => $invoice,
            'customer_id' => $customerId,
            'koperasi_id' => $koperasiId,
            'total' => $totalAmount,
            'status' => 'PENDING_PAYMENT',
            'ongkir' => $shippingCost,
            'kurir' => $shippingCourier,
            'alamat' => $shippingAddress,
            'payment_method' => $paymentMethod,
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $orderId = $orderModel->insert($orderData);

        // Save items & Decrement product stock
        foreach ($productDetails as $pd) {
            $itemData = [
                'order_id' => $orderId,
                'product_id' => $pd['product']['id'],
                'qty' => $pd['qty'],
                'harga' => $pd['price'],
                'subtotal' => $pd['price'] * $pd['qty']
            ];
            $orderItemModel->insert($itemData);

            // Update Stock
            $newStock = $pd['product']['stok'] - $pd['qty'];
            $productModel->update($pd['product']['id'], ['stok' => $newStock]);
        }

        // Add audit log
        $db->table('audit_logs')->insert([
            'user_id' => $customerId,
            'action' => 'Transaksi Baru',
            'notes' => 'Membuat pesanan ' . $invoice . ' sebesar Rp' . number_format($totalAmount, 0, ',', '.'),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $db->transComplete();

        if ($db->transStatus() === false) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Gagal memproses pesanan'
            ])->setStatusCode(500);
        }

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Pesanan berhasil dibuat',
            'data' => [
                'order_id' => $orderId,
                'invoice' => $invoice,
                'total' => $totalAmount,
                'status' => 'PENDING_PAYMENT'
            ]
        ]);
    }

    public function updateStatus($id)
    {
        $orderModel = new OrderModel();
        $order = $orderModel->find($id);

        if (!$order) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Pesanan tidak ditemukan'
            ])->setStatusCode(404);
        }

        $status = $this->request->getVar('status');
        $validStatuses = [
            'PENDING_PAYMENT', 'PAYMENT_VERIFIED', 'WAITING_PROCESS', 'VERIFIKASI_KOPERASI',
            'PACKING', 'READY_TO_SHIP', 'SHIPPED', 'IN_TRANSIT', 'ARRIVED_DESTINATION',
            'OUT_FOR_DELIVERY', 'DELIVERED', 'COMPLETED', 'CANCELLED_BY_CUSTOMER',
            'REJECTED_BY_SELLER', 'PAYMENT_FAILED', 'RETURN_REQUEST', 'RETURN_APPROVED', 'REFUNDED'
        ];

        if (!in_array($status, $validStatuses)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Status tidak valid: ' . $status
            ])->setStatusCode(400);
        }

        $orderModel->update($id, ['status' => $status]);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Update Status Pesanan',
            'notes' => 'Status pesanan ' . $order['invoice'] . ' diperbarui menjadi ' . $status,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Status pesanan berhasil diperbarui menjadi ' . $status
        ]);
    }
}
