<?php
include "stuff.php";
$con = mysqli_connect($server,$user,$password,$db);
$table = $_GET["table"];
$id = $_GET["id"];
if($table == "estate"){
  $res = mysqli_query($con,"SELECT id FROM models WHERE estate = {$id}");
  while($row = mysqli_fetch_array($res))delmodel($con,$row['id']);
  mysqli_query($con,"DELETE FROM estates WHERE id = {$id}");
  mysqli_query($con,"UPDATE users SET latest_estate = 0 WHERE latest_estate = {$id}");
}else if($table == "model"){
  delmodel($con,$id);
}
header("location: ../index.php");

function delmodel($con,$id){
  $res = mysqli_query($con,"SELECT models.tarball,results.id FROM results INNER JOIN models ON results.model = models.id WHERE models.id = {$id}");
  while($row = mysqli_fetch_array($res)){
    $tarball    = "../Models/".$row[0];
    $image_mask = "../Images/model{$id}.*";
    $results    = "../Results/".$row[1];
    if(file_exists($tarball))unlink($tarball);
    foreach(glob($image_mask) as $filename){
      if(file_exists($filename))unlink($filename);
    }
    if(file_exists($results))rrmdir($results);
  }
  mysqli_query($con,"DELETE FROM results WHERE model = {$id}");
  mysqli_query($con,"DELETE FROM models WHERE id = {$id}");
  mysqli_query($con,"UPDATE users SET latest_model = 0 WHERE latest_model = {$id}");
}

// remove all files from a folder and then delete the folder
function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir"){
            rrmdir($dir."/".$object);
         }else{
            unlink($dir."/".$object);
         }
       }
     }
     reset($objects);
     rmdir($dir);
  }
}
?>
