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

class Staff_declaration_model extends App_Model
{
    private $t_decl;
    private $t_items;
    private $t_files;

    public function __construct()
    {
        parent::__construct();
        $this->t_decl  = db_prefix() . 'staff_declarations';
        $this->t_items = db_prefix() . 'staff_declaration_items';
        $this->t_files = db_prefix() . 'staff_declaration_files';
    }

    public function all_for_staff($staff_id, $can_view_all)
    {
        if (!$can_view_all) {
            $this->db->where('staff_id', (int)$staff_id);
        }
        $this->db->order_by('id', 'DESC');
        return $this->db->get($this->t_decl)->result_array();
    }

    public function create($header, $items)
    {
        $this->db->insert($this->t_decl, $header);
        $declaration_id = $this->db->insert_id();

        $sort = 1;
        foreach ($items as $row) {
            $row = array_merge($row, [
                'declaration_id' => $declaration_id,
                'sort_order'     => $sort++,
            ]);
            $this->db->insert($this->t_items, $row);
        }

        return $declaration_id;
    }

    public function add_file($declaration_id, $staff_id, $file)
    {
        $this->db->insert($this->t_files, [
            'declaration_id' => (int)$declaration_id,
            'staff_id'       => (int)$staff_id,
            'file_name'      => $file['file_name'],
            'original_name'  => $file['original_name'],
            'filetype'       => $file['filetype'],
            'filesize'       => $file['filesize'],
            'dateadded'      => date('Y-m-d H:i:s'),
        ]);
    }

    public function get($id)
    {
        $decl = $this->db->where('id', (int)$id)->get($this->t_decl)->row_array();
        if (!$decl) return null;

        $items = $this->db->where('declaration_id', (int)$id)
            ->order_by('sort_order', 'ASC')->get($this->t_items)->result_array();

        $files = $this->db->where('declaration_id', (int)$id)
            ->order_by('id', 'DESC')->get($this->t_files)->result_array();

        return ['decl' => $decl, 'items' => $items, 'files' => $files];
    }

public function add_audit($declaration_id, $staff_id, $action, $description = null)
{
    $this->db->insert(db_prefix() . 'staff_declaration_audit', [
        'declaration_id' => (int)$declaration_id,
        'staff_id'       => (int)$staff_id,
        'action'         => $action,
        'description'    => $description,
        'ip'             => $this->input->ip_address(),
        'user_agent'     => substr((string)$this->input->user_agent(), 0, 255),
        'dateadded'      => date('Y-m-d H:i:s'),
    ]);
    $admins = $this->staff_declaration_model->get_admin_user_ids();
$link   = 'staff_declaration/view/' . $declaration_id;

foreach ($admins as $toUserId) {

    $notif = [
        'touserid'    => $toUserId,
        'fromuserid'  => $staff_id,
        'description' => 'New Gift Declaration submitted (#' . $declaration_id . ')',
        'link'        => $link,
        // some installations support 'additional_data' => serialize([...])
    ];

    // Preferred: helper exists
    if (function_exists('add_notification')) {
        add_notification($notif);
    } else {
        // Fallback: common approach via misc_model (if exists in your build)
        if (!isset($this->misc_model)) {
            $this->load->model('misc_model');
        }
        if (method_exists($this->misc_model, 'add_notification')) {
            $this->misc_model->add_notification($notif);
        }
    }
}

}

public function get_audit($declaration_id)
{
    $this->db->where('declaration_id', (int)$declaration_id);
    $this->db->order_by('id', 'DESC');
    return $this->db->get(db_prefix() . 'staff_declaration_audit')->result_array();
}

/**
 * Notify Admins (simple, reliable)
 * tblstaff has "admin" column (1/0) in Perfex.
 */
public function get_admin_user_ids()
{
    $this->db->select('staffid');
    $this->db->where('admin', 1);
    $this->db->where('active', 1);
    $rows = $this->db->get(db_prefix() . 'staff')->result_array();

    return array_map(fn($r) => (int)$r['staffid'], $rows);
}
public function get_activity_logs($declaration_id, $limit = 50)
{
    $prefix = '[Staff Declaration #' . (int)$declaration_id . ']';

    $this->db->select('a.id, a.description, a.date, a.staffid, s.firstname, s.lastname');
    $this->db->from(db_prefix().'activity_log a');
    $this->db->join(db_prefix().'staff s', 's.staffid = a.staffid', 'left');
    $this->db->like('a.description', $prefix, 'after'); // only our module logs
    $this->db->order_by('a.date', 'DESC');
    $this->db->limit((int)$limit);

    return $this->db->get()->result_array();
}


public function update_declaration($id, $header, $items)
{
    $id = (int)$id;

    // Update header
    $this->db->where('id', $id)->update($this->t_decl, $header);

    // Replace items (dynamic rows)
    $this->db->where('declaration_id', $id)->delete($this->t_items);

    $sort = 1;
    foreach ($items as $row) {
        $row = array_merge($row, [
            'declaration_id' => $id,
            'sort_order'     => $sort++,
        ]);
        $this->db->insert($this->t_items, $row);
    }

    return $this->db->affected_rows() > 0;
}

public function delete_declaration($id)
{
    $id = (int)$id;

    // Get files first (to delete physical files)
    $files = $this->db->where('declaration_id', $id)->get($this->t_files)->result_array();

    // Delete children
    $this->db->where('declaration_id', $id)->delete($this->t_items);
    $this->db->where('declaration_id', $id)->delete($this->t_files);

    // Delete parent
    $this->db->where('id', $id)->delete($this->t_decl);

    return $files; // return files so controller can delete from disk + log
}

public function delete_file_row($declaration_id, $file_id)
{
    $row = $this->db->where('id', (int)$file_id)
        ->where('declaration_id', (int)$declaration_id)
        ->get($this->t_files)->row_array();

    if (!$row) return null;

    $this->db->where('id', (int)$file_id)->delete($this->t_files);
    return $row;
}
public function get_export_rows($ids = [], $staff_id = null, $can_view_all = false)
{
    $decl  = db_prefix() . 'staff_declarations';
    $items = db_prefix() . 'staff_declaration_items';

    $this->db->select("
        d.id AS declaration_id,
        d.staff_id,
        d.staff_name,
        d.staff_code,
        d.position,
        d.department,
        d.employee_signature,
        d.employee_date,
        d.created_at,
        d.updated_at,

        i.sort_order,
        i.date_received,
        i.category,
        i.description,
        i.estimated_value,
        i.gift_from,
        i.relationship,
        i.purpose,
        i.action_taken
    ", false);

    $this->db->from("$decl d");
    $this->db->join("$items i", "i.declaration_id = d.id", "left");

    if (!empty($ids)) {
        $this->db->where_in('d.id', array_map('intval', $ids));
    }

    if (!$can_view_all && $staff_id) {
        $this->db->where('d.staff_id', (int)$staff_id);
    }

    $this->db->order_by('d.id', 'DESC');
    $this->db->order_by('i.sort_order', 'ASC');

    return $this->db->get()->result_array();
}


public function notify_recipients($decl_id)
{
    $decl = $this->get((int)$decl_id);
    if (!$decl) return;

    $roleIds  = array_filter(array_map('intval', explode(',', (string)get_option('sd_notify_role_ids'))));
    $staffIds = array_filter(array_map('intval', explode(',', (string)get_option('sd_notify_staff_ids'))));

    // If nothing configured, fallback to admins (optional safety)
    $this->db->select('staffid,email,firstname,lastname');
    $this->db->from(db_prefix().'staff');
    $this->db->where('active', 1);

     // If role(s) selected, filter by roleid (Perfex staff has role)
    if (!empty($roleIds)) {
        $this->db->where_in('role', $roleIds); // some builds use `role`, others `roleid`
    }


    if (!empty($staffIds)) {
        if (!empty($roleIds)) {
            $this->db->or_where_in('staffid', $staffIds);
        } else {
            $this->db->where_in('staffid', $staffIds);
        }
    }

    // If still no filters set, notify admins (optional)
    if (empty($roleIds) && empty($staffIds)) {
        $this->db->where('admin', 1);
    }

    $recipients = $this->db->get()->result_array();
    if (empty($recipients)) return;

    $url = admin_url('staff_declaration/view/' . (int)$decl_id);

    foreach ($recipients as $u) {
        // In-app notification
        if (function_exists('add_notification')) {
            add_notification([
                'touserid'        => (int)$u['staffid'],
                'description'     => 'New Gift Disclosure submitted by ' . ($decl['staff_name'] ?? 'staff'),
                'link'            => $url,
                'additional_data' => serialize([(int)$decl_id]),
            ]);
        }

         //log_message('error', 'The variable was set correctly: ' . json_encode($decl));
        $this->send_email_to($u['email'], $decl, $url);
    }

    if (function_exists('pusher_trigger_notification')) {
        pusher_trigger_notification($recipients);
    }
}

private function send_email_to($toEmail, $decl, $url)
{
    if (empty($toEmail)) {
        return;
    }

    // ✅ Normalize (support both shapes: flat row OR {decl,items,files})
    $d     = (is_array($decl) && isset($decl['decl']) && is_array($decl['decl'])) ? $decl['decl'] : $decl;
    $items = (is_array($decl) && isset($decl['items']) && is_array($decl['items'])) ? $decl['items'] : [];

    $subject = 'New Gift Disclosure Submitted';

    // Staff ID fallback: staff_code -> staff_id
    $staffId = $d['staff_code'] ?? ($d['staff_id'] ?? '');

    // Optional: brief summary of first item
    $firstItemLine = '';
    if (!empty($items)) {
        $first = $items[0];
        $firstItemLine = '<p><strong>First item:</strong> '
            . htmlspecialchars(($first['description'] ?? '-'))
            . ' (RM ' . htmlspecialchars(($first['estimated_value'] ?? '-')) . ')</p>';
    }

    $message =
        '<p>A new Gift Disclosure Form has been submitted.</p>'
        . '<p>'
        . '<strong>Name:</strong> ' . htmlspecialchars($d['staff_name'] ?? '') . '<br>'
        . '<strong>Staff ID:</strong> ' . htmlspecialchars($staffId) . '<br>'
        . '<strong>Department:</strong> ' . htmlspecialchars($d['department'] ?? '') . '<br>'
        . '<strong>Date:</strong> ' . htmlspecialchars($d['employee_date'] ?? '') . '<br>'
        . '</p>'
        . $firstItemLine
        . '<p>View: <a href="' . $url . '">' . $url . '</a></p>';

    // Use Perfex mail helper if available
    if (function_exists('send_mail')) {
        @send_mail($toEmail, $subject, $message);
        return;
    }

    // CI Email fallback
    $CI = &get_instance();
    $CI->load->library('email');
    $CI->email->clear(true);
$fromEmail = 'humancapital@inceif.edu.my';
$fromName  = 'Human Capital INCEIF';
$CI->email->from($fromEmail, $fromName);
$CI->email->reply_to($fromEmail, $fromName);
    $CI->email->to($toEmail);
    $CI->email->subject($subject);
    $CI->email->message($message);
    @$CI->email->send();
}



}