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

class Chat extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $this->load->model('Chat_model');
        $this->load->model('admin/Penghuni_model');
        $this->load->helper('url');
        $this->load->library('form_validation');
    }

    /**
     * Chat List Page - Daftar semua chat dengan penghuni
     */
    public function index($id_penghuni = null)
    {
        $id_admin = $this->session->userdata('admin_id');
        $admin_name = $this->session->userdata('admin_name');

        // Check subscription
        $sub = $this->Chat_model->check_subscription($id_admin);
        if (!$sub) {
            $this->session->set_flashdata('error', 'Anda belum mengaktifkan fitur chat. Silakan berlangganan terlebih dahulu.');
            redirect('admin/dashboard');
        }

        // If no penghuni ID provided, show chat list
        if (!$id_penghuni) {
            $this->chat_list();
            return;
        }

        // Get messages and penghuni data
        $data['messages'] = $this->Chat_model->get_messages($id_penghuni, $id_admin);
        $data['penghuni'] = $this->Penghuni_model->get_by_id($id_penghuni);

        if (!$data['penghuni']) {
            show_error('Penghuni tidak ditemukan', 404);
        }

        $data['title'] = "Chat dengan " . ($data['penghuni']->nama_penghuni ?? 'Penghuni');

        // Pass WebSocket config
        $data['ws_config'] = [
            'ws_url' => $this->config->item('ws_url') ?? 'localhost:3001',
            'userType' => 'admin',
            'userId' => $id_admin,
            'targetType' => 'penghuni',
            'targetId' => $id_penghuni,
            'userName' => $admin_name,
            'targetName' => $data['penghuni']->nama_penghuni ?? 'Penghuni'
        ];

        // Mark messages as read when opening chat
        $this->Chat_model->mark_all_as_read_admin($id_penghuni, $id_admin);

        $this->load->view('admin/chat/index', $data);
    }

    /**
     * Chat List Page
     */
    public function chat_list()
    {
        $id_admin = $this->session->userdata('admin_id');

        // Get all chat sessions with penghuni
        $chat_sessions = $this->Chat_model->get_chat_sessions($id_admin);

        // Process each session for display
        foreach ($chat_sessions as &$session) {
            // Get latest message
            $last_message = $this->Chat_model->get_last_message($session->id_penghuni, $id_admin);
            if ($last_message) {
                $session->last_message = $last_message->message;
                $session->last_message_time = $last_message->created_at;
                $session->last_message_at = $last_message->created_at;
            }

            // Get unread count for admin
            $session->unread_count_admin = $this->Chat_model->get_unread_count_admin($session->id_penghuni, $id_admin);

            // Check if penghuni is online (simplified - in real app use WebSocket/Redis)
            $session->is_online = $this->Chat_model->get_online_status('penghuni', $session->id_penghuni);
        }

        $data['chat_sessions'] = $chat_sessions;
        $data['title'] = "Daftar Chat";
        $data['ws_config'] = [
            'ws_url' => $this->config->item('ws_url') ?? 'localhost:3001',
            'userType' => 'admin',
            'userId' => $id_admin,
            'userName' => $this->session->userdata('admin_name')
        ];

        $this->load->view('admin/chat/list', $data);
    }

    /**
     * API: Send Message
     */
    public function send()
    {
        // Set JSON header
        header('Content-Type: application/json');

        // Debug mode
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $this->input->post('id_penghuni');
        $message = $this->input->post('message', true);

        // Log input
        error_log("=== SEND MESSAGE ===");
        error_log("Admin ID: " . $id_admin);
        error_log("Penghuni ID: " . $id_penghuni);
        error_log("Message: " . $message);

        // Validation
        if (empty($id_penghuni) || empty($message)) {
            error_log("Validation failed: empty data");
            echo json_encode([
                'status' => 'error',
                'message' => 'Data tidak lengkap'
            ]);
            return;
        }
        try {
            // Check subscription
            $sub = $this->Chat_model->check_subscription($id_admin);
            if (!$sub) {
                error_log("Subscription not active for admin: " . $id_admin);
                echo json_encode(['status' => 'error', 'message' => 'Fitur chat belum diaktifkan']);
                return;
            }

            // Prepare message data
            $messageData = [
                'id_penghuni' => $id_penghuni,
                'id_admin' => $id_admin,
                'message' => $message,
                'sender' => 'admin',
                'is_read' => 0,
                'is_read_admin' => 1,
                'is_read_penghuni' => 0,
                'created_at' => date('Y-m-d H:i:s')
            ];

            error_log("Sending message data: " . print_r($messageData, true));

            // Send message
            $result = $this->Chat_model->send_message($messageData);

            error_log("Message sent, result: " . ($result ? $result : 'false'));

            if ($result) {
                echo json_encode([
                    'status' => 'success',
                    'message_id' => $result,
                    'message' => 'Pesan berhasil dikirim',
                    'timestamp' => date('Y-m-d H:i:s')
                ]);
            } else {
                error_log("Failed to send message");
                echo json_encode(['status' => 'error', 'message' => 'Gagal mengirim pesan']);
            }
        } catch (Exception $e) {
            error_log("Exception in send: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            echo json_encode([
                'status' => 'error',
                'message' => 'Terjadi kesalahan: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * API: Get Messages (for AJAX loading)
     */
    public function get_messages()
    {
        // Set JSON header
        header('Content-Type: application/json');

        // Enable error reporting for debugging
        error_reporting(E_ALL);
        ini_set('display_errors', 0); // Set to 0 untuk production, 1 untuk debugging

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $this->input->get('id_penghuni');

        // Debug log
        error_log("=== GET MESSAGES CALLED ===");
        error_log("Admin ID: " . $id_admin);
        error_log("Penghuni ID from GET: " . $id_penghuni);

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        try {
            // Get messages
            $messages = $this->Chat_model->get_messages($id_penghuni, $id_admin);

            error_log("Found " . count($messages) . " messages");

            // Mark as read when fetching
            $this->Chat_model->mark_all_as_read_admin($id_penghuni, $id_admin);

            // Format messages for JSON response
            $formatted_messages = [];
            foreach ($messages as $message) {
                $formatted_messages[] = [
                    'id_chat' => $message->id_chat,
                    'message' => $message->message,
                    'sender' => $message->sender,
                    'created_at' => $message->created_at,
                    'is_read_admin' => $message->is_read_admin,
                    'is_read_penghuni' => $message->is_read_penghuni
                ];
            }

            echo json_encode([
                'status' => 'success',
                'messages' => $formatted_messages,
                'count' => count($formatted_messages)
            ]);
        } catch (Exception $e) {
            error_log("Error in get_messages: " . $e->getMessage());
            echo json_encode([
                'status' => 'error',
                'message' => 'Terjadi kesalahan saat mengambil pesan: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * API: Get Chat List (AJAX refresh)
     */
    public function get_chat_list()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');

        // Get all chat sessions with penghuni
        $chat_sessions = $this->Chat_model->get_chat_sessions($id_admin);

        // Process each session
        $sessions = [];
        foreach ($chat_sessions as $session) {
            $last_message = $this->Chat_model->get_last_message($session->id_penghuni, $id_admin);

            $sessions[] = [
                'id_penghuni' => $session->id_penghuni,
                'nama_penghuni' => $session->nama_penghuni,
                'kamar' => $session->kamar,
                'email' => $session->email,
                'last_message' => $last_message ? $last_message->message : null,
                'last_message_time' => $last_message ? $last_message->created_at : null,
                'unread_count_admin' => $this->Chat_model->get_unread_count_admin($session->id_penghuni, $id_admin),
                'is_online' => $this->Chat_model->check_user_online($session->id_penghuni, 'penghuni')
            ];
        }

        echo json_encode([
            'status' => 'success',
            'data' => [
                'sessions' => $sessions,
                'total_unread' => $this->Chat_model->get_total_unread_admin($id_admin),
                'timestamp' => time()
            ]
        ]);
    }

    /**
     * API: Get Unread Count (Total)
     */
    public function get_unread_count()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $count = $this->Chat_model->get_total_unread_admin($id_admin);

        echo json_encode([
            'status' => 'success',
            'count' => $count,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * API: Get Unread Count for Specific Penghuni
     */
    public function get_unread_count_penghuni($id_penghuni = null)
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $id_penghuni ?: $this->input->get('id_penghuni');

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        $count = $this->Chat_model->get_unread_count_admin($id_penghuni, $id_admin);

        echo json_encode([
            'status' => 'success',
            'count' => $count,
            'id_penghuni' => $id_penghuni
        ]);
    }

    /**
     * API: Mark Messages as Read
     */
    public function mark_as_read()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $this->input->post('id_penghuni');
        $message_ids = $this->input->post('message_ids');

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        if ($message_ids && is_array($message_ids)) {
            // Mark specific messages as read
            $result = $this->Chat_model->mark_messages_as_read_admin($message_ids, $id_admin);
        } else {
            // Mark all messages from this penghuni as read
            $result = $this->Chat_model->mark_all_as_read_admin($id_penghuni, $id_admin);
        }

        echo json_encode([
            'status' => $result ? 'success' : 'error',
            'id_penghuni' => $id_penghuni
        ]);
    }

    /**
     * API: Get Online Status
     */
    public function get_online_status($id_penghuni = null)
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_penghuni = $id_penghuni ?: $this->input->get('id_penghuni');

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        $is_online = $this->Chat_model->check_user_online($id_penghuni, 'penghuni');
        $last_seen = $this->Chat_model->get_last_seen($id_penghuni, 'penghuni');

        echo json_encode([
            'status' => 'success',
            'is_online' => $is_online,
            'last_seen' => $last_seen,
            'id_penghuni' => $id_penghuni
        ]);
    }

    /**
     * API: Search Penghuni
     */
    public function search_penghuni()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $search_term = $this->input->get('q', true);
        $limit = $this->input->get('limit') ?: 10;

        if (empty($search_term)) {
            echo json_encode(['status' => 'error', 'message' => 'Kata kunci pencarian diperlukan']);
            return;
        }

        $results = $this->Chat_model->search_penghuni($id_admin, $search_term, $limit);

        echo json_encode([
            'status' => 'success',
            'results' => $results,
            'count' => count($results)
        ]);
    }

    /**
     * API: Delete Message
     */
    public function delete_message($message_id = null)
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $message_id = $message_id ?: $this->input->post('message_id');

        if (!$message_id) {
            echo json_encode(['status' => 'error', 'message' => 'ID pesan diperlukan']);
            return;
        }

        // Verify ownership
        $message = $this->Chat_model->get_message_by_id($message_id);
        if (!$message || $message->id_admin != $id_admin) {
            echo json_encode(['status' => 'error', 'message' => 'Pesan tidak ditemukan atau tidak memiliki akses']);
            return;
        }

        $result = $this->Chat_model->delete_message($message_id);

        echo json_encode([
            'status' => $result ? 'success' : 'error',
            'message' => $result ? 'Pesan berhasil dihapus' : 'Gagal menghapus pesan'
        ]);
    }

    /**
     * API: Clear Chat History
     */
    public function clear_chat()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $this->input->post('id_penghuni');

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        $result = $this->Chat_model->clear_chat_history($id_penghuni, $id_admin);

        echo json_encode([
            'status' => $result ? 'success' : 'error',
            'message' => $result ? 'Riwayat chat berhasil dihapus' : 'Gagal menghapus riwayat chat'
        ]);
    }

    /**
     * API: Get Chat Statistics
     */
    public function get_statistics()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $time_range = $this->input->get('time_range') ?: 'today'; // today, week, month, year

        $stats = $this->Chat_model->get_chat_statistics($id_admin, $time_range);

        echo json_encode([
            'status' => 'success',
            'data' => $stats,
            'time_range' => $time_range
        ]);
    }

    /**
     * WebSocket Notification Helper
     */
    private function send_ws_notification($id_penghuni, $id_admin, $message)
    {
        // In real implementation, this would send a message to WebSocket server
        // Using Redis, Socket.io, or direct WebSocket connection

        // Example structure for WebSocket message
        $ws_message = [
            'type' => 'message',
            'from' => [
                'type' => 'admin',
                'id' => $id_admin,
                'name' => $this->session->userdata('admin_name')
            ],
            'to' => [
                'type' => 'penghuni',
                'id' => $id_penghuni
            ],
            'message' => $message,
            'timestamp' => time(),
            'message_id' => $this->db->insert_id() // Get last inserted ID
        ];

        // Here you would implement the actual WebSocket push
        // For example, using Redis publish:
        // $this->redis->publish('chat_channel', json_encode($ws_message));

        // Or using external WebSocket server API call
        // $this->curl->post('http://websocket-server:3001/broadcast', $ws_message);

        return true;
    }

    /**
     * Export Chat History
     */
    public function export_chat($id_penghuni = null)
    {
        $id_admin = $this->session->userdata('admin_id');

        if (!$id_penghuni) {
            show_error('ID penghuni diperlukan');
        }

        // Get all messages
        $messages = $this->Chat_model->get_all_messages($id_penghuni, $id_admin);
        $penghuni = $this->Penghuni_model->get_by_id($id_penghuni);

        // Generate CSV
        $filename = 'chat_history_' . $penghuni->nama_penghuni . '_' . date('Ymd_His') . '.csv';

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $output = fopen('php://output', 'w');

        // CSV header
        fputcsv($output, ['Tanggal', 'Waktu', 'Pengirim', 'Pesan']);

        // Data rows
        foreach ($messages as $message) {
            $date = date('Y-m-d', strtotime($message->created_at));
            $time = date('H:i:s', strtotime($message->created_at));
            $sender = $message->sender == 'admin' ? 'Admin' : $penghuni->nama_penghuni;

            fputcsv($output, [$date, $time, $sender, $message->message]);
        }

        fclose($output);
        exit;
    }

    /**
     * API: Update Typing Status
     */
    public function typing_status()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');
        $id_penghuni = $this->input->post('id_penghuni');
        $is_typing = $this->input->post('is_typing') == 'true';

        if (!$id_penghuni) {
            echo json_encode(['status' => 'error', 'message' => 'ID penghuni diperlukan']);
            return;
        }

        // Update typing status in database or cache
        $this->Chat_model->update_typing_status($id_admin, 'admin', $id_penghuni, $is_typing);

        // Send WebSocket notification
        $ws_message = [
            'type' => 'typing',
            'from' => [
                'type' => 'admin',
                'id' => $id_admin,
                'name' => $this->session->userdata('admin_name')
            ],
            'to' => [
                'type' => 'penghuni',
                'id' => $id_penghuni
            ],
            'isTyping' => $is_typing,
            'timestamp' => time()
        ];

        // Send to WebSocket server
        // $this->send_ws_notification($ws_message);

        echo json_encode([
            'status' => 'success',
            'is_typing' => $is_typing
        ]);
    }

    /**
     * API: Check Server Status
     */
    public function check_server_status()
    {
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_admin = $this->session->userdata('admin_id');

        $status = [
            'server_time' => date('Y-m-d H:i:s'),
            'timestamp' => time(),
            'admin_id' => $id_admin,
            'subscription_active' => $this->Chat_model->check_subscription($id_admin),
            'total_chats' => $this->Chat_model->count_total_chats($id_admin),
            'total_unread' => $this->Chat_model->get_total_unread_admin($id_admin),
            'memory_usage' => memory_get_usage(true) / 1024 / 1024 . ' MB',
            'server_load' => sys_getloadavg()[0] ?? 'N/A'
        ];

        echo json_encode([
            'status' => 'success',
            'data' => $status
        ]);
    }

    /**
     * Test WebSocket Connection
     */
    public function test_websocket()
    {
        $data['title'] = 'Test WebSocket Connection';
        $data['ws_url'] = $this->config->item('ws_url') ?? 'localhost:3001';
        $data['admin_id'] = $this->session->userdata('admin_id');
        $data['admin_name'] = $this->session->userdata('admin_name');

        $this->load->view('admin/chat/test_websocket', $data);
    }

    /**
     * Error Handling - Page Not Found
     */
    public function _404()
    {
        $this->load->view('errors/html/error_404');
    }
}
