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

$lockAfterConvert = get_option('lead_lock_after_convert_to_customer');
$this->ci->load->model('leads_model');
$statuses = $this->ci->leads_model->get_status();

$aColumns = [
    db_prefix() . 'leads.id as leadId',
    db_prefix() . 'leads.name as leadName',
    db_prefix() . 'leads.email as leadEmail',
    db_prefix() . 'leads.phonenumber as leadPhoneNumber',
    db_prefix() . 'leads.dateadded as leadDateAdded',
    db_prefix() . 'leads_status.name as status_name',
    db_prefix() . 'leads_sources.name as source_name',
    db_prefix() . 'leads.lastcontact as leadLastContact'
];

$sIndexColumn = 'id';
$sTable = db_prefix() . 'leads';
$join = [
    'JOIN ' . db_prefix() . 'propertybase_properties_leads ON ' . db_prefix() . 'propertybase_properties_leads.lead_id = ' . db_prefix() . 'leads.id',

    'LEFT JOIN ' . db_prefix() . 'leads_status ON ' . db_prefix() . 'leads_status.id = ' . db_prefix() . 'leads.status',
    'JOIN ' . db_prefix() . 'leads_sources ON ' . db_prefix() . 'leads_sources.id = ' . db_prefix() . 'leads.source',
];
$where = [];

array_push($where, 'AND ' . db_prefix() . 'propertybase_properties_leads.property_id = ' . $property_id);


$additionalColumns = hooks()->apply_filters('leads_table_additional_columns_sql', [
    'junk',
    'lost',
    'color',
    'status',
    'assigned',
    db_prefix() . 'leads.addedfrom as addedfrom',
    '(SELECT count(leadid) FROM ' . db_prefix() . 'clients WHERE ' . db_prefix() . 'clients.leadid=' . db_prefix() . 'leads.id) as is_converted',
]);

$result = data_tables_init($aColumns, $sIndexColumn, $sTable, $join, $where, $additionalColumns);

$output = $result['output'];
$rResult = $result['rResult'];


foreach ($rResult as $aRow) {
    $row = [];
    for ($i = 0; $i < count($aColumns); $i++) {

        $CI = &get_instance();
        $CI->load->model('propertybase_model');

        $hrefAttr = 'href="' . admin_url('leads/index/' . $aRow['leadId']) . '" onclick="init_lead(' . $aRow['leadId'] . ');return false;"';

        $locked = false;

        if ($aRow['is_converted'] > 0) {
            $locked = ((!is_admin() && $lockAfterConvert == 1) ? true : false);
        }

        $row[] = '<a ' . $hrefAttr . '>' . $aRow['leadId'] . '</a>';
        $row[] = '<a ' . $hrefAttr . '>' . $aRow['leadName'] . '</a>';

        $row[] = ($aRow['leadEmail'] != '' ? '<a href="mailto:' . $aRow['leadEmail'] . '">' . $aRow['leadEmail'] . '</a>' : '');

        $row[] = ($aRow['leadPhoneNumber'] != '' ? '<a href="tel:' . $aRow['leadPhoneNumber'] . '">' . $aRow['leadPhoneNumber'] . '</a>' : '');

        if (!empty($aRow['assigned'])) {
            $row[] = '<a href="' . admin_url('staff/profile/' . $aRow['assigned']) . '">' . staff_profile_image($aRow['assigned'], [
                    'staff-profile-image-small',
                ]) . '</a>';
        } else {
            $row[] = '';
        }

        if ($aRow['status_name'] == null) {
            if ($aRow['lost'] == 1) {
                $outputStatus = '<span class="label label-danger">' . _l('lead_lost') . '</span>';
            } elseif ($aRow['junk'] == 1) {
                $outputStatus = '<span class="label label-warning">' . _l('lead_junk') . '</span>';
            }
        } else {
            $outputStatus = '<span class="lead-status-' . $aRow['status'] . ' label' . (empty($aRow['color']) ? ' label-default' : '') . '" style="color:' . $aRow['color'] . ';border:1px solid ' . adjust_hex_brightness($aRow['color'], 0.4) . ';background: ' . adjust_hex_brightness($aRow['color'], 0.04) . ';">' . $aRow['status_name'];

            if (!$locked) {
                $statusCss = "font-size:14px;vertical-align:middle;";
                $outputStatus .= '<div class="dropdown inline-block mleft5 table-export-exclude">';
                $outputStatus .= '<a href="#" style="'.$statusCss.'" class="dropdown-toggle text-dark" id="tableLeadsStatus-' . $aRow['leadId'] . '" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
                $outputStatus .= '<span data-toggle="tooltip" title="' . _l('ticket_single_change_status') . '"><i class="fa-solid fa-chevron-down tw-opacity-70"></i></span>';
                $outputStatus .= '</a>';

                $outputStatus .= '<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="tableLeadsStatus-' . $aRow['leadId'] . '">';
                foreach ($statuses as $leadChangeStatus) {
                    if ($aRow['status'] != $leadChangeStatus['id']) {
                        $outputStatus .= '<li>
                  <a href="#" onclick="lead_mark_as(' . $leadChangeStatus['id'] . ',' . $aRow['leadId'] . '); return false;">
                     ' . $leadChangeStatus['name'] . '
                  </a>
               </li>';
                    }
                }
                $outputStatus .= '</ul>';
                $outputStatus .= '</div>';
            }
            $outputStatus .= '</span>';
        }

        $row[] = $outputStatus;

        $row[] = $aRow['source_name'];

        $row[] = ($aRow['leadLastContact'] == '0000-00-00 00:00:00' || !is_date($aRow['leadLastContact']) ? '' : '<span data-toggle="tooltip" data-title="' . _dt($aRow['leadLastContact']) . '" class="text-has-action is-date">' . time_ago($aRow['leadLastContact']) . '</span>');

        $row[] = '<span data-toggle="tooltip" data-title="' . _dt($aRow['leadDateAdded']) . '" class="text-has-action is-date">' . time_ago($aRow['leadDateAdded']) . '</span>';

    }

    $output['aaData'][] = $row;
}
