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

class Agency_model extends CI_Model {

    public function __construct() {
        log_message('info', 'Agency_model initialized');
    }

    public function create_agencies_table() {
        // Check if table exists, if not create it
        if (!$this->db->table_exists('agencies')) {
            $this->db->query("
                CREATE TABLE agencies (
                    id INT(11) PRIMARY KEY AUTO_INCREMENT,
                    name VARCHAR(255) NOT NULL,
                    address TEXT,
                    contact_email VARCHAR(255),
                    contact_phone VARCHAR(20),
                    logo VARCHAR(500),
                    status ENUM('active', 'inactive') DEFAULT 'active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                )
            ");
        }
    }

    public function get_all_agencies() {
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('agencies')->result();
    }

    public function get_agency($id) {
        return $this->db->get_where('agencies', ['id' => $id])->row();
    }

    public function create_agency($data) {
        $this->db->insert('agencies', $data);
        return $this->db->insert_id();
    }

    public function update_agency($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('agencies', $data);
    }

    public function delete_agency($id) {
        $this->db->where('id', $id);
        return $this->db->delete('agencies');
    }
    public function search_agencies($search_term) {
    $this->db->like('name', $search_term);
    $this->db->or_like('contact_email', $search_term);
    $this->db->or_like('contact_phone', $search_term);
    $this->db->where('status', 'active');
    $this->db->limit(10);
    return $this->db->get('agencies')->result();
}

public function get_agencies_list() {
    $this->db->select('id, name');
    $this->db->where('status', 'active');
    $this->db->order_by('name', 'ASC');
    return $this->db->get('agencies')->result_array();
}

    public function get_agency_stats() {
        $stats = [
            'total_agencies' => $this->db->count_all('agencies'),
            'active_agencies' => $this->db->where('status', 'active')->count_all_results('agencies'),
            'agencies' => $this->get_all_agencies()
        ];
        return $stats;
    }
}
?>