<?php

namespace App\Controllers;

class MessageController extends BaseController
{
    /**
     * GET /api/messages?koperasi_id=X
     * Get all messages for a koperasi (inbox for seller)
     */
    public function index()
    {
        $db = \Config\Database::connect();
        $koperasiId = $this->request->getVar('koperasi_id');

        $builder = $db->table('product_messages m');
        $builder->select('m.*');

        if ($koperasiId) {
            $builder->where('m.koperasi_id', $koperasiId);
        }

        $builder->orderBy('m.created_at', 'DESC');
        $messages = $builder->get()->getResultArray();

        // Group by product_id for conversation threads
        $threads = [];
        foreach ($messages as $msg) {
            $pid = $msg['product_id'] ?? 0;
            if (!isset($threads[$pid])) {
                $threads[$pid] = [
                    'product_id'   => $pid,
                    'product_name' => $msg['product_name'] ?? 'Produk',
                    'unread_count' => 0,
                    'last_message' => $msg['message'],
                    'last_time'    => $msg['created_at'],
                    'messages'     => []
                ];
            }
            $threads[$pid]['messages'][] = $msg;
            if (!$msg['is_read'] && $msg['sender_role'] === 'customer') {
                $threads[$pid]['unread_count']++;
            }
        }

        return $this->response->setJSON([
            'status'  => 'success',
            'data'    => array_values($threads),
            'total'   => count($messages),
        ]);
    }

    /**
     * GET /api/messages/thread?product_id=X&koperasi_id=Y
     * Get full conversation for a product
     */
    public function thread()
    {
        $db = \Config\Database::connect();
        $productId   = $this->request->getVar('product_id');
        $koperasiId  = $this->request->getVar('koperasi_id');

        $builder = $db->table('product_messages');
        if ($productId)  $builder->where('product_id', $productId);
        if ($koperasiId) $builder->where('koperasi_id', $koperasiId);
        $builder->orderBy('created_at', 'ASC');
        $messages = $builder->get()->getResultArray();

        // Mark all as read for seller
        if ($koperasiId) {
            $db->table('product_messages')
               ->where('koperasi_id', $koperasiId)
               ->where('product_id', $productId)
               ->where('sender_role', 'customer')
               ->update(['is_read' => 1]);
        }

        $customerId = $this->request->getVar('customer_id');
        if ($customerId) {
            $db->table('product_messages')
               ->where('product_id', $productId)
               ->where('sender_role', 'seller')
               ->update(['is_read' => 1]);
        }

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

    /**
     * GET /api/messages/customer?customer_id=X
     * Get all active threads for a customer
     */
    public function customerThreads()
    {
        $db = \Config\Database::connect();
        $customerId = $this->request->getVar('customer_id');

        if (!$customerId) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Customer ID required']);
        }

        // Get product IDs the customer has sent messages to
        $builder = $db->table('product_messages');
        $builder->select('product_id')->distinct();
        $builder->where('sender_id', $customerId);
        $builder->where('sender_role', 'customer');
        $productIdsObj = $builder->get()->getResultArray();
        
        $productIds = array_column($productIdsObj, 'product_id');

        if (empty($productIds)) {
            return $this->response->setJSON(['status' => 'success', 'data' => []]);
        }

        // Fetch all messages for these products so customer can see seller replies too
        $builder = $db->table('product_messages');
        $builder->whereIn('product_id', $productIds);
        $builder->orderBy('created_at', 'ASC');
        $messages = $builder->get()->getResultArray();

        $threads = [];
        foreach ($messages as $msg) {
            $pid = $msg['product_id'];
            if (!isset($threads[$pid])) {
                $threads[$pid] = [
                    'messages'     => [],
                    'unread_count' => 0
                ];
            }
            $threads[$pid]['messages'][] = $msg;
            // Count unread seller replies
            if ($msg['sender_role'] === 'seller' && !$msg['is_read']) {
                $threads[$pid]['unread_count']++;
            }
        }

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

    /**
     * POST /api/messages
     * Send a message (buyer or seller)
     */
    public function send()
    {
        $db = \Config\Database::connect();

        $productId   = $this->request->getVar('product_id');
        $koperasiId  = $this->request->getVar('koperasi_id');
        $senderId    = $this->request->getVar('sender_id');
        $senderName  = $this->request->getVar('sender_name') ?: 'Pengguna';
        $senderRole  = $this->request->getVar('sender_role') ?: 'customer';
        $message     = $this->request->getVar('message');
        $productName = $this->request->getVar('product_name') ?: 'Produk';

        if (!$message) {
            return $this->response->setJSON([
                'status'  => 'error',
                'message' => 'Pesan tidak boleh kosong'
            ])->setStatusCode(400);
        }

        $data = [
            'product_id'   => $productId,
            'koperasi_id'  => $koperasiId,
            'sender_id'    => $senderId,
            'sender_name'  => $senderName,
            'sender_role'  => $senderRole,
            'message'      => $message,
            'product_name' => $productName,
            'is_read'      => 0,
            'created_at'   => date('Y-m-d H:i:s'),
        ];

        $newId = $db->table('product_messages')->insert($data);

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Pesan terkirim',
            'id'      => $db->insertID(),
            'data'    => $data
        ]);
    }

    /**
     * POST /api/messages/unread-count?koperasi_id=X
     * Get unread messages count for badge
     */
    public function unreadCount()
    {
        $db = \Config\Database::connect();
        $koperasiId = $this->request->getVar('koperasi_id');

        $count = $db->table('product_messages')
            ->where('koperasi_id', $koperasiId)
            ->where('sender_role', 'customer')
            ->where('is_read', 0)
            ->countAllResults();

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

    /**
     * GET /api/messages/customer-unread-count?customer_id=X
     * Get unread messages count for customer badge
     */
    public function customerUnreadCount()
    {
        $db = \Config\Database::connect();
        $customerId = $this->request->getVar('customer_id');

        if (!$customerId) {
            return $this->response->setJSON(['status' => 'error', 'count' => 0]);
        }

        $pids = $db->table('product_messages')
            ->select('product_id')->distinct()
            ->where('sender_id', $customerId)
            ->where('sender_role', 'customer')
            ->get()->getResultArray();
        
        $productIds = array_column($pids, 'product_id');

        if (empty($productIds)) {
            return $this->response->setJSON(['status' => 'success', 'count' => 0]);
        }

        $count = $db->table('product_messages')
            ->whereIn('product_id', $productIds)
            ->where('sender_role', 'seller')
            ->where('is_read', 0)
            ->countAllResults();

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

}
