<?php

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../includes/csrf.php';
require_once __DIR__ . '/../../includes/activity_log.php';

header('Content-Type: application/json');

if (($_SESSION['role'] ?? '') !== 'admin')
{
    echo json_encode(['success' => false, 'message' => 'Access denied.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? ''))
{
    echo json_encode(['success' => false, 'message' => 'Invalid request.']);
    exit();
}

$id = (int)($_POST['id'] ?? 0);
$name = trim($_POST['unit_name'] ?? '');
$description = trim($_POST['description'] ?? '');
$order = max(1, (int)($_POST['display_order'] ?? 1));
$required = ($_POST['is_required'] ?? 'No') === 'Yes' ? 'Yes' : 'No';
$status = ($_POST['status'] ?? 'Active') === 'Inactive' ? 'Inactive' : 'Active';

if ($name === '' || mb_strlen($name) > 100 || mb_strlen($description) > 255)
{
    echo json_encode(['success' => false, 'message' => 'Please enter a valid unit name and description.']);
    exit();
}

$check = mysqli_prepare($conn, 'SELECT id FROM unit_master WHERE unit_name=? AND id<>?');
mysqli_stmt_bind_param($check, 'si', $name, $id);
mysqli_stmt_execute($check);
$exists = mysqli_num_rows(mysqli_stmt_get_result($check)) > 0;
mysqli_stmt_close($check);

if ($exists)
{
    echo json_encode(['success' => false, 'message' => 'A unit with this name already exists.']);
    exit();
}

if ($id > 0)
{
    $stmt = mysqli_prepare($conn, 'UPDATE unit_master SET unit_name=?, description=?, display_order=?, is_required=?, status=? WHERE id=?');
    mysqli_stmt_bind_param($stmt, 'ssissi', $name, $description, $order, $required, $status, $id);
}
else
{
    $stmt = mysqli_prepare($conn, 'INSERT INTO unit_master (unit_name, description, display_order, is_required, status) VALUES (?,?,?,?,?)');
    mysqli_stmt_bind_param($stmt, 'ssiss', $name, $description, $order, $required, $status);
}

if (mysqli_stmt_execute($stmt))
{
    logActivity(
        $conn,
        'Unit Management',
        $id > 0 ? 'Update Unit' : 'Create Unit',
        'Unit "' . $name . '" saved.'
    );

    echo json_encode([
        'success' => true,
        'message' => 'Unit saved successfully.'
    ]);
}
else
{
    echo json_encode(['success' => false, 'message' => 'Unable to save the unit.']);
}

mysqli_stmt_close($stmt);
