<?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'];

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

    // Remove all the contacts of the current user from the 'contacts' table
    $querycont = $mysqli->prepare("DELETE FROM contacts WHERE user_id = ?");
    $querycont->bind_param("i", $userID);
    if ($querycont->execute()) { $messagedel = "success"; } else { $messagedel = "failure"; }

    // 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 = "success"; } else { $reindexmsg = "failure"; }

    $delresult = array('removeresult' => $messagedel, 'reindex' => $reindexmsg);

    echo json_encode($delresult);

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

?>