<?php
// departments_script.php
require '../config.php';
session_start();
session_write_close();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
if (!in_array($userRole, ['admin', 'superadmin'])) {
    die("Access Denied");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // =====================================================
    // TRANSACTION: CREATE OPERATION MAPPINGS
    // =====================================================
    if ($action === 'create') {
        $type = $_POST['type'] ?? '';
        $name = trim($_POST['name'] ?? '');
        $code = trim($_POST['code'] ?? '');
        if ($code === '') $code = null;

        if (empty($name)) {
            header("Location: departments.php?error=empty_fields");
            exit;
        }

        if ($type === 'department') {
            $stmt = $conn->prepare("INSERT INTO departments (name, code) VALUES (?, ?)");
            $stmt->bind_param("ss", $name, $code);
        } elseif ($type === 'position') {
            $stmt = $conn->prepare("INSERT INTO positions (name, code) VALUES (?, ?)");
            $stmt->bind_param("ss", $name, $code);
        } elseif ($type === 'designation') {
            $stmt = $conn->prepare("INSERT INTO designations (name, code) VALUES (?, ?)");
            $stmt->bind_param("ss", $name, $code);
        } else {
            die("Invalid operational entity structure.");
        }

        if ($stmt->execute()) {
            header("Location: departments.php?saved=1&tab=" . urlencode($type));
        } else {
            header("Location: departments.php?error=db_write_error&tab=" . urlencode($type));
        }
        $stmt->close();
        exit;
    }

    // =====================================================
    // TRANSACTION: UPDATE OPERATION MAPPINGS
    // =====================================================
    if ($action === 'update') {
        $type = $_POST['type'] ?? '';
        $id   = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $code = trim($_POST['code'] ?? '');
        if ($code === '') $code = null;

        if ($id <= 0 || empty($name)) {
            header("Location: departments.php?error=invalid_mutation");
            exit;
        }

        if ($type === 'department') {
            $stmt = $conn->prepare("UPDATE departments SET name = ?, code = ? WHERE id = ?");
        } elseif ($type === 'position') {
            $stmt = $conn->prepare("UPDATE positions SET name = ?, code = ? WHERE id = ?");
        } elseif ($type === 'designation') {
            $stmt = $conn->prepare("UPDATE designations SET name = ?, code = ? WHERE id = ?");
        } else {
            die("Invalid operational entity structure.");
        }

        $stmt->bind_param("ssi", $name, $code, $id);
        if ($stmt->execute()) {
            header("Location: departments.php?updated=1&tab=" . urlencode($type));
        } else {
            header("Location: departments.php?error=db_write_error&tab=" . urlencode($type));
        }
        $stmt->close();
        exit;
    }

    // =====================================================
    // TRANSACTION: DELETE OPERATION MAPPINGS
    // =====================================================
    if ($action === 'delete') {
        $type = $_POST['type'] ?? '';
        $id   = intval($_POST['id'] ?? 0);

        if ($id <= 0) {
            header("Location: departments.php?error=invalid_reference");
            exit;
        }

        // Integrity Constraints Verification Latch
        if ($type === 'department') {
            $checkStmt = $conn->prepare("SELECT COUNT(*) FROM employees WHERE department_id = ?");
            $checkStmt->bind_param("i", $id);
            $checkStmt->execute();
            $checkStmt->bind_result($count);
            $checkStmt->fetch();
            $checkStmt->close();

            if ($count > 0) {
                header("Location: departments.php?error=in_use&type=department");
                exit;
            }

            $stmt = $conn->prepare("DELETE FROM departments WHERE id = ?");
        } 
        elseif ($type === 'position') {
            // Check if position name is still associated with any active employee profile strings
            $getPos = $conn->prepare("SELECT name FROM positions WHERE id = ?");
            $getPos->bind_param("i", $id);
            $getPos->execute();
            $getPos->bind_result($pName);
            $getPos->fetch();
            $getPos->close();

            $checkStmt = $conn->prepare("SELECT COUNT(*) FROM employees WHERE position = ?");
            $checkStmt->bind_param("s", $pName);
            $checkStmt->execute();
            $checkStmt->bind_result($count);
            $checkStmt->fetch();
            $checkStmt->close();

            if ($count > 0) {
                header("Location: departments.php?error=in_use&type=position");
                exit;
            }

            $stmt = $conn->prepare("DELETE FROM positions WHERE id = ?");
        } 
        elseif ($type === 'designation') {
            $getDes = $conn->prepare("SELECT name FROM designations WHERE id = ?");
            $getDes->bind_param("i", $id);
            $getDes->execute();
            $getDes->bind_result($dName);
            $getDes->fetch();
            $getDes->close();

            $checkStmt = $conn->prepare("SELECT COUNT(*) FROM employees WHERE designation = ?");
            $checkStmt->bind_param("s", $dName);
            $checkStmt->execute();
            $checkStmt->bind_result($count);
            $checkStmt->fetch();
            $checkStmt->close();

            if ($count > 0) {
                header("Location: departments.php?error=in_use&type=designation");
                exit;
            }

            $stmt = $conn->prepare("DELETE FROM designations WHERE id = ?");
        } else {
            die("Unrecognized relational tracking block.");
        }

        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            header("Location: departments.php?deleted=1&tab=" . urlencode($type));
        } else {
            header("Location: departments.php?error=delete_pipeline_failure&tab=" . urlencode($type));
        }
        $stmt->close();
        exit;
    }
}