<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /beauty_pos/login.php");
    exit;
}

include_once __DIR__ . "/../config/database.php";

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: /beauty_pos/suppliers/index.php");
    exit;
}

$id = (int)$_GET['id'];

$check = mysqli_query(
    $conn,
    "SELECT id
     FROM suppliers
     WHERE id='$id'
     LIMIT 1"
);

if (mysqli_num_rows($check) == 0) {

    header("Location: /beauty_pos/suppliers/index.php?error=delete");
    exit;

}

/*
|--------------------------------------------------------------------------
| Future Safe Check
|--------------------------------------------------------------------------
| When purchase_orders table gets supplier_id relation,
| add validation here before delete.
|
| Example:
|
| $purchaseCheck = mysqli_query(
|     $conn,
|     "SELECT id FROM purchase_orders
|      WHERE supplier_id='$id'
|      LIMIT 1"
| );
|
| if(mysqli_num_rows($purchaseCheck)>0){
|     header("Location: /beauty_pos/suppliers/index.php?error=delete");
|     exit;
| }
|--------------------------------------------------------------------------
*/

$delete = mysqli_query(
    $conn,
    "DELETE FROM suppliers
     WHERE id='$id'"
);

if ($delete) {

    header("Location: /beauty_pos/suppliers/index.php?success=deleted");
    exit;

} else {

    header("Location: /beauty_pos/suppliers/index.php?error=delete");
    exit;

}