<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';

require_permission($conn, 'branches_manage');

$oldInput = pull_old_input();
$editingBranchId = filter_input(INPUT_GET, 'branch_id', FILTER_VALIDATE_INT) ?: (int) old_value($oldInput, 'branch_id', '0');
$branches = branch_master_rows($conn, true);
$usageByBranchName = array();
$editingBranch = null;
$activeBranchCount = 0;
$returnPage = current_page_return('branches.php');

foreach ($branches as $branchRow) {
    $branchName = trim((string) ($branchRow['branch_name'] ?? ''));
    $usageByBranchName[$branchName] = branch_master_usage_counts($conn, $branchName);

    if ((int) ($branchRow['is_active'] ?? 0) === 1) {
        $activeBranchCount++;
    }

    if ((int) ($branchRow['branch_id'] ?? 0) === $editingBranchId) {
        $editingBranch = $branchRow;
    }
}

$formBranchId = $editingBranch ? (int) ($editingBranch['branch_id'] ?? 0) : 0;
$formBranchName = old_value($oldInput, 'branch_name', (string) ($editingBranch['branch_name'] ?? ''));
$formBranchCode = old_value($oldInput, 'branch_code', (string) ($editingBranch['branch_code'] ?? ''));
$formSortOrder = old_value($oldInput, 'sort_order', (string) ($editingBranch['sort_order'] ?? '100'));
$formIsActive = old_value($oldInput, 'is_active', $editingBranch ? ((int) ($editingBranch['is_active'] ?? 0) === 1 ? '1' : '0') : '1') === '1';

$pageTitle = ui_text('จัดการสาขา', 'Branch Management');
$pageHeading = ui_text('เพิ่มหรือแก้ไขข้อมูลสาขา', 'Add or edit branch');
$pageDescription = ui_text(
    'กำหนดข้อมูลสาขากลางของระบบ เพื่อให้ทุกฟังก์ชันใช้รายการสาขาจากแหล่งเดียวกัน',
    'Manage central branch data so every function uses the same branch source.'
);
$backToManageSystemLabel = ui_text('กลับไปจัดการระบบ', 'Back to Manage System');
$formTitle = $editingBranch ? ui_text('แก้ไขสาขา', 'Edit branch') : ui_text('เพิ่มสาขาใหม่', 'Add branch');
$formHelper = ui_text(
    'ตั้งชื่อสาขา รหัสสาขา ลำดับแสดงผล และสถานะใช้งาน',
    'Set branch name, code, sort order, and active status.'
);
$resetFormLabel = ui_text('เพิ่มสาขาใหม่', 'New branch');
$branchNameLabel = ui_text('ชื่อสาขา', 'Branch name');
$branchCodeLabel = ui_text('รหัสสาขา', 'Branch code');
$branchCodeHelper = ui_text('ใช้ตัวอักษรหรือตัวเลข 3 ตัว เช่น SRN', 'Use 3 letters or numbers, for example SRN.');
$sortOrderLabel = ui_text('ลำดับแสดงผล', 'Sort order');
$activeStatusLabel = ui_text('เปิดใช้งานสาขานี้', 'Branch is active');
$saveLabel = ui_text('บันทึกสาขา', 'Save branch');
$totalBranchesLabel = ui_text('จำนวนสาขาทั้งหมด', 'Total branches');
$activeLabel = ui_text('ใช้งาน', 'Active');
$inactiveLabel = ui_text('ปิดใช้งาน', 'Inactive');
$statusLabel = ui_text('สถานะ', 'Status');
$usageLabel = ui_text('การใช้งาน', 'Usage');
$usageOrdersLabel = ui_text('บิลทั้งหมด', 'Total orders');
$usageOpenOrdersLabel = ui_text('งานค้าง', 'Open jobs');
$usageEmployeesLabel = ui_text('พนักงานที่ผูกสาขา', 'Assigned employees');
$actionLabel = ui_text('จัดการ', 'Action');
$editLabel = ui_text('แก้ไข', 'Edit');
$activateLabel = ui_text('เปิดใช้งาน', 'Activate');
$deactivateLabel = ui_text('ปิดใช้งาน', 'Deactivate');
$cannotDeactivateOpenLabel = ui_text('ปิดไม่ได้: มีงานค้าง', 'Cannot deactivate: open jobs exist.');
$cannotDeactivateLastLabel = ui_text('ปิดไม่ได้: ต้องมีสาขาที่ใช้งานอย่างน้อย 1 สาขา', 'Cannot deactivate: at least one active branch is required.');
$emptyStateLabel = ui_text('ยังไม่มีข้อมูลสาขา', 'No branches found yet.');

render_page_start($pageTitle, 'branches', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($pageHeading) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <a class="button button-secondary" href="manage_system.php"><?= e($backToManageSystemLabel) ?></a>
    </div>
</section>

<div class="grid">
    <section class="form-card" id="branch-form">
        <div class="section-head">
            <div>
                <h2 class="section-title"><?= e($formTitle) ?></h2>
                <p class="helper"><?= e($formHelper) ?></p>
            </div>
            <?php if ($editingBranch): ?>
                <a class="button button-ghost" href="branches.php"><?= e($resetFormLabel) ?></a>
            <?php endif; ?>
        </div>

        <form method="POST" action="../process/save_branch.php">
            <?= csrf_input('save_branch') ?>
            <?php if ($formBranchId > 0): ?>
                <input type="hidden" name="branch_id" value="<?= $formBranchId ?>">
            <?php endif; ?>

            <div class="form-grid">
                <div class="field">
                    <label for="branch_name"><?= e($branchNameLabel) ?></label>
                    <input id="branch_name" name="branch_name" type="text" value="<?= e($formBranchName) ?>" required>
                </div>

                <div class="field">
                    <label for="branch_code"><?= e($branchCodeLabel) ?></label>
                    <input id="branch_code" name="branch_code" type="text" value="<?= e($formBranchCode) ?>" maxlength="3" style="text-transform: uppercase;" required>
                    <p class="helper"><?= e($branchCodeHelper) ?></p>
                </div>

                <div class="field">
                    <label for="sort_order"><?= e($sortOrderLabel) ?></label>
                    <input id="sort_order" name="sort_order" type="number" min="0" step="1" value="<?= e($formSortOrder) ?>">
                </div>
            </div>

            <label class="service-option compact-option">
                <input type="checkbox" name="is_active" value="1" <?= $formIsActive ? 'checked' : '' ?>>
                <span>
                    <strong><?= e($activeStatusLabel) ?></strong>
                </span>
            </label>

            <button class="button button-accent" type="submit"><?= e($saveLabel) ?></button>
        </form>
    </section>
</div>

<section class="table-card" style="margin-top: 18px;">
    <div class="section-head" style="padding: 18px 18px 0;">
        <div>
            <h2 class="section-title"><?= e($totalBranchesLabel) ?></h2>
            <p class="helper"><?= count($branches) ?></p>
        </div>
    </div>

    <?php if (empty($branches)): ?>
        <div class="empty-state" style="margin: 18px;"><?= e($emptyStateLabel) ?></div>
    <?php else: ?>
        <table style="min-width: 720px;">
            <thead>
            <tr>
                <th><?= e($branchCodeLabel) ?></th>
                <th><?= e($branchNameLabel) ?></th>
                <th><?= e($sortOrderLabel) ?></th>
                <th><?= e($statusLabel) ?></th>
                <th><?= e($usageLabel) ?></th>
                <th><?= e($actionLabel) ?></th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($branches as $branchRow): ?>
                <?php
                $branchId = (int) ($branchRow['branch_id'] ?? 0);
                $branchName = (string) ($branchRow['branch_name'] ?? '');
                $isActive = (int) ($branchRow['is_active'] ?? 0) === 1;
                $usage = $usageByBranchName[$branchName] ?? array(
                    'orders_total' => 0,
                    'orders_open' => 0,
                    'employees_assigned' => 0,
                );
                $openOrders = (int) ($usage['orders_open'] ?? 0);
                $canToggleDeactivate = $openOrders === 0 && $activeBranchCount > 1;
                $toggleToActive = $isActive ? 0 : 1;
                $toggleLabel = $isActive ? $deactivateLabel : $activateLabel;
                $toggleDisabledMessage = '';

                if ($isActive && !$canToggleDeactivate) {
                    $toggleDisabledMessage = $openOrders > 0 ? $cannotDeactivateOpenLabel : $cannotDeactivateLastLabel;
                }
                ?>
                <tr>
                    <td><strong><?= e((string) ($branchRow['branch_code'] ?? '-')) ?></strong></td>
                    <td><?= e($branchName !== '' ? $branchName : '-') ?></td>
                    <td><?= (int) ($branchRow['sort_order'] ?? 0) ?></td>
                    <td><?= e($isActive ? $activeLabel : $inactiveLabel) ?></td>
                    <td>
                        <div class="helper">
                            <?= e($usageOrdersLabel) ?>: <?= (int) ($usage['orders_total'] ?? 0) ?><br>
                            <?= e($usageOpenOrdersLabel) ?>: <?= $openOrders ?><br>
                            <?= e($usageEmployeesLabel) ?>: <?= (int) ($usage['employees_assigned'] ?? 0) ?>
                        </div>
                    </td>
                    <td>
                        <div class="inline-actions">
                            <a class="button button-secondary" href="branches.php?branch_id=<?= $branchId ?>#branch-form"><?= e($editLabel) ?></a>
                            <?php if ($isActive && !$canToggleDeactivate): ?>
                                <span class="muted"><?= e($toggleDisabledMessage) ?></span>
                            <?php else: ?>
                                <form class="inline-form" method="POST" action="../process/toggle_branch_status.php">
                                    <?= csrf_input('toggle_branch_status') ?>
                                    <input type="hidden" name="branch_id" value="<?= $branchId ?>">
                                    <input type="hidden" name="is_active" value="<?= $toggleToActive ?>">
                                    <input type="hidden" name="return_page" value="<?= e($returnPage) ?>">
                                    <button class="button button-ghost" type="submit"><?= e($toggleLabel) ?></button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</section>

<?php render_page_end(); ?>
