<?php /* branches/form.php */
$isEdit    = !empty($branch);
$action    = $isEdit
  ? APP_URL . '/branches/edit/' . $branch['id']
  : APP_URL . '/branches/create';

// All users for assignment (edit mode)
$allUsers = $isEdit ? Database::fetchAll(
    "SELECT u.id, u.name, u.username, r.role_name,
            b.name AS current_branch,
            u.branch_id
     FROM users u
     JOIN roles r ON r.id = u.role_id
     LEFT JOIN branches b ON b.id = u.branch_id
     WHERE u.status = 'active'
     ORDER BY u.name"
) : [];

// All branches for reassignment dropdown
$allBranches = $isEdit ? Database::fetchAll(
    'SELECT id, name FROM branches WHERE status = ? ORDER BY is_main DESC, name ASC',
    ['active']
) : [];
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h5 class="fw-bold mb-0">
    <i class="bi bi-building<?= $isEdit?'-fill':'' ?> me-2 text-primary"></i>
    <?= $isEdit ? 'Edit Branch: <strong>' . e($branch['name']) . '</strong>' : 'Add New Branch' ?>
  </h5>
  <a href="<?= APP_URL ?>/branches" class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Back to Branches
  </a>
</div>

<?= flashMessages() ?>

<div class="row g-3">

  <!-- Branch Details Form -->
  <div class="col-lg-5">
    <div class="card">
      <div class="card-header bg-transparent fw-semibold small">
        <i class="bi bi-info-circle me-1"></i>Branch Details
      </div>
      <div class="card-body">
        <form method="POST" action="<?= $action ?>">
          <?= Auth::csrfField() ?>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Branch Name <span class="text-danger">*</span></label>
            <input type="text" name="name" class="form-control fw-semibold"
                   value="<?= e($branch['name'] ?? '') ?>"
                   placeholder="e.g. Colombo Branch"
                   <?= ($branch['is_main'] ?? false) ? 'readonly' : '' ?>
                   required>
            <?php if($branch['is_main'] ?? false):?>
            <div class="form-text text-warning">Main branch name is locked.</div>
            <?php endif;?>
          </div>

          <div class="mb-3">
            <label class="form-label fw-semibold small">Address</label>
            <textarea name="address" class="form-control" rows="2"
                      placeholder="Branch address…"><?= e($branch['address'] ?? '') ?></textarea>
          </div>

          <div class="row g-2 mb-3">
            <div class="col-6">
              <label class="form-label fw-semibold small">Phone</label>
              <input type="text" name="phone" class="form-control form-control-sm"
                     value="<?= e($branch['phone'] ?? '') ?>"
                     placeholder="+94 11 234 5678">
            </div>
            <div class="col-6">
              <label class="form-label fw-semibold small">Email</label>
              <input type="email" name="email" class="form-control form-control-sm"
                     value="<?= e($branch['email'] ?? '') ?>"
                     placeholder="branch@shop.com">
            </div>
          </div>

          <div class="mb-3 d-flex gap-3">
            <div class="form-check">
              <input type="checkbox" name="is_main" value="1"
                     class="form-check-input" id="isMain"
                     <?= ($branch['is_main'] ?? false) ? 'checked disabled' : '' ?>>
              <label class="form-check-label small fw-semibold" for="isMain">
                Set as Main Branch
              </label>
              <div class="form-text">Only one main branch allowed</div>
            </div>
          </div>

          <?php if($isEdit):?>
          <div class="mb-3">
            <label class="form-label fw-semibold small">Status</label>
            <select name="status" class="form-select form-select-sm"
                    <?= ($branch['is_main'] ?? false) ? 'disabled' : '' ?>>
              <option value="active"   <?= ($branch['status']??'')==='active'   ?'selected':''?>>Active</option>
              <option value="inactive" <?= ($branch['status']??'')==='inactive' ?'selected':''?>>Inactive</option>
            </select>
          </div>
          <?php endif;?>

          <button type="submit" class="btn btn-primary w-100 fw-semibold">
            <i class="bi bi-check-circle me-1"></i>
            <?= $isEdit ? 'Save Changes' : 'Create Branch' ?>
          </button>
        </form>
      </div>
    </div>

    <?php if($isEdit && !empty($branchUsers)):?>
    <!-- Users in this branch -->
    <div class="card mt-3">
      <div class="card-header bg-transparent fw-semibold small">
        <i class="bi bi-people me-1 text-primary"></i>
        Users in this Branch
        <span class="badge bg-primary ms-1"><?= count($branchUsers) ?></span>
      </div>
      <div class="card-body p-0">
        <table class="table table-sm mb-0">
          <thead class="table-secondary">
            <tr><th>Name</th><th>Role</th><th class="no-print">Action</th></tr>
          </thead>
          <tbody>
            <?php foreach($branchUsers as $u):
              $rc = match($u['role_name']) {
                'super_admin'=>'bg-danger','admin'=>'bg-primary',
                'manager'=>'bg-info text-dark','cashier'=>'bg-success',default=>'bg-secondary'};
            ?>
            <tr>
              <td>
                <div class="small fw-semibold"><?= e($u['name']) ?></div>
                <code style="font-size:.65rem" class="text-muted"><?= e($u['username']) ?></code>
              </td>
              <td>
                <span class="badge <?= $rc ?>" style="font-size:.62rem">
                  <?= e(str_replace('_',' ',$u['role_name'])) ?>
                </span>
              </td>
              <td>
                <form method="POST" action="<?= APP_URL ?>/branches/assign-user">
                  <?= Auth::csrfField() ?>
                  <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                  <div class="input-group input-group-sm">
                    <select name="branch_id" class="form-select form-select-sm">
                      <?php foreach($allBranches as $br):?>
                      <option value="<?= $br['id'] ?>"
                              <?= $br['id']==$branch['id']?'selected':''?>>
                        <?= e($br['name']) ?>
                      </option>
                      <?php endforeach;?>
                    </select>
                    <button class="btn btn-sm btn-outline-primary">
                      <i class="bi bi-arrow-right"></i>
                    </button>
                  </div>
                </form>
              </td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif;?>
  </div>

  <!-- All users assignment panel -->
  <?php if($isEdit):?>
  <div class="col-lg-7">
    <div class="card">
      <div class="card-header bg-dark text-white fw-semibold small d-flex justify-content-between">
        <span><i class="bi bi-person-gear me-1"></i>Assign Users to Branches</span>
        <span class="badge bg-secondary"><?= count($allUsers) ?> users</span>
      </div>
      <div class="card-body p-0">
        <!-- Search filter -->
        <div class="p-2 border-bottom">
          <input type="text" id="userFilter" class="form-control form-control-sm"
                 placeholder="Filter users…" oninput="filterUsers(this.value)">
        </div>
        <div style="max-height:520px;overflow-y:auto">
          <table class="table table-sm table-hover mb-0" id="usersTable">
            <thead class="table-secondary sticky-top">
              <tr>
                <th>User</th>
                <th>Role</th>
                <th>Current Branch</th>
                <th>Assign To</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($allUsers as $u):
                $inThisBranch = $u['branch_id'] == $branch['id'];
                $rc = match($u['role_name']) {
                  'super_admin'=>'bg-danger','admin'=>'bg-primary',
                  'manager'=>'bg-info text-dark','cashier'=>'bg-success',default=>'bg-secondary'};
              ?>
              <tr class="user-row <?= $inThisBranch?'table-success bg-opacity-10':'' ?>"
                  data-name="<?= strtolower(e($u['name'].' '.$u['username'])) ?>">
                <td>
                  <div class="small fw-semibold"><?= e($u['name']) ?></div>
                  <code style="font-size:.65rem" class="text-muted"><?= e($u['username']) ?></code>
                </td>
                <td>
                  <span class="badge <?= $rc ?>" style="font-size:.6rem">
                    <?= e(str_replace('_',' ',$u['role_name'])) ?>
                  </span>
                </td>
                <td class="small">
                  <?php if($inThisBranch):?>
                  <span class="text-success fw-semibold">
                    <i class="bi bi-check-circle me-1"></i><?= e($u['current_branch']) ?>
                  </span>
                  <?php else:?>
                  <span class="text-muted"><?= e($u['current_branch'] ?? 'Unassigned') ?></span>
                  <?php endif;?>
                </td>
                <td>
                  <form method="POST" action="<?= APP_URL ?>/branches/assign-user"
                        class="d-flex gap-1 align-items-center">
                    <?= Auth::csrfField() ?>
                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                    <select name="branch_id" class="form-select form-select-sm"
                            style="max-width:140px">
                      <?php foreach($allBranches as $br):?>
                      <option value="<?= $br['id'] ?>"
                              <?= $br['id']==$u['branch_id']?'selected':''?>>
                        <?= e($br['name']) ?>
                      </option>
                      <?php endforeach;?>
                    </select>
                    <button class="btn btn-sm btn-outline-primary flex-shrink-0"
                            title="Assign">
                      <i class="bi bi-arrow-right-circle"></i>
                    </button>
                  </form>
                </td>
              </tr>
              <?php endforeach;?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Quick assign all to this branch -->
      <div class="card-footer py-2 d-flex justify-content-between align-items-center">
        <small class="text-muted">
          <i class="bi bi-info-circle me-1"></i>
          Click <i class="bi bi-arrow-right-circle"></i> to reassign a user
        </small>
        <form method="POST" action="<?= APP_URL ?>/branches/assign-all"
              onsubmit="return confirm('Assign ALL unassigned users to <?= e($branch['name']) ?>?')">
          <?= Auth::csrfField() ?>
          <input type="hidden" name="branch_id" value="<?= $branch['id'] ?>">
          <button class="btn btn-sm btn-outline-warning fw-semibold">
            <i class="bi bi-people me-1"></i>Assign Unassigned → This Branch
          </button>
        </form>
      </div>
    </div>
  </div>
  <?php endif;?>

</div>

<script>
function filterUsers(q) {
  q = q.toLowerCase();
  document.querySelectorAll('.user-row').forEach(row => {
    row.style.display = row.dataset.name.includes(q) ? '' : 'none';
  });
}
</script>