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

class Pro_settings extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load_global();
        $this->load->helper('custom');
        $this->load->model('Pro_settings_model');
        $this->load->model('Users_model');
    }
    
    public function index() {
        if(!$this->permissions('pro_settings_view')){
            $this->show_access_denied_page();
        }
        
        $data = $this->data;
        $data['page_title'] = 'Purchase Requisition Settings';
        $data['settings'] = $this->Pro_settings_model->get_all_settings();
        
        // Load users for approval user management
        $this->db->select('id, username, first_name, last_name, email');
        $this->db->from('db_users');
        $this->db->where('status', 1);
        $this->db->order_by('username', 'ASC');
        $query = $this->db->get();
        $data['users'] = $query->result();
        
        $this->load->view('pro-settings', $data);
    }
    
    public function save_settings() {
        if(!$this->permissions('pro_settings_edit')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $settings = $this->input->post('settings');
        $success = true;
        $message = 'Settings saved successfully';
        
        if ($settings && is_array($settings)) {
            foreach ($settings as $setting_name => $setting_data) {
                $result = $this->Pro_settings_model->update_setting(
                    $setting_name,
                    $setting_data['value'],
                    $setting_data['type'],
                    $setting_data['description']
                );
                
                if (!$result) {
                    $success = false;
                    $message = 'Error saving some settings';
                    break;
                }
            }
        }
        
        echo json_encode(array('success' => $success, 'message' => $message));
    }
    
    public function reset_to_default() {
        if(!$this->permissions('pro_settings_edit')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $result = $this->Pro_settings_model->reset_to_default_settings();
        
        if ($result) {
            echo json_encode(array('success' => true, 'message' => 'Settings reset to default values'));
        } else {
            echo json_encode(array('success' => false, 'message' => 'Error resetting settings'));
        }
    }
    
    public function get_setting_value() {
        $setting_name = $this->input->post('setting_name');
        $value = get_pro_setting($setting_name);
        
        echo json_encode(array('success' => true, 'value' => $value));
    }
    
    public function test_notifications() {
        if(!$this->permissions('pro_settings_edit')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $notification_type = $this->input->post('notification_type'); // email or sms
        $test_message = "This is a test notification for Purchase Requisition Order system.";
        
        if ($notification_type === 'email') {
            // Send test email using SMTP settings
            $store_details = get_store_details();
            if (!$store_details->smtp_status) {
                echo json_encode(array('success' => false, 'message' => 'SMTP is disabled. Please enable SMTP in Settings > SMTP'));
                return;
            }
            
            $this->load->library('email');
            $config = array(
                'protocol' => 'smtp',
                'smtp_host' => $store_details->smtp_host,
                'smtp_port' => $store_details->smtp_port,
                'smtp_user' => $store_details->smtp_user,
                'smtp_pass' => $store_details->smtp_pass,
                'mailtype' => 'html',
                'charset' => 'utf-8'
            );
            $this->email->initialize($config);
            
            $this->email->from($store_details->smtp_user, $store_details->store_name);
            $this->email->to(get_current_user_email());
            $this->email->subject('PRO System - Test Email Notification');
            $this->email->message($test_message);
            
            if ($this->email->send()) {
                echo json_encode(array('success' => true, 'message' => 'Test email sent successfully'));
            } else {
                echo json_encode(array('success' => false, 'message' => 'Failed to send test email: ' . $this->email->print_debugger()));
            }
        } elseif ($notification_type === 'sms') {
            // Send test SMS
            $this->load->library('sms');
            $phone = get_current_user_phone();
            
            if ($phone) {
                $result = $this->sms->send($phone, $test_message);
                if ($result) {
                    echo json_encode(array('success' => true, 'message' => 'Test SMS sent successfully'));
                } else {
                    echo json_encode(array('success' => false, 'message' => 'Failed to send test SMS'));
                }
            } else {
                echo json_encode(array('success' => false, 'message' => 'No phone number found for current user'));
            }
        } else {
            echo json_encode(array('success' => false, 'message' => 'Invalid notification type'));
        }
    }
    
    public function get_approval_users() {
        if(!$this->permissions('pro_approval_users_view')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $this->db->select('au.*, u.username, u.first_name, u.last_name');
        $this->db->from('db_pro_approval_users au');
        $this->db->join('db_users u', 'au.user_id = u.id');
        $this->db->where('au.is_active', 1);
        $this->db->order_by('u.username', 'ASC');
        
        $query = $this->db->get();
        $approval_users = $query->result();
        
        echo json_encode(array('success' => true, 'data' => $approval_users));
    }
    
    public function add_approval_user() {
        if(!$this->permissions('pro_approval_users_add')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $user_id = $this->input->post('user_id');
        $min_amount = $this->input->post('min_amount');
        $max_amount = $this->input->post('max_amount');
        
        // Validate input
        if (empty($user_id) || $min_amount === '' || $max_amount === '') {
            echo json_encode(array('success' => false, 'message' => 'All fields are required'));
            return;
        }
        
        if ($min_amount < 0 || $max_amount < 0) {
            echo json_encode(array('success' => false, 'message' => 'Amounts cannot be negative'));
            return;
        }
        
        // Special case: both 0 means unlimited approval
        if ($min_amount == 0 && $max_amount == 0) {
            // This is unlimited approval - no further validation needed
        } else if ($min_amount > $max_amount && $max_amount != 0) {
            echo json_encode(array('success' => false, 'message' => 'Minimum amount cannot be greater than maximum amount'));
            return;
        }
        
        // Check if user already exists (including inactive ones)
        $existing = $this->db->get_where('db_pro_approval_users', array('user_id' => $user_id))->row();
        if ($existing) {
            if ($existing->is_active == 1) {
                echo json_encode(array('success' => false, 'message' => 'This user is already configured as an approval user'));
                return;
            } else {
                // User exists but is inactive, reactivate them with new settings
                $data = array(
                    'min_amount' => $min_amount,
                    'max_amount' => $max_amount,
                    'is_active' => 1,
                    'updated_date' => date('Y-m-d H:i:s'),
                    'updated_by' => get_current_user_id()
                );
                
                $result = $this->db->update('db_pro_approval_users', $data, array('user_id' => $user_id));
                
                if ($result) {
                    echo json_encode(array('success' => true, 'message' => 'Approval user reactivated successfully'));
                } else {
                    echo json_encode(array('success' => false, 'message' => 'Error reactivating approval user'));
                }
                return;
            }
        }
        
        // Insert new approval user
        $data = array(
            'user_id' => $user_id,
            'min_amount' => $min_amount,
            'max_amount' => $max_amount,
            'is_active' => 1,
            'created_by' => get_current_user_id()
        );
        
        $result = $this->db->insert('db_pro_approval_users', $data);
        
        if ($result) {
            echo json_encode(array('success' => true, 'message' => 'Approval user added successfully'));
        } else {
            echo json_encode(array('success' => false, 'message' => 'Error adding approval user'));
        }
    }
    
    public function remove_approval_user() {
        if(!$this->permissions('pro_approval_users_delete')){
            echo json_encode(array('success' => false, 'message' => 'Access denied'));
            return;
        }
        
        $approval_user_id = $this->input->post('user_id'); // This is actually the approval user record ID
        
        if (empty($approval_user_id)) {
            echo json_encode(array('success' => false, 'message' => 'Approval user ID is required'));
            return;
        }
        
        // Soft delete by setting is_active to 0
        $result = $this->db->update('db_pro_approval_users', 
            array('is_active' => 0, 'updated_by' => get_current_user_id()), 
            array('id' => $approval_user_id)
        );
        
        if ($result) {
            echo json_encode(array('success' => true, 'message' => 'Approval user removed successfully'));
        } else {
            echo json_encode(array('success' => false, 'message' => 'Error removing approval user'));
        }
    }
}
