<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }

switch ($_REQUEST['fcn']){
    default:break;
case "updateAssignment":
    $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `assignment_type`=? WHERE `id`=? AND `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param("sii", $_REQUEST['assignment'], $_REQUEST['id'], $_REQUEST['clientnumber']);
    $success = $stmt->execute();
    $stmt->close();
    echo $success ? "1" : "0";
    exit();
break;
    case "add":
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `address_book` WHERE `clientnumber`=? AND `firstName`=? AND `lastName`=? AND `email`=? ")or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('isss',$_REQUEST['clientnumber'],$_REQUEST['firstName'],$_REQUEST['lastName'],$_REQUEST['email']);
        $stmt->execute();$cr=$stmt->get_result();$stmt->close();
        $count=mysqli_num_rows($cr);

        $stmt2 = $GLOBALS['con']->prepare("SELECT `indexer` FROM `address_book` WHERE `clientnumber`='".$_REQUEST['clientnumber']."' ORDER BY ABS(indexer) DESC LIMIT 1")or die(mysqli_error($GLOBALS['con']));

        $stmt2->execute();$cr2=$stmt2->get_result();$stmt2->close();
        $c2=mysqli_fetch_array($cr2);
        $index=($c2['indexer']+1);

        if($count<1){
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES (NULL,'client',?,?,?,?,?,?,?,0,'".$index."', 'all')")or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('issssss',$_REQUEST['clientnumber'],getClientName($_REQUEST['clientnumber']),$_REQUEST['firstName'],$_REQUEST['lastName'],$_REQUEST['phone1'],$_REQUEST['phone2'],$_REQUEST['email']);$stmt->execute();$cr=$stmt->get_result();
        $id=mysqli_insert_id($GLOBALS['con']);
        $stmt->close();

        $select = '<select class="form-select form-select-sm" onchange="updateAssignment(this, '.$cd['id'].')">';
        $select .= '<option value="all"'.($cd['assignment_type'] == 'all' ? ' selected' : '').'>All</option>';
        $select .= '<option value="billing"'.($cd['assignment_type'] == 'billing' ? ' selected' : '').'>Billing</option>';
        $select .= '<option value="renewal"'.($cd['assignment_type'] == 'renewal' ? ' selected' : '').'>Renewal</option>';
        $select .= '<option value="delivery"'.($cd['assignment_type'] == 'delivery' ? ' selected' : '').'>Delivery</option>';
        $select .= '</select>';

        $tdata='<tr id="R'.$id.'" class="table-success">
        <td><input id="FN'.$id.'" name="firstName_'.$id.'" class="form-control" type="text" value="'.$_REQUEST['firstName'].'" ></td>
        <td><input id="LN_'.$id.'" name="lastName_'.$id.'" class="form-control" type="text" value="'.$_REQUEST['lastName'].'" ></td>
        <td><input id="P_'.$id.'" name="phone1_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['phone1'].'" ></td>
        <td><input id="M_'.$id.'" name="phone2_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['phone2'].'" ></td>
        <td><input id="E_'.$id.'" name="email_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['email'].'" ></td>
        <td class="text-center align-middle">
  <input id="V_'.$id.'" name="auto_'.$id.'" type="checkbox"
         class="form-check-input m-0 mx-auto d-block"
         onclick="checker(\''.$id.'\')" '.$auto.'>
</td>
        ';
        $tdata .= '<td>'.$select.'</td>';
        $tdata .= '<td> <button data-id="'.$id.'" id="remove" class="btn btn-secondary"><i class="fad fa-trash"></i></button></td>
        </tr>';
echo "1|".$tdata."|".$id;
}
else {echo "0";}
exit();
break;

case "addImport":
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `address_book` WHERE `clientnumber`=? AND `firstName`=? AND `lastName`=? AND `email`=? ")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('isss',$_REQUEST['clientnumber'],$_REQUEST['firstName'],$_REQUEST['lastName'],$_REQUEST['email']);
$stmt->execute();$cr=$stmt->get_result();$stmt->close();
$count=mysqli_num_rows($cr);

$stmt2 = $GLOBALS['con']->prepare("SELECT `indexer` FROM `address_book` WHERE `clientnumber`='".$_REQUEST['clientnumber']."' ORDER BY ABS(indexer) DESC LIMIT 1")or die(mysqli_error($GLOBALS['con']));

$stmt2->execute();$cr2=$stmt2->get_result();$stmt2->close();
$c2=mysqli_fetch_array($cr2);
$index=($c2['indexer']+1);

if($count<1){
     $stmt=$GLOBALS['con']->prepare("INSERT INTO `address_book` VALUES (NULL,'".$_REQUEST['type']."',?,?,?,?,?,?,?,'','".$index."','all')")or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('issssss',$_REQUEST['clientnumber'],getClientName($_REQUEST['clientnumber']),$_REQUEST['firstName'],$_REQUEST['lastName'],$_REQUEST['phone1'],$_REQUEST['phone2'],$_REQUEST['email']);$stmt->execute();$cr=$stmt->get_result();
    $id=mysqli_insert_id($GLOBALS['con']);
    $stmt->close();

    $tdata='<tr id="R'.$id.'" class="table-success">
        <td><input id="FN'.$id.'" name="firstName_'.$id.'" class="form-control" type="text" value="'.$_REQUEST['firstName'].'"></td>
        <td><input id="LN_'.$id.'" name="lastName_'.$id.'" class="form-control" type="text" value="'.$_REQUEST['lastName'].'"></td>
        <td><input id="P_'.$id.'" name="phone1_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['phone1'].'"></td>
        <td><input id="M_'.$id.'" name="phone2_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['phone2'].'"></td>
        <td><input id="E_'.$id.'" name="email_'.$id.'" type="text" class="form-control" value="'.$_REQUEST['email'].'"></td>
        <td><input id="V_'.$id.'" name="auto_'.$id.'" type="checkbox" class="form-control" onclick="checker(\''.$id.'\')" '.$auto.'></td>
        <td> <button data-id="'.$id.'" id="remove" class="btn btn-secondary"><i class="fad fa-trash"></i></button></td>
    </tr>';
    echo "1|".$tdata."|".$id;
    }
    else {echo "0";}
    exit();
    break;

    case "update":
    $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET
    `firstName`='".$_REQUEST['firstName']."',
    `lastName`='".$_REQUEST['lastName']."',
    `phone1`='".$_REQUEST['phone1']."',
    `phone2`='".$_REQUEST['phone2']."',
    `email`='".$_REQUEST['email']."'
    WHERE `id`='".$_REQUEST['id']."'
    ")or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();$cr=$stmt->get_result();
    $stmt->close();
    echo "1";
    exit();
    break;

    case "remove":
    $stmt = $GLOBALS['con']->prepare("DELETE FROM `address_book` WHERE `id`=? ")or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i',$_REQUEST['id']);
    $stmt->execute();$cr=$stmt->get_result();$stmt->close();
    echo "1";
    exit();
    break;

    case "check":
    $stmt = $GLOBALS['con']->prepare("UPDATE `address_book` SET `auto`=? WHERE `id`=? ")or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii',$_REQUEST['set'],$_REQUEST['id']);
    $stmt->execute();$cr=$stmt->get_result();$stmt->close();
    echo "1";
    exit();
    break;

    case "import":
    $top=mysqli_query($GLOBALS['con'],"SELECT * FROM `clientdetails` WHERE `clientnumber`='".$_REQUEST['clientnumber']."'")or die($e=mysqli_error($GLOBALS['con']));
    $info=mysqli_fetch_array($top);
    switch($_REQUEST['type']){
    default:break;
    case "client":
    $recall=mysqli_query($GLOBALS['con'],"SELECT * FROM `clientdetails` WHERE `clientnumber`='".$_REQUEST['clientnumber']."'")or die($e=mysqli_error($GLOBALS['con'])); break;
    case "agent":
    $recall=mysqli_query($GLOBALS['con'],"SELECT * FROM `agents` WHERE `agent_number`='".$info['agent_number']."'")or die($e=mysqli_error($GLOBALS['con']));
    break;
    case "broker":$type="brokers";
    $recall=mysqli_query($GLOBALS['con'],"SELECT * FROM `brokers` WHERE `broker_number`='".$info['broker_number']."'")or die($e=mysqli_error($GLOBALS['con']));
    break;
    }

    echo $e;
    ?>
<div class="row">
    <div class="col-12">Select the <?= $_REQUEST['type']?> you wish to import into your address book.</div>
</div>
<div class="row">
    <div class="col-12">
        <table class="table table-sm table-striped">
            <thead>
                <tr>
                    <th><?= $_REQUEST['type']?> Name</th>
                    <th>Contact Type</th>
                    <th>Phone</th>
                    <th>Email</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php while($data=mysqli_fetch_array($recall)){
             switch($_REQUEST['type']){
                default:break;
                case "client":
                if($data['email']!=""){
                    $name=$data['clientname']; $type="Main"; $email=$data['email']; $phone=$data['phone1'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                if($data['pri_contact_email']!=""){
                    $name=$data['pri_contact_name']; $type="Primary"; $email=$data['pri_contact_email']; $phone=$data['pri_contact_tel'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                if($data['sec_contact_email']!=""){
                    $name=$data['sec_contact_name']; $type="Secondary"; $email=$data['sec_contact_email']; $phone=$data['sec_contact_tel'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                if($data['billing_email']!=""){
                    $name=$data['billing_name']; $type="Billing"; $email=$data['billing_email']; $phone=$data['billing_phone'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                    
                break;

                case "agent":
                if($data['email']!=""){
                    $name=$data['agent_name']; $type="Main"; $email=$data['email']; $phone=$data['tel'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                
                if($data['billing_email']!=""){
                    $name=$data['billing_name']; $type="Billing"; $email=$data['billing_email']; $phone=$data['billing_phone'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                    
                break;
                case "broker":
                if($data['email']!=""){
                    $name=$data['broker_name']; $type="Main"; $email=$data['email']; $phone=$data['tel'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                
                if($data['billing_email']!=""){
                    $name=$data['billing_name']; $type="Billing"; $email=$data['billing_email']; $phone=$data['billing_phone'];
                    $rowData.='
                    <tr>
                        <th>'.$name.'</th>
                        <th>'.$type.'</th>
                        <th>'.$phone.'</th>
                        <th>'.$email.'</th>
                        <th><a class="btn btn-sm btn-success m-0 px-3 py-2" onclick="addImport(\''.$name.'\',\'\',\''.$phone.'\',\'\',\''.$email.'\',\''.$_REQUEST['type'].'\')"><i class="fad fa-plus" style="--fa-secondary-opacity:1"></i></a></th>
                    </tr>
                    ';
                }
                    
                break;
                }
            
                echo $rowData;
    
        }?>
            </tbody>
        </table>
    </div>
</div>
<script>
function addImport(f, l, p1, p2, em, ty) {
    var table2 = parent.$('#table2');
    var tbody2 = table2.find('tbody');
    var person = {
        firstName: f,
        lastName: l,
        phone1: p1,
        phone2: p2,
        email: em,
        type: ty
    };
    var str = ''
    $.each(person, function(key, element) {
        str = str + key + '=' + element + '&';
    });
    str = str + 'clientnumber=<?= $_REQUEST['clientnumber']?>&';
    str = str + 'fcn=addImport&';
    str = str + 'tenant=' + TENANT_URL;
    $.post(ROOT_URL + '/includes/client/client_addressbook_functions.php?' + str, function(ret) {
        var rtn = ret.split('|')
        if (rtn[0] == 1) {

            tbody2.prepend(rtn[1])

            tbody2.load(ROOT_URL + '/includes/client/client_addressbook_data.php', {
                clientnumber: '<?= $_REQUEST['clientnumber']?>',
                tenant: TENANT_URL
            })
            killModal('addressBox')
        }
        if (rtn[0] == 0) {
            showResponse('danger', 'USER EXISTS IN THIS ADDRESS BOOK');

        }
    })

}
</script>
<?php 
        exit();
    break;
}
?>