<?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('toggle_branch_status', '../pages/branches.php');

$branchId = filter_input(INPUT_POST, 'branch_id', FILTER_VALIDATE_INT) ?: 0;
$nextStatusRaw = trim((string) ($_POST['is_active'] ?? ''));
$nextStatus = $nextStatusRaw === '1' ? 1 : 0;
$returnPage = trim((string) ($_POST['return_page'] ?? ''));
$redirectPath = process_safe_return_path($returnPage, '../pages/branches.php');

if ($branchId <= 0) {
    redirect_with_flash(
        $redirectPath,
        'error',
        localized_flash_message('Branch target is invalid.', 'Branch target is invalid.')
    );
}

$branchRow = branch_master_row_by_id($conn, $branchId);
if (!$branchRow) {
    redirect_with_flash(
        $redirectPath,
        'error',
        localized_flash_message('Branch was not found.', 'Branch was not found.')
    );
}

if ((int) ($branchRow['is_active'] ?? 0) === $nextStatus) {
    redirect_with_flash(
        $redirectPath,
        'success',
        localized_flash_message('Branch status is already up to date.', 'Branch status is already up to date.')
    );
}

$conn->begin_transaction();

try {
    branch_master_save($conn, array(
        'branch_id' => $branchId,
        'branch_name' => (string) ($branchRow['branch_name'] ?? ''),
        'branch_code' => (string) ($branchRow['branch_code'] ?? ''),
        'sort_order' => (int) ($branchRow['sort_order'] ?? 100),
        'is_active' => $nextStatus,
    ));

    $conn->commit();

    redirect_with_flash(
        '../pages/branches.php?branch_id=' . $branchId . '#branch-form',
        'success',
        localized_flash_message('Branch status updated.', 'Branch status updated.')
    );
} catch (Throwable $exception) {
    process_handle_exception_and_redirect(
        $conn,
        $exception,
        'toggle_branch_status',
        '../pages/branches.php?branch_id=' . $branchId . '#branch-form',
        localized_flash_message('Branch status could not be updated.', 'Branch status could not be updated.'),
        array(
            'branch_id' => $branchId,
            'next_status' => $nextStatus,
        ),
        array(),
        true
    );
}
