<?php 

function delete_listing($id){

  $x = fetch_records("SELECT * FROM listings WHERE id = '{$id}' LIMIT 1");

  query("UPDATE users SET listings = listings - 1 WHERE id = '{$x['user_id']}' LIMIT 1");
  query("UPDATE categories SET listings = listings - 1 WHERE id = '{$x['category_id']}' LIMIT 1");

  $x['image'] != 'default.png' && file_exists(DIR.'images/listings/'.$x['image']) ? unlink(DIR.'images/listings/'.$x['image']) : null;

  query("DELETE FROM listings WHERE id = '{$id}' LIMIT 1");

}

function delete_category($id){

  $x = fetch_records("SELECT * FROM categories WHERE id = '{$id}' LIMIT 1");

  delete_records("SELECT id FROM listings WHERE category_id = '{$id}' ORDER BY id ASC", 'delete_listing', false);

  $x['image'] != 'default.png' ? unlink(DIR.'images/categories/'.$x['image']) : null;

  query("DELETE FROM categories WHERE id = '{$id}' LIMIT 1");

}

function delete_records($sql, $function){

  global $con;

  $q1 = mysqli_query($con, $sql);
  if(mysqli_num_rows($q1) > 0){

    while($f1 = mysqli_fetch_array($q1)){
      $function($f1['id']);
    }

  }

}

?>