<?php
require_once 'connection.php';

date_default_timezone_set('Asia/Karachi');

// Calculate the current time minus 48 hours
$timeLimit = date("Y-m-d H:i:s", strtotime('-48 hours'));

// Print the calculated time limit for debugging purposes
echo "Time limit is: $timeLimit";

// Set MySQL time zone to match PHP's time zone
$conn->query("SET time_zone = '".date('P')."'");  // Automatically set MySQL time zone to match PHP

// Create queries to delete chats and group messages where the timestamp is older than 48 hours
$delete_chat_sql = "DELETE FROM chat WHERE timestamp < '$timeLimit'";
$delete_groupmessage_sql = "DELETE FROM groupmessagetable WHERE timestamp < '$timeLimit'";

// Execute the delete query for `chat` table
$chat_deleted = $conn->query($delete_chat_sql);

// Execute the delete query for `groupmessagetable`
$group_deleted = $conn->query($delete_groupmessage_sql);

if ($chat_deleted === TRUE && $group_deleted === TRUE) {
    if ($conn->affected_rows > 0) {
        // Success response
        echo json_encode(array('status' => 'success', 'message' => 'Chats and group messages older than 48 hours deleted successfully.'));
    } else {
        // No records found to delete
        echo json_encode(array('status' => 'success', 'message' => 'No chats or group messages found that are older than 48 hours.'));
    }
} else {
    // Error handling
    echo json_encode(array('status' => 'error', 'message' => 'Error deleting chats or group messages: ' . $conn->error));
}

$conn->close();
?>
