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

use chriskacerguis\RestServer\RestController;
use chriskacerguis\RestServer\Format;

class Chat_api extends RestController {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('Chat_api_model');
        $this->load->library('form_validation');
    }
    
    // Authenticate user for WebSocket
    public function authenticate_post() {
        $this->form_validation->set_rules('user_type', 'User Type', 'required|in_list[admin,penghuni]');
        $this->form_validation->set_rules('user_id', 'User ID', 'required|integer');
        
        if ($this->form_validation->run() == FALSE) {
            $this->response([
                'status' => false,
                'message' => validation_errors()
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $userType = $this->post('user_type');
        $userId = $this->post('user_id');
        
        // Verify user exists and get additional info
        $userInfo = $this->Chat_api_model->get_user_info($userType, $userId);
        
        if (!$userInfo) {
            $this->response([
                'status' => false,
                'message' => 'User not found'
            ], RestController::HTTP_UNAUTHORIZED);
        }
        
        // Generate token for WebSocket authentication
        $token = bin2hex(random_bytes(32));
        $expires = time() + 3600; // 1 hour
        
        // Store token
        $this->Chat_api_model->store_auth_token($token, $userType, $userId, $expires);
        
        $this->response([
            'status' => true,
            'token' => $token,
            'expires' => $expires,
            'user' => $userInfo
        ], RestController::HTTP_OK);
    }
    
    // Get chat history
    public function messages_get() {
        $id_penghuni = $this->get('penghuni_id');
        $id_admin = $this->get('admin_id');
        $limit = $this->get('limit') ?: 50;
        $offset = $this->get('offset') ?: 0;
        
        if (!$id_penghuni || !$id_admin) {
            $this->response([
                'status' => false,
                'message' => 'Missing required parameters'
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $messages = $this->Chat_api_model->get_messages($id_penghuni, $id_admin, $limit, $offset);
        
        $this->response([
            'status' => true,
            'messages' => $messages,
            'count' => count($messages)
        ], RestController::HTTP_OK);
    }
    
    // Send message
    public function messages_post() {
        $this->form_validation->set_rules('id_penghuni', 'Penghuni ID', 'required|integer');
        $this->form_validation->set_rules('id_admin', 'Admin ID', 'required|integer');
        $this->form_validation->set_rules('message', 'Message', 'required');
        $this->form_validation->set_rules('sender', 'Sender', 'required|in_list[admin,penghuni]');
        
        if ($this->form_validation->run() == FALSE) {
            $this->response([
                'status' => false,
                'message' => validation_errors()
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $messageData = [
            'id_penghuni' => $this->post('id_penghuni'),
            'id_admin' => $this->post('id_admin'),
            'message' => $this->post('message'),
            'sender' => $this->post('sender'),
            'message_type' => $this->post('message_type') ?: 'text',
            'file_url' => $this->post('file_url'),
            'is_read' => 0,
            'is_delivered' => 0,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $messageId = $this->Chat_api_model->save_message($messageData);
        
        if ($messageId) {
            // Update unread count
            $this->Chat_api_model->update_unread_count(
                $messageData['id_penghuni'],
                $messageData['id_admin'],
                $messageData['sender']
            );
            
            $this->response([
                'status' => true,
                'message_id' => $messageId,
                'message' => 'Message sent successfully'
            ], RestController::HTTP_OK);
        } else {
            $this->response([
                'status' => false,
                'message' => 'Failed to send message'
            ], RestController::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
    
    // Mark messages as read
    public function read_post() {
        $this->form_validation->set_rules('message_ids', 'Message IDs', 'required');
        $this->form_validation->set_rules('reader_type', 'Reader Type', 'required|in_list[admin,penghuni]');
        $this->form_validation->set_rules('reader_id', 'Reader ID', 'required|integer');
        
        if ($this->form_validation->run() == FALSE) {
            $this->response([
                'status' => false,
                'message' => validation_errors()
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $messageIds = json_decode($this->post('message_ids'), true);
        $readerType = $this->post('reader_type');
        $readerId = $this->post('reader_id');
        
        $updated = $this->Chat_api_model->mark_as_read($messageIds, $readerType, $readerId);
        
        $this->response([
            'status' => true,
            'updated' => $updated,
            'message' => 'Messages marked as read'
        ], RestController::HTTP_OK);
    }
    
    // Get unread counts
    public function unread_get() {
        $userType = $this->get('user_type');
        $userId = $this->get('user_id');
        
        if (!$userType || !$userId) {
            $this->response([
                'status' => false,
                'message' => 'Missing required parameters'
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $count = $this->Chat_api_model->get_unread_count($userType, $userId);
        
        $this->response([
            'status' => true,
            'unread_count' => $count
        ], RestController::HTTP_OK);
    }
    
    // Get online status
    public function online_status_get() {
        $userType = $this->get('user_type');
        $userId = $this->get('user_id');
        
        if (!$userType || !$userId) {
            $this->response([
                'status' => false,
                'message' => 'Missing required parameters'
            ], RestController::HTTP_BAD_REQUEST);
        }
        
        $status = $this->Chat_api_model->get_online_status($userType, $userId);
        
        $this->response([
            'status' => true,
            'is_online' => $status
        ], RestController::HTTP_OK);
    }
}