<?php
/**
 *  Copyright (C) 2022, 2024  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();

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

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $username = $_POST['username'];
    $contactName = $_POST['contact_name'];
    $contactDesc = $_POST['contact_desc'];
    $contactLongDesc = $_POST['contact_long_desc'];
    $addressStreet = $_POST['address_street'];
    $addressZip = $_POST['address_zip'];
    $addressTown = $_POST['address_town'];
    $addressCountry = $_POST['address_country'];
    $addressState = $_POST['address_state'];
    $extensionNumber = $_POST['extension_number'];
    $contactMobile = $_POST['contact_mobile'];
    $contactNum1 = $_POST['contact_num1'];
    $contactNum2 = $_POST['contact_num2'];
    $contact_fax = $_POST['contact_fax'];
    $contact_email = $_POST['contact_email'];
    $groups = $_POST['groups'];
    $dateAdded = $_POST['date_added'];
    $dateModified = $_POST['date_modified'];

    // Get the id of the user for which we want to insert the contact data
    $query1 = $mysqli->prepare("SELECT id, username FROM app_users WHERE BINARY username = ?");
    $query1->bind_param("s", $username);
    $query1->execute(); 
    $queryres = $query1->get_result()->fetch_assoc();
    $userID = $queryres['id'];

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

    if (!$fetchInfo) {

         $query3 = $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, groups, date_added, date_modified) 
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
         $query3->bind_param("isssssssssssssssss", $userID, $contactName, $contactDesc, $contactLongDesc, $addressStreet, $addressZip, $addressTown, $addressCountry, $addressState, 
                              $extensionNumber, $contactMobile, $contactNum1, $contactNum2, $contact_fax, $contact_email, $groups, $dateAdded, $dateModified);

	 if ($query3->execute()) {
	     $messagetosend1 = 'success';
	 } else { $messagetosend1 = 'An error occurred while attempting to save the contact to the database!'; }

	 // 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()) { $messagetosend2 = 'success'; } else { $messagetosend2 = 'failure'; }

         if ($messagetosend1 == 'success' && $messagetosend2 == 'success') { $messagetosend = 'success'; } else { $messagetosend = 'Error while saving the data'; }

    } else { $messagetosend = 'Error! A contact with the same name is already in the database!'; }

    $response = array('result' => $messagetosend);
    echo json_encode($response);

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

?>
