<?php

// if (isset($_GET['delete_status'])) {
    include 'dbconnect.php';
    date_default_timezone_set('Africa/Nairobi');
    $twentyFourHoursAgo = date('Y-m-d H:i:s', strtotime('-24 hours'));

    // Step 1: Select entries that have stayed for more than 24 hours
    $query = "SELECT * FROM status WHERE timestamp <= '$twentyFourHoursAgo'";
    $result = pg_query($db, $query);

    if ($result) {
        // Step 2: Retrieve image names from the result
        $imageNamesToDelete = [];
        while ($row = pg_fetch_assoc($result)) {
            $imageNamesToDelete[] = $row['img'];
        }
        // Step 3: Delete entries from the database
        $deleteQuery = "DELETE FROM status WHERE timestamp <= '$twentyFourHoursAgo'";
        $deleteResult = pg_query($db, $deleteQuery);
        if ($deleteResult) {
            // Step 4: Delete corresponding images from the "Images" directory
            foreach ($imageNamesToDelete as $imagePath) {
                if (file_exists(trim($imagePath))) {
                    unlink($imagePath);
                }
            }
            $response = [
                'success' => true,
                'message' => 'Old status records and corresponding images deleted successfully'
            ];
            echo json_encode($response);
        } else {
            $failed = [
                'success' => false,
                'message' => 'Database error'
            ];
            echo json_encode($failed);
        }
    } else {
        $failed = [
            'success' => false,
            'message' => 'Database error'
        ];
        echo json_encode($failed);
    }
// }
?>