<?php
/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

if (isset($_POST['s_ajax_call']) && ($_POST['s_ajax_call'] == $_SESSION['validate_s_access'])) {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $username = $_POST['username'];
    $contDataPosted = $_POST['contactsdata'];
    $contactsData = json_decode($contDataPosted, true);

    // Get the user id from the 'app_users' table
    $queryid = $mysqli->prepare("SELECT id, username FROM app_users WHERE BINARY username = ?");
    $queryid->bind_param("s", $username);
    $queryid->execute();
    $queryidres = $queryid->get_result()->fetch_assoc();
    $userID = $queryidres['id'];

    $restrictmsg = "";
    $insertcheck = 0;
    $duplicate = 0;

    for ($i = 0; $i < count($contactsData); $i++) {

         $contactName = $contactsData[$i][0];
         if (preg_match('/[^A-Za-z0-9\s\-\.\'\(\)]/', $contactName)) {
             $contactNamemsg = "The 'Display Name' field contains characters that are not allowed.";
         } else { $contactNamemsg = ""; }
         $restrictmsg .= $contactNamemsg . " ";

         $contactDesc = $contactsData[$i][1];
         if (preg_match('/[^A-Za-z0-9\s\-\_\.\,\'\"\(\)\!\?\@\%\&\*]/', $contactDesc)) {
             $contactDescmsg = "The 'Title / Description' field contains characters that are not allowed.";
         } else { $contactDescmsg = ""; }
         $restrictmsg .= $contactDescmsg . " ";

         $contactLongDesc = $contactsData[$i][2];
         if (preg_match('/[^A-Za-z0-9\s\-\_\.\,\'\"\(\)\!\?\@\%\&\*]/', $contactLongDesc)) {
             $contactLongDescmsg = "The 'Long Description' field contains characters that are not allowed.";
         } else { $contactLongDescmsg = ""; }
         $restrictmsg .= $contactLongDescmsg . " ";

         $addressStreet = $contactsData[$i][3];
         if (preg_match('/[^A-Za-z0-9\s\-\_\.\,\'\"\(\)\#\%\&]/', $addressStreet)) {
             $addressStreetmsg = "The 'Address - Street' field contains characters that are not allowed.";
         } else { $addressStreetmsg = ""; }
         $restrictmsg .= $addressStreetmsg . " ";

         $addressZip = $contactsData[$i][4];
         if (preg_match('/[^A-Za-z0-9\s\-\_\.\(\)\#\&]/', $addressZip)) {
             $addressZipmsg = "The 'Address - Zip' field contains characters that are not allowed.";
         } else { $addressZipmsg = ""; }
         $restrictmsg .= $addressZipmsg . " ";

         $addressTown = $contactsData[$i][5];
         if (preg_match('/[^A-Za-z0-9\s\-\_\.\,\(\)\&]/', $addressTown)) {
             $addressTownmsg = "The 'Address - Town' field contains characters that are not allowed.";
         } else { $addressTownmsg = ""; }
         $restrictmsg .= $addressTownmsg . " ";

         $addressCountry = $contactsData[$i][6];
         if (preg_match('/[^A-Za-z0-9\s\-\.\,\(\)\&]/', $addressCountry)) {
             $addressCountrymsg = "The 'Address - Country' field contains characters that are not allowed.";
         } else { $addressCountrymsg = ""; }
         $restrictmsg .= $addressCountrymsg . " ";

         $addressState = $contactsData[$i][7];
         if (preg_match('/[^A-Za-z0-9\s\-\.\,\(\)\&]/', $addressState)) {
             $addressStatemsg = "The 'Address - State/Province' field contains characters that are not allowed.";
         } else { $addressStatemsg = ""; }
         $restrictmsg .= $addressStatemsg . " ";

         $extensionNumber = $contactsData[$i][8];
         if (preg_match('/[^A-Za-z0-9\*\#]/', $extensionNumber)) {
             $extensionNumbermsg = "The 'Extension (Internal)' field contains characters that are not allowed.";
         } else { $extensionNumbermsg = ""; }
         $restrictmsg .= $extensionNumbermsg . " ";

         $contactMobile = $contactsData[$i][9];
         if (preg_match('/[^0-9\s\+\-\.\#]/', $contactMobile)) {
             $contactMobilemsg = "The 'Mobile Number' field contains characters that are not allowed.";
         } else { $contactMobilemsg = ""; }
         $restrictmsg .= $contactMobilemsg . " ";

         $contactNum1 = $contactsData[$i][10];
         if (preg_match('/[^0-9\s\+\-\.\#]/', $contactNum1)) {
             $contactNum1msg = "The 'Contact Number 1' field contains characters that are not allowed.";
         } else { $contactNum1msg = ""; }
         $restrictmsg .= $contactNum1msg . " ";

         $contactNum2 = $contactsData[$i][11];
         if (preg_match('/[^0-9\s\+\-\.\#]/', $contactNum2)) {
             $contactNum2msg = "The 'Contact Number 2' field contains characters that are not allowed.";
         } else { $contactNum2msg = ""; }
         $restrictmsg .= $contactNum2msg . " ";

         $contact_fax = $contactsData[$i][12];
         if (preg_match('/[^0-9\s\+\-\.\#]/', $contact_fax)) {
             $contact_faxmsg = "The 'Fax Number' field contains characters that are not allowed.";
         } else { $contact_faxmsg = ""; }
         $restrictmsg .= $contact_faxmsg . " ";

         $contact_email = $contactsData[$i][13];
         if (filter_var($contact_email, FILTER_VALIDATE_EMAIL) || $contact_email == '') {
             $contact_emailmsg = "";
         } else { $contact_emailmsg = "The email address in the 'Email' field is not valid."; }
         $restrictmsg .= $contact_emailmsg . " ";

         $profilePicture = $contactsData[$i][14];
         if (preg_match('/[^A-Za-z0-9\+\/\=\;\:\,]/', $profilePicture)) {
             $profilePicturemsg = "The 'Profile Picture' field contains characters that are not allowed.";
         } else { $profilePicturemsg = ""; }
         $restrictmsg .= $profilePicturemsg . " ";

         $groups = $contactsData[$i][15];
         if (preg_match('/[^A-Za-z0-9\s\-\|]/', $groups)) {
             $groupsmsg = "The 'Groups' field contains characters that are not allowed.";
         } else { $groupsmsg = ""; }
         $restrictmsg .= $groupsmsg . " ";

         $dateAdded = date("Y-m-d H:i:s");
         $dateModified = $dateAdded;

         if (ctype_space($restrictmsg)) {

             // Check if the contact is already in the 'contacts' table
             $queryck = $mysqli->prepare("SELECT id, user_id, contact_name FROM contacts WHERE user_id = ? AND contact_name = ?");
             $queryck->bind_param("is", $userID, $contactName);
             $queryck->execute();
             $fetchInfo = $queryck->get_result()->fetch_assoc();

             if (!$fetchInfo) {

                  $querync = $mysqli->prepare("INSERT INTO contacts (user_id, contact_name, contact_desc, contact_long_desc, address_street, address_zip, address_town, address_country, 
                                               address_state, extension_number, contact_mobile, contact_num1, contact_num2, contact_fax, contact_email, profile_picture_c, groups, 
                                               date_added, date_modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                  $querync->bind_param("issssssssssssssssss", $userID, $contactName, $contactDesc, $contactLongDesc, $addressStreet, $addressZip, $addressTown, $addressCountry, 
                                        $addressState, $extensionNumber, $contactMobile, $contactNum1, $contactNum2, $contact_fax, $contact_email, $profilePicture, $groups, $dateAdded, 
                                        $dateModified);

	          if ($querync->execute()) { /* OK */ } else { $insertcheck++; }

             } else { $duplicate++; }

         } else { break; }

    }

    // Reindex the 'contacts' table
    $reindexset = $mysqli->prepare("SET @resetrec = 0");
    $reindexup = $mysqli->prepare("UPDATE contacts SET id = @resetrec := @resetrec + 1");
    $reindexalt = $mysqli->prepare("ALTER TABLE contacts auto_increment = 1");
    if ($reindexset->execute() && $reindexup->execute() && $reindexalt->execute()) { $reindexmsg = ""; } else { $reindexmsg = "The 'contacts' table couldn't be reindexed!"; }

    if (ctype_space($restrictmsg)) { $restrictmsgproc = ""; } else { $restrictmsgproc = $restrictmsg; }

    if ($insertcheck == 0) { $insertmsg = ""; } else { $insertmsg = "At least one error while trying to insert contacts into the database!"; }

    if ($duplicate == 0) { $duplicatemsg = ""; } else { $duplicatemsg = "Some of the contacts that you have tried to import were already in the database."; }

    $response = array('restrict' => $restrictmsgproc, 'reindex' => $reindexmsg, 'insert' => $insertmsg, 'duplicate' => $duplicatemsg);

    echo json_encode($response);

} else {
    header("Location: ../login.php");
}

?>
