<?php
include 'pagename.php';
include $session;
Session::checkSession_app();
include '../config.php';

header('Content-Type: application/json');

$filename = $_POST['filename'];
$user_id = $_POST['uid'];

if (!empty($filename)) {
    $delete_task_sql = "SELECT * FROM evp_email_list_metadata WHERE csv_file_name = '$filename' AND user_id = '$user_id'";
    $delete_task_read = $db->select($delete_task_sql);

    if ($delete_task_read && mysqli_num_rows($delete_task_read) > 0) {
        $task_delete = "DELETE FROM evp_email_list WHERE csv_file_name = '$filename' AND user_id = '$user_id'";
        $read_task_delete = $db->delete($task_delete);

        $meta_delete = "DELETE FROM evp_email_list_metadata WHERE csv_file_name = '$filename' AND user_id = '$user_id'";
        $read_meta_delete = $db->delete($meta_delete);

        $delete_task_sql = "SELECT * FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id'";
        $delete_task_read = $db->select($delete_task_sql);

        if ($delete_task_read && mysqli_num_rows($delete_task_read) > 0) {
            $task_delete = "DELETE FROM evp_task WHERE csv_name = '$filename' AND user_id = '$user_id'";
            $read_task_delete = $db->delete($task_delete);
        }

        echo json_encode(['csv_file_name' => $filename, 'success' => true, 'message' => 'File deleted successfully.']);
        exit;
    } else {
        echo json_encode(['csv_file_name' => $filename, 'success' => false, 'message' => 'File not found or already deleted.']);
        exit;
    }
}

echo json_encode(['success' => false, 'message' => 'Invalid request.']);
?>