<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_permission($conn, 'branches_manage');
process_post_only_or_redirect('../pages/branches.php');
ensure_post_csrf_or_redirect('save_branch', '../pages/branches.php', $_POST);

$branchId = filter_input(INPUT_POST, 'branch_id', FILTER_VALIDATE_INT) ?: 0;
$branchName = normalize_branch_name((string) ($_POST['branch_name'] ?? ''));
$branchCode = normalize_branch_code((string) ($_POST['branch_code'] ?? ''));
$sortOrder = filter_input(INPUT_POST, 'sort_order', FILTER_VALIDATE_INT);
$isActive = isset($_POST['is_active']) ? 1 : 0;

$oldInput = array(
    'branch_id' => $branchId > 0 ? (string) $branchId : '',
    'branch_name' => $branchName,
    'branch_code' => $branchCode,
    'sort_order' => $sortOrder === false || $sortOrder === null ? '100' : (string) $sortOrder,
    'is_active' => $isActive === 1 ? '1' : '0',
);

$redirectPath = '../pages/branches.php';
if ($branchId > 0) {
    $redirectPath .= '?branch_id=' . $branchId . '#branch-form';
}

if ($branchName === '') {
    redirect_with_flash(
        $redirectPath,
        'error',
        localized_flash_message('Branch name is required.', 'Branch name is required.'),
        $oldInput
    );
}

if ($branchCode === '') {
    redirect_with_flash(
        $redirectPath,
        'error',
        localized_flash_message('Branch code is required.', 'Branch code is required.'),
        $oldInput
    );
}

$sortOrder = $sortOrder === false || $sortOrder === null ? 100 : $sortOrder;

$conn->begin_transaction();

try {
    $savedBranchId = branch_master_save($conn, array(
        'branch_id' => $branchId,
        'branch_name' => $branchName,
        'branch_code' => $branchCode,
        'sort_order' => $sortOrder,
        'is_active' => $isActive,
    ));

    $conn->commit();

    redirect_with_flash(
        '../pages/branches.php?branch_id=' . $savedBranchId . '#branch-form',
        'success',
        localized_flash_message('Branch saved successfully.', 'Branch saved successfully.')
    );
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'save_branch',
        $redirectPath,
        localized_flash_message('Branch could not be saved.', 'Branch could not be saved.'),
        array(
            'branch_id' => $branchId,
            'branch_name' => $branchName,
            'branch_code' => $branchCode,
            'sort_order' => $sortOrder,
            'is_active' => $isActive,
        ),
        $oldInput,
        true
    );
}
