<?php
session_start();

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

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

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

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

/* Check Employee Exists */

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

if (mysqli_num_rows($employee) == 0) {
    header("Location: index.php");
    exit;
}

/* Check Appointment Dependency */

$appointment = mysqli_query($conn, "
    SELECT id
    FROM appointments
    WHERE employee_id='$id'
    LIMIT 1
");

if (mysqli_num_rows($appointment) > 0) {

    header("Location: index.php?error=appointment_exists");
    exit;

}

/* Delete */

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

if ($delete) {

    header("Location: index.php?msg=deleted");
    exit;

} else {

    header("Location: index.php?error=delete_failed");
    exit;

}