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

class Pro_settings_model extends CI_Model {
    
    public function __construct() {
        parent::__construct();
    }
    
    public function get_all_settings() {
        $this->db->select('*');
        $this->db->from('db_pro_settings');
        $this->db->where('is_active', 1);
        $this->db->order_by('setting_name', 'ASC');
        
        $query = $this->db->get();
        $settings = array();
        
        foreach ($query->result() as $row) {
            $settings[$row->setting_name] = array(
                'id' => $row->id,
                'setting_name' => $row->setting_name,
                'setting_value' => $row->setting_value,
                'setting_type' => $row->setting_type,
                'setting_description' => $row->setting_description,
                'is_active' => $row->is_active,
                'created_date' => $row->created_date,
                'updated_date' => $row->updated_date,
                'created_by' => $row->created_by,
                'updated_by' => $row->updated_by
            );
        }
        
        return $settings;
    }
    
    public function get_setting($setting_name) {
        $this->db->select('*');
        $this->db->from('db_pro_settings');
        $this->db->where('setting_name', $setting_name);
        $this->db->where('is_active', 1);
        
        $query = $this->db->get();
        return $query->row();
    }
    
    public function update_setting($setting_name, $setting_value, $setting_type = 'text', $description = null) {
        // Check if setting exists
        $existing = $this->get_setting($setting_name);
        
        if ($existing) {
            // Update existing setting
            $data = array(
                'setting_value' => $setting_value,
                'setting_type' => $setting_type,
                'setting_description' => $description,
                'updated_date' => date('Y-m-d H:i:s'),
                'updated_by' => get_current_user_id()
            );
            
            $this->db->where('setting_name', $setting_name);
            return $this->db->update('db_pro_settings', $data);
        } else {
            // Insert new setting
            $data = array(
                'setting_name' => $setting_name,
                'setting_value' => $setting_value,
                'setting_type' => $setting_type,
                'setting_description' => $description,
                'is_active' => 1,
                'created_by' => get_current_user_id()
            );
            
            return $this->db->insert('db_pro_settings', $data);
        }
    }
    
    public function delete_setting($setting_name) {
        $this->db->where('setting_name', $setting_name);
        return $this->db->update('db_pro_settings', array('is_active' => 0));
    }
    
    public function reset_to_default_settings() {
        $default_settings = array(
            'pro_auto_approve_amount' => array('value' => '1000.00', 'type' => 'decimal', 'description' => 'Amount below which requisitions are auto-approved (0 = disabled)'),
            'pro_require_approval_amount' => array('value' => '500.00', 'type' => 'decimal', 'description' => 'Amount above which requisitions require approval (0 = always require)'),
            'pro_max_requisition_amount' => array('value' => '10000.00', 'type' => 'decimal', 'description' => 'Maximum amount allowed for a single requisition (0 = no limit)'),
            'pro_sms_notifications' => array('value' => '0', 'type' => 'boolean', 'description' => 'Send SMS notifications for PRO status changes (1 = enabled, 0 = disabled)'),
            'pro_approval_workflow' => array('value' => 'single', 'type' => 'text', 'description' => 'Approval workflow type: single, multi_level, department_based'),
            'pro_auto_convert_approved' => array('value' => '0', 'type' => 'boolean', 'description' => 'Automatically convert approved requisitions to purchases (1 = enabled, 0 = disabled)'),
            'pro_require_supplier' => array('value' => '0', 'type' => 'boolean', 'description' => 'Require supplier selection for requisition items (1 = required, 0 = optional)'),
            'pro_allow_edit_after_submit' => array('value' => '0', 'type' => 'boolean', 'description' => 'Allow editing requisitions after submission (1 = allowed, 0 = not allowed)'),
            'pro_approval_timeout_days' => array('value' => '7', 'type' => 'number', 'description' => 'Days after which pending requisitions are considered expired (0 = no timeout)'),
            'pro_notification_recipients' => array('value' => '[]', 'type' => 'json', 'description' => 'JSON array of user IDs who should receive PRO notifications'),
            'pro_approval_workflow_enabled' => array('value' => '1', 'type' => 'boolean', 'description' => 'Enable approval workflow for purchase requisitions (1 = enabled, 0 = disabled)')
        );
        
        $success = true;
        
        foreach ($default_settings as $setting_name => $setting_data) {
            $result = $this->update_setting(
                $setting_name,
                $setting_data['value'],
                $setting_data['type'],
                $setting_data['description']
            );
            
            if (!$result) {
                $success = false;
                break;
            }
        }
        
        return $success;
    }
    
    public function get_settings_by_group($group_name) {
        // Group settings by category for better organization
        $groups = array(
            'approval' => array(
                'pro_auto_approve_amount',
                'pro_require_approval_amount',
                'pro_max_requisition_amount',
                'pro_approval_workflow',
                'pro_approval_timeout_days',
                'pro_approval_workflow_enabled'
            ),
            'notifications' => array(
                'pro_sms_notifications',
                'pro_notification_recipients'
            ),
            'workflow' => array(
                'pro_auto_convert_approved',
                'pro_require_supplier',
                'pro_allow_edit_after_submit'
            )
        );
        
        if (!isset($groups[$group_name])) {
            return array();
        }
        
        $settings = $this->get_all_settings();
        $group_settings = array();
        
        foreach ($groups[$group_name] as $setting_name) {
            if (isset($settings[$setting_name])) {
                $group_settings[$setting_name] = $settings[$setting_name];
            }
        }
        
        return $group_settings;
    }
    
    public function validate_setting_value($setting_name, $value) {
        $setting = $this->get_setting($setting_name);
        
        if (!$setting) {
            return false;
        }
        
        switch ($setting->setting_type) {
            case 'boolean':
                return in_array($value, array('0', '1', 0, 1, true, false));
            case 'number':
                return is_numeric($value) && is_int((int)$value);
            case 'decimal':
                return is_numeric($value);
            case 'json':
                return json_decode($value) !== null;
            default:
                return is_string($value);
        }
    }
    
    public function get_setting_history($setting_name) {
        $this->db->select('prs.*, u1.username as created_by_name, u2.username as updated_by_name');
        $this->db->from('db_pro_settings prs');
        $this->db->join('db_users u1', 'prs.created_by = u1.id', 'left');
        $this->db->join('db_users u2', 'prs.updated_by = u2.id', 'left');
        $this->db->where('prs.setting_name', $setting_name);
        $this->db->order_by('prs.updated_date', 'DESC');
        
        return $this->db->get()->result();
    }
}
