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

class Whatsapp extends MY_Controller {
    public function __construct(){
        parent::__construct();
        $this->load_global();
        $this->load->model('whatsapp_model', 'whatsapp');
    }
    
    // WhatsApp Settings Configuration
    public function index(){
        $this->settings();
    }
    
    public function settings(){
        $this->permission_check('whatsapp_settings');
        $data = $this->data;
        $data['page_title'] = 'WhatsApp Settings';
        
        // Get current store WhatsApp settings
        $store_details = get_store_details();
        $data['whatsapp_status'] = $store_details->whatsapp_status ?? 0;
        $data['whatsapp_api_url'] = $store_details->whatsapp_api_url ?? '';
        $data['whatsapp_api_key'] = $store_details->whatsapp_api_key ?? '';
        $data['whatsapp_api_secret'] = $store_details->whatsapp_api_secret ?? '';
        $data['whatsapp_instance_id'] = $store_details->whatsapp_instance_id ?? '';
        $data['whatsapp_webhook_url'] = $store_details->whatsapp_webhook_url ?? '';
        $data['whatsapp_webhook_token'] = $store_details->whatsapp_webhook_token ?? '';
        $data['whatsapp_send_invoice'] = $store_details->whatsapp_send_invoice ?? 1;
        $data['whatsapp_send_reminders'] = $store_details->whatsapp_send_reminders ?? 1;
        $data['whatsapp_send_notifications'] = $store_details->whatsapp_send_notifications ?? 1;
        $data['whatsapp_business_name'] = $store_details->whatsapp_business_name ?? '';
        $data['whatsapp_default_message'] = $store_details->whatsapp_default_message ?? '';
        
        $this->load->view('whatsapp-settings', $data);
    }

    // Update WhatsApp Settings
    public function update_settings(){
        $this->permission_check_with_msg('whatsapp_settings');
        
        // Extract and sanitize inputs
        extract(xss_html_filter(array_merge($this->data, $_POST, $_GET)));

        // Prepare update data
        $info = array(
            'whatsapp_status' => $whatsapp_status ?? 0,
            'whatsapp_api_url' => $whatsapp_api_url ?? '',
            'whatsapp_api_key' => $whatsapp_api_key ?? '',
            'whatsapp_api_secret' => $whatsapp_api_secret ?? '',
            'whatsapp_instance_id' => $whatsapp_instance_id ?? '',
            'whatsapp_webhook_url' => $whatsapp_webhook_url ?? '',
            'whatsapp_webhook_token' => $whatsapp_webhook_token ?? '',
            'whatsapp_send_invoice' => $whatsapp_send_invoice ?? 0,
            'whatsapp_send_reminders' => $whatsapp_send_reminders ?? 0,
            'whatsapp_send_notifications' => $whatsapp_send_notifications ?? 0,
            'whatsapp_business_name' => $whatsapp_business_name ?? '',
            'whatsapp_default_message' => $whatsapp_default_message ?? ''
        );

        // Update store settings
        $result = $this->db->where("id", get_current_store_id())->update("db_store", $info);
        
        if($result) {
            $this->session->set_flashdata('success', 'WhatsApp settings updated successfully!');
            echo "success";
        } else {
            echo "failed";
        }
    }

    // Test WhatsApp Connection
    public function test_connection(){
        $this->permission_check_with_msg('whatsapp_settings');
        
        $store_details = get_store_details();
        $test_result = $this->whatsapp->test_api_connection($store_details);
        
        echo json_encode($test_result);
    }

    // Send test message to specific number
    public function send_test_message(){
        $this->permission_check_with_msg('whatsapp_settings');
        
        $test_number = '+918883888012';
        $test_message = 'Test message from Minerva Technologies WhatsApp Integration - ' . date('Y-m-d H:i:s');
        
        $result = $this->whatsapp->send_message(
            $test_number,
            $test_message,
            'test',
            null,
            null,
            null
        );
        
        echo json_encode($result);
    }

    // Send WhatsApp Message
    public function send_message(){
        $this->permission_check('whatsapp_send');
        
        $this->form_validation->set_rules('phone_number', 'Phone Number', 'trim|required');
        $this->form_validation->set_rules('message', 'Message', 'trim|required');
        
        if ($this->form_validation->run() == TRUE) {
            extract($this->security->xss_clean(html_escape($_POST)));
            
            $result = $this->whatsapp->send_message(
                $phone_number,
                $message,
                'manual',
                null,
                null
            );
            
            echo json_encode($result);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Please provide phone number and message.']);
        }
    }

    // Send Message Form
    public function compose(){
        $this->permission_check('whatsapp_send');
        $data = $this->data;
        $data['page_title'] = 'Send WhatsApp Message';
        
        // Get customers for dropdown - simple approach
        $data['customers'] = $this->db->select('id, customer_name, mobile')
                                     ->where('store_id', get_current_store_id())
                                     ->where('status', 1)
                                     ->get('db_customers')->result();
        
        // Get templates
        $data['templates'] = $this->whatsapp->get_templates();
        
        $this->load->view('whatsapp-compose', $data);
    }

    // Message Templates Management
    public function templates(){
        $this->permission_check('whatsapp_templates_view');
        $data = $this->data;
        $data['page_title'] = 'WhatsApp Templates';
        $this->load->view('whatsapp-templates-list', $data);
    }

    // WhatsApp Logs
    public function logs(){
        $this->permission_check('whatsapp_logs_view');
        $data = $this->data;
        $data['page_title'] = 'WhatsApp Message Logs';
        $this->load->view('whatsapp-logs', $data);
    }

    // Ajax list for templates
    public function templates_ajax_list(){
        $list = $this->whatsapp->get_templates_datatables();
        
        $data = array();
        $no = $_POST['start'];
        foreach ($list as $template) {
            $no++;
            $row = array();
            
            // 0: Template Name
            $row[] = $template->template_name;
            // 1: Type
            $row[] = ucfirst($template->template_type);
            // 2: Subject
            $row[] = isset($template->template_subject) ? $template->template_subject : '';
            // 3: Content (preview)
            $content = isset($template->template_content) ? $template->template_content : '';
            $row[] = (strlen($content) > 100) ? substr($content, 0, 100) . '...' : $content;
            
            // 4: Status
            if(isset($template->status) && (int)$template->status === 1) {
                $status_html = "<span class='label label-success'>Active</span>";
                $toggle_btn = "<button class=\"btn btn-warning btn-sm\" onclick=\"update_template_status(".$template->id.",0)\">Deactivate</button>";
            } else {
                $status_html = "<span class='label label-danger'>Inactive</span>";
                $toggle_btn = "<button class=\"btn btn-success btn-sm\" onclick=\"update_template_status(".$template->id.",1)\">Activate</button>";
            }
            $row[] = $status_html;
            
            // 5: Actions
            $delete_btn = "<button class=\"btn btn-danger btn-sm\" onclick=\"delete_template(".$template->id.")\"><i class=\"fa fa-trash\"></i></button>";
            $actions = '<div class="btn-group">'.$toggle_btn.' '.$delete_btn.'</div>';
            $row[] = $actions;
            
            $data[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->whatsapp->count_all_templates(),
            "recordsFiltered" => $this->whatsapp->count_filtered_templates(),
            "data" => $data,
        );
        
        echo json_encode($output);
    }

    // Add new template
    public function add_template() {
        $this->permission_check_with_msg('whatsapp_templates_edit');

        $post = $this->security->xss_clean($this->input->post());
        $template_name = trim($post['template_name'] ?? '');
        $template_type = trim($post['template_type'] ?? '');
        $template_subject = trim($post['template_subject'] ?? '');
        $template_content = trim($post['template_content'] ?? '');

        if($template_name === '' || $template_type === '' || $template_content === '') {
            echo "Template name, type and content are required";
            return;
        }

        $data = array(
            'store_id' => get_current_store_id(),
            'template_name' => $template_name,
            'template_type' => $template_type,
            'template_subject' => $template_subject,
            'template_content' => $template_content,
            'status' => 1,
            'is_default' => 0,
            'created_date' => date('Y-m-d'),
            'created_time' => date('H:i:s'),
            'created_by' => $this->session->userdata('inv_username') ?? 'System'
        );

        $ok = $this->db->insert('db_whatsapp_templates', $data);
        echo $ok ? 'success' : 'Failed to save template';
    }

    // Update template status (activate/deactivate)
    public function update_template_status() {
        $this->permission_check_with_msg('whatsapp_templates_edit');
        $id = (int)$this->input->post('id');
        $status = (int)$this->input->post('status');
        if(!$id) { echo 'Invalid template id'; return; }
        $this->whatsapp->update_template_status($id, $status);
    }

    // Delete template
    public function delete_template() {
        $this->permission_check_with_msg('whatsapp_templates_edit');
        $id = (int)$this->input->post('template_id');
        if(!$id) { echo 'Invalid template id'; return; }
        $this->whatsapp->delete_template($id);
    }

    // View Log Details
    public function view_log($id){
        $this->permission_check('whatsapp_logs_view');
        
        $log = $this->whatsapp->get_log($id);
        if(!$log) {
            show_404();
        }
        
        echo json_encode($log);
    }

    // Ajax list for logs
    public function logs_ajax_list(){
        $this->permission_check('whatsapp_logs_view');
        $list = $this->whatsapp->get_logs_datatables();

        $data = array();
        $no = $_POST['start'];
        foreach ($list as $log) {
            $no++;
            $row = array();

            // 0: Phone Number
            $row[] = $log->phone_number;
            // 1: Message Type
            $row[] = ucfirst($log->message_type);
            // 2: Message Content (preview)
            $msg = isset($log->message_content) ? $log->message_content : '';
            $row[] = (strlen($msg) > 100) ? substr($msg, 0, 100) . '...' : $msg;
            // 3: Status
            $status = isset($log->status) ? strtolower($log->status) : '';
            $label = 'label-default';
            if($status === 'sent') $label = 'label-success';
            elseif($status === 'failed') $label = 'label-danger';
            elseif($status === 'pending') $label = 'label-warning';
            $row[] = "<span class='label {$label}'>".ucfirst($status ?: 'N/A')."</span>";
            // 4: Sent At
            $row[] = $log->sent_at;
            // 5: Actions
            $actions = '<button class="btn btn-info btn-sm" onclick="view_log_details('.$log->id.')"><i class="fa fa-eye"></i> View</button>';
            $row[] = $actions;

            $data[] = $row;
        }

        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->whatsapp->count_all_logs(),
            "recordsFiltered" => $this->whatsapp->count_filtered_logs(),
            "data" => $data,
        );

        echo json_encode($output);
    }

    // Webhook endpoint for receiving WhatsApp messages
    public function webhook(){
        // Simple webhook response
        if($this->input->get('hub_challenge')) {
            echo $this->input->get('hub_challenge');
            return;
        }
        
        // Process incoming message
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        // Log the webhook data (basic implementation)
        if($data) {
            log_message('info', 'WhatsApp Webhook Data: ' . json_encode($data));
        }
        
        http_response_code(200);
    }
}
