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

/**
 * Super Admin Messages Controller
 * Send messages across all portals
 */
class Messages extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('superadmin/Portal_model');
        $this->load->model('superadmin/Super_admin_model');
        $this->_check_super_admin();
    }

    private function _check_super_admin() {
        if ($this->session->userdata('super_admin_logged_in') !== TRUE) {
            redirect('superadmin/auth/login');
        }
    }

    public function index() {
        $data['title'] = 'Message Center';
        $data['current_page'] = 'messages';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        // Get message statistics
        $data['stats'] = $this->get_message_stats();
        $data['recent_messages'] = $this->get_recent_messages();
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/messages/index', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    private function get_message_stats() {
        $stats = [];
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM message_schedules");
        $stats['total'] = $query->row()->total ?? 0;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM message_schedules WHERE status = 'sent'");
        $stats['sent'] = $query->row()->total ?? 0;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM message_schedules WHERE status = 'failed'");
        $stats['failed'] = $query->row()->total ?? 0;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM message_schedules WHERE status = 'pending'");
        $stats['pending'] = $query->row()->total ?? 0;
        
        return $stats;
    }

    private function get_recent_messages($limit = 50) {
        return $this->db->query("
            SELECT 
                ms.id,
                ms.message,
                ms.status,
                ms.scheduled_date,
                ms.scheduled_time,
                ms.sent_at,
                ms.created_at,
                c.name as campaign_name,
                c.portal_id,
                p.portal_name
            FROM message_schedules ms
            LEFT JOIN campaigns c ON ms.campaign_id = c.id
            LEFT JOIN portals p ON c.portal_id = p.portal_code
            ORDER BY ms.created_at DESC
            LIMIT ?
        ", [$limit])->result();
    }

    public function send() {
        $data['title'] = 'Send New Message';
        $data['current_page'] = 'messages';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        if ($this->input->method() == 'post') {
            $portal_id = $this->input->post('portal_id');
            $message_template = $this->input->post('message');
            $send_count = (int)$this->input->post('send_count');
            $scheduled_date = $this->input->post('scheduled_date');
            $scheduled_time = $this->input->post('scheduled_time');
            
            if (empty($portal_id) || empty($message_template)) {
                $this->session->set_flashdata('error', 'Portal and message are required');
                redirect('superadmin/messages/send');
            }
            
            // Get campaign for this portal (or create one)
            $campaign = $this->db->where('portal_id', $portal_id)->where('status', 'active')->get('campaigns')->row();
            
            if (!$campaign) {
                // Create a default campaign for super admin messages
                $this->db->insert('campaigns', [
                    'name' => 'Super Admin Campaign - ' . date('Y-m-d'),
                    'portal_id' => $portal_id,
                    'status' => 'active',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                $campaign_id = $this->db->insert_id();
            } else {
                $campaign_id = $campaign->id;
            }
            
            // Get master data for this portal
            $this->db->where('portal_id', $portal_id);
            $this->db->limit($send_count);
            $records = $this->db->get('master_data')->result();
            
            $scheduled = 0;
            foreach ($records as $record) {
                // Replace placeholders in message
                $message = $message_template;
                $message = str_replace('{name}', $record->name ?? '', $message);
                $message = str_replace('{phone}', $record->phone ?? $record->mobile ?? '', $message);
                $message = str_replace('{email}', $record->email ?? '', $message);
                $message = str_replace('{city}', $record->city ?? '', $message);
                
                $this->db->insert('message_schedules', [
                    'campaign_id' => $campaign_id,
                    'master_data_id' => $record->id,
                    'message' => $message,
                    'scheduled_date' => $scheduled_date ?: date('Y-m-d'),
                    'scheduled_time' => $scheduled_time ?: date('H:i:s'),
                    'status' => 'pending',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                $scheduled++;
            }
            
            $this->Super_admin_model->log_activity('messages_scheduled', "Scheduled {$scheduled} messages for portal: {$portal_id}", $portal_id);
            $this->session->set_flashdata('success', "Successfully scheduled {$scheduled} messages!");
            redirect('superadmin/messages');
        }
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/messages/send', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function portal($portal_code) {
        $portal = $this->Portal_model->get_by_code($portal_code);
        
        if (!$portal) {
            show_404();
        }
        
        $data['title'] = $portal->name . ' - Messages';
        $data['current_page'] = 'messages';
        $data['portal'] = $portal;
        
        // Get messages for this portal
        $data['messages'] = $this->db->query("
            SELECT 
                ms.id,
                ms.message,
                ms.status,
                ms.scheduled_date,
                ms.scheduled_time,
                ms.sent_at,
                ms.error_message,
                ms.created_at,
                c.name as campaign_name,
                md.name as recipient_name,
                md.phone as recipient_phone
            FROM message_schedules ms
            LEFT JOIN campaigns c ON ms.campaign_id = c.id
            LEFT JOIN master_data md ON ms.master_data_id = md.id
            WHERE c.portal_id = ?
            ORDER BY ms.created_at DESC
            LIMIT 500
        ", [$portal_code])->result();
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/messages/portal', $data);
        $this->load->view('superadmin/layouts/footer');
    }
}
