<?php
session_start();
require_once "config.php";

// Function to sanitize input using mysqli_real_escape_string
function sanitizeInput($conn, $input) {
    return mysqli_real_escape_string($conn, htmlspecialchars(strip_tags(trim($input))));
}

// Print POST data for debugging
// print_r($_POST); die;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_GET['action'])) {
        $action = $_GET['action'];

        if ($action == 'add') {
            $department_name = sanitizeInput($conn, $_POST['department_name']);
            $description = sanitizeInput($conn, $_POST['description']);

            $sql = "INSERT INTO departments (department_name, description) VALUES (?, ?)";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "ss", $department_name, $description);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    header("Location: add-department.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        }

        if ($action == 'edit') {
            $edit_name = sanitizeInput($conn, $_POST['edit_department_name']);
            $edit_id = $_POST['edit_id'];

            $sql = "UPDATE departments SET department_name = ? WHERE department_id = ?";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "si", $edit_name, $edit_id);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    header("Location: add-department.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        }

        if ($action == 'delete' && isset($_POST['delete_id'])) {
            $delete_id = $_POST['delete_id'];

            $sql = "DELETE FROM departments WHERE department_id = ?";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "i", $delete_id);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    header("Location: add-department.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        }
    }
}

mysqli_close($conn);
?>
