<?php
// Start or resume the session
session_start();

/*
Used to enhance security by preventing browsers and proxies from caching pages.
When a user logs out of a web application, you wouldn't want the next person using the same device to simply press the back button in the browser
and access the previous user's session or sensitive information.
This is particularly important in scenarios like shared devices, where multiple users might use the same browser sequentially.
However, it's noted that this method does not work for iOS users, which is be due to iOS's handling of cache control headers and
its aggressive caching strategies to improve user experience and performance.
*/
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

// We verify that the user is logged in, if not we redirect the user to index.php the log in page.
if (!isset($_SESSION['username'])) {
  header("Location: index.php");
  exit;
}

require_once '/my_custom_url/PRIVATE/db_config.php';
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  die("Connection failure:" . $conn->connect_error);
}

// Retrieve data sent by AJAX
$BeginningActivityId = $_POST['Beginning_activity_id'];
$CeaseActivityId = $_POST['Cease_activity_id'];
$mytype = $conn->real_escape_string($_POST['type_stop']);
$my_mess = $conn->real_escape_string($_POST['my_mess']);
$my_initials = $conn->real_escape_string($_POST['my_initials']);

// Check the 'justified' value for the start of the activity
$checkSql = "SELECT justified FROM ACTIVITY WHERE id = ?";
$checkStmt = $conn->prepare($checkSql);
$checkStmt->bind_param("i", $BeginningActivityId);
$checkStmt->execute();
$result = $checkStmt->get_result();
$row = $result->fetch_assoc();
$checkStmt->close();

/*Here we manage a very important behavior of the application that guarantees us a true multi-user experience.
The goal is to prevent the creation of a new record in the STOPS table if it has already been created by another user. The risk is low but can occur.
Thus, to protect against this risk, we check that the 'justified' value is indeed equal to 0, which means that this record has never been included in a declaration of stops.
*/
if ($row && $row['justified'] == 0) { // The record was not created, proceed with updates and insertions

  // Update the ACTIVITY table for the specified records
    $updateSql = "UPDATE ACTIVITY SET justified = TRUE WHERE id IN (?, ?)";
    $stmt = $conn->prepare($updateSql);
    $stmt->bind_param("ii", $BeginningActivityId, $CeaseActivityId);
    $stmt->execute();
    $stmt->close();

    // Insert a record into STOPS
    $insertSql = "INSERT INTO STOPS (id_activ, id_activ2, type) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($insertSql);
    $stmt->bind_param("iis", $BeginningActivityId, $CeaseActivityId, $mytype);
    $stmt->execute();
    $stmt->close();

    // Insert a record into  MESSAGES
    $insertSql = "INSERT INTO MESSAGES (id_activ, content, initials) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($insertSql);
    $stmt->bind_param("iss", $BeginningActivityId, $my_mess, $my_initials);
    $stmt->execute();
    $stmt->close();

    // Check that the queries were executed correctly and return an appropriate message
    if ($conn->error) {
        echo "Error while saving the justification." . $conn->error;
    } else {
        echo "Justification successfully saved.";
    }

} else {
// The declaration of this stop has been made, the final user is notified.
    echo "Another user has already made the declaration for this stop";
}

$conn->close();
?>
