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

/**
 * Super Admin Campaigns Controller
 */
class Campaigns 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() {
        $portal_filter = $this->input->get('portal');
        $status_filter = $this->input->get('status');
        
        $data['title'] = 'Campaign Management';
        $data['current_page'] = 'campaigns';
        $data['portals'] = $this->Portal_model->get_all_active();
        $data['portal_filter'] = $portal_filter;
        $data['status_filter'] = $status_filter;
        
        $data['campaigns'] = $this->get_campaigns($portal_filter, $status_filter);
        $data['stats'] = $this->get_campaign_stats();
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/campaigns/index', $data);
        $this->load->view('superadmin/layouts/footer');
    }
    
    private function get_campaigns($portal_filter = null, $status_filter = null) {
        $where = [];
        $params = [];
        
        if ($portal_filter) {
            $where[] = "c.portal_id = ?";
            $params[] = $portal_filter;
        }
        
        if ($status_filter) {
            $where[] = "c.status = ?";
            $params[] = $status_filter;
        }
        
        $where_clause = count($where) > 0 ? 'WHERE ' . implode(' AND ', $where) : '';
        
        $query = $this->db->query("
            SELECT 
                c.id,
                c.name,
                c.template_id,
                c.status,
                c.created_at,
                c.scheduled_at,
                c.portal_id,
                u.username as created_by,
                p.portal_name as portal_name,
                (SELECT COUNT(*) FROM message_schedules WHERE campaign_id = c.id) as schedule_count,
                (SELECT COUNT(*) FROM message_schedules WHERE campaign_id = c.id AND status = 'sent') as sent_count
            FROM campaigns c
            LEFT JOIN users u ON c.user_id = u.id
            LEFT JOIN portals p ON c.portal_id = p.portal_code
            {$where_clause}
            ORDER BY c.created_at DESC
            LIMIT 500
        ", $params);
        
        return $query->result();
    }
    
    private function get_campaign_stats() {
        $stats = [];
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM campaigns");
        $stats['total'] = $query->row()->total;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM campaigns WHERE status = 'active'");
        $stats['active'] = $query->row()->total;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM campaigns WHERE status = 'completed'");
        $stats['completed'] = $query->row()->total;
        
        $query = $this->db->query("SELECT COUNT(*) as total FROM campaigns WHERE DATE(created_at) = CURDATE()");
        $stats['today'] = $query->row()->total;
        
        return $stats;
    }

    public function view($id) {
        $query = $this->db->query("
            SELECT 
                c.*,
                u.username as created_by,
                p.portal_name as portal_name
            FROM campaigns c
            LEFT JOIN users u ON c.user_id = u.id
            LEFT JOIN portals p ON c.portal_id = p.portal_code
            WHERE c.id = ?
        ", [$id]);
        
        if ($query->num_rows() == 0) {
            $this->session->set_flashdata('error', 'Campaign not found.');
            redirect('superadmin/campaigns');
        }
        
        $data['title'] = 'View Campaign';
        $data['current_page'] = 'campaigns';
        $data['campaign'] = $query->row();
        
        // Get message schedules
        $data['batches'] = [];
        $data['schedules'] = $this->db->query("
            SELECT ms.*, md.mobile, md.name as recipient_name
            FROM message_schedules ms
            LEFT JOIN master_data md ON ms.master_data_id = md.id
            WHERE ms.campaign_id = ?
            ORDER BY ms.scheduled_at DESC
            LIMIT 100
        ", [$id])->result();
        
        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/campaigns/view', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function create() {
        $data['title'] = 'Create New Campaign';
        $data['current_page'] = 'campaigns';
        $data['portals'] = $this->Portal_model->get_all_active();
        
        // Get message templates (if table exists)
        $data['templates'] = [];
        try {
            $check = $this->db->query("SHOW TABLES LIKE 'message_templates'");
            if ($check->num_rows() > 0) {
                $data['templates'] = $this->db->query("SELECT id, name, content FROM message_templates WHERE status = 'active' ORDER BY name")->result();
            }
        } catch (Exception $e) {
            // Table doesn't exist, continue with empty templates
        }

        if ($this->input->method() == 'post') {
            $this->form_validation->set_rules('name', 'Campaign Name', 'required|trim');
            $this->form_validation->set_rules('portal_id', 'Portal', 'required');

            if ($this->form_validation->run() === TRUE) {
                $campaign_data = [
                    'name' => $this->input->post('name'),
                    'portal_id' => $this->input->post('portal_id'),
                    'template_id' => $this->input->post('template_id') ?: null,
                    'status' => 'draft',
                    'user_id' => $this->session->userdata('super_admin_id') ?: 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'scheduled_at' => $this->input->post('scheduled_at') ?: null
                ];

                $this->db->insert('campaigns', $campaign_data);
                $campaign_id = $this->db->insert_id();
                
                if ($campaign_id) {
                    $this->Super_admin_model->log_activity('campaign_created', 'Created campaign: ' . $campaign_data['name'], $campaign_data['portal_id']);
                    $this->session->set_flashdata('success', 'Campaign created successfully! Campaign ID: ' . $campaign_id);
                    redirect('superadmin/campaigns');
                } else {
                    $this->session->set_flashdata('error', 'Failed to create campaign: ' . $this->db->error()['message']);
                }
            }
        }

        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/campaigns/create', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function edit($id) {
        $data['title'] = 'Edit Campaign';
        $data['current_page'] = 'campaigns';
        $data['portals'] = $this->Portal_model->get_all_active();
        $data['campaign'] = $this->db->get_where('campaigns', ['id' => $id])->row();
        
        // Get message templates (if table exists)
        $data['templates'] = [];
        try {
            $check = $this->db->query("SHOW TABLES LIKE 'message_templates'");
            if ($check->num_rows() > 0) {
                $data['templates'] = $this->db->query("SELECT id, name, content FROM message_templates WHERE status = 'active' ORDER BY name")->result();
            }
        } catch (Exception $e) {
            // Table doesn't exist
        }

        if (!$data['campaign']) {
            $this->session->set_flashdata('error', 'Campaign not found.');
            redirect('superadmin/campaigns');
        }

        if ($this->input->method() == 'post') {
            $this->form_validation->set_rules('name', 'Campaign Name', 'required|trim');
            $this->form_validation->set_rules('portal_id', 'Portal', 'required');

            if ($this->form_validation->run() === TRUE) {
                $campaign_data = [
                    'name' => $this->input->post('name'),
                    'portal_id' => $this->input->post('portal_id'),
                    'template_id' => $this->input->post('template_id') ?: null,
                    'status' => $this->input->post('status') ?: 'draft',
                    'scheduled_at' => $this->input->post('scheduled_at') ?: null
                ];

                $this->db->update('campaigns', $campaign_data, ['id' => $id]);
                
                $this->Super_admin_model->log_activity('campaign_updated', 'Updated campaign: ' . $campaign_data['name'], $campaign_data['portal_id']);
                $this->session->set_flashdata('success', 'Campaign updated successfully!');
                redirect('superadmin/campaigns');
            }
        }

        $this->load->view('superadmin/layouts/header', $data);
        $this->load->view('superadmin/campaigns/edit', $data);
        $this->load->view('superadmin/layouts/footer');
    }

    public function delete($id) {
        $campaign = $this->db->get_where('campaigns', ['id' => $id])->row();
        
        if (!$campaign) {
            $this->session->set_flashdata('error', 'Campaign not found.');
            redirect('superadmin/campaigns');
        }

        // Delete related message schedules first
        $this->db->delete('message_schedules', ['campaign_id' => $id]);
        
        // Delete the campaign
        $this->db->delete('campaigns', ['id' => $id]);
        
        $this->Super_admin_model->log_activity('campaign_deleted', 'Deleted campaign: ' . $campaign->name, $campaign->portal_id);
        $this->session->set_flashdata('success', 'Campaign deleted successfully!');

        redirect('superadmin/campaigns');
    }

    public function toggle_status($id) {
        $campaign = $this->db->get_where('campaigns', ['id' => $id])->row();
        
        if (!$campaign) {
            $this->session->set_flashdata('error', 'Campaign not found');
            redirect('superadmin/campaigns');
        }
        
        $new_status = ($campaign->status == 'active') ? 'paused' : 'active';
        
        $this->db->update('campaigns', ['status' => $new_status], ['id' => $id]);
        
        $this->Super_admin_model->log_activity(
            'campaign_status_change',
            "Changed campaign {$campaign->name} status to {$new_status}",
            $campaign->portal_id
        );
        
        $this->session->set_flashdata('success', 'Campaign status updated to ' . ucfirst($new_status));
        redirect('superadmin/campaigns');
    }
}
