<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();
require_once __DIR__ . '/shift-type-common.php';

$pageLink = 'organization/shift-types.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = st_take_flash();
$missing = [];
$ready = st_is_ready($con, $missing);
$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? $_POST['id'] ?? 0));
$isAdd = $mode === 'add';
$isEdit = $editId > 0 && !$isAdd;

if (($isAdd && empty($acl['can_add'])) || ($isEdit && empty($acl['can_edit']))) {
    st_flash('You do not have permission to access that Shift Type action.');
    redirect('/' . $pageLink);
}

$record = null;
if ($ready && $isEdit) {
    $record = st_fetch($con, $editId);
    if (!$record) {
        st_flash('Shift Type was not found.');
        redirect('/' . $pageLink);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $id = max(0, (int)($_POST['id'] ?? 0));

    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif (!$ready) {
        $errors[] = 'Required old Shift Type table mapping is missing.';
    } elseif ($action === 'save') {
        $savingEdit = $id > 0;
        if (($savingEdit && empty($acl['can_edit'])) || (!$savingEdit && empty($acl['can_add']))) {
            $errors[] = 'You do not have permission to save Shift Type records.';
        } elseif ($savingEdit && !st_fetch($con, $id)) {
            $errors[] = 'Shift Type was not found.';
        } else {
            $shiftType = trim((string)($_POST['shift_type'] ?? ''));
            $locationId = (int)($_POST['location_id'] ?? 0);

            if ($shiftType === '') {
                $errors[] = 'Shift Type is required.';
            } elseif (mb_strlen($shiftType) > 150) {
                $errors[] = 'Shift Type must be 150 characters or fewer.';
            } elseif (st_duplicate($con, $shiftType, $id)) {
                $errors[] = 'Shift Type already exists.';
            }
            if (!st_location_exists($con, $locationId)) {
                $errors[] = 'Location is required.';
            }

            if (!$errors) {
                $con->begin_transaction();
                try {
                    st_save($con, $id, $shiftType, $locationId);
                    $con->commit();
                    st_flash($savingEdit ? 'Shift Type updated successfully.' : 'Shift Type added successfully.');
                    redirect('/' . $pageLink);
                } catch (Throwable $e) {
                    $con->rollback();
                    error_log('Shift Type save failed: ' . $e->getMessage());
                    $errors[] = 'Unable to save Shift Type. Please try again.';
                }
            }
        }
    } elseif ($action === 'toggle' || $action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to change Shift Type records.';
        } elseif (!st_fetch($con, $id)) {
            $errors[] = 'Shift Type was not found.';
        } elseif ($action === 'toggle') {
            $active = (string)($_POST['target'] ?? '') === 'active';
            st_toggle($con, $id, $active);
            st_flash($active ? 'Shift Type activated successfully.' : 'Shift Type deactivated successfully.');
            redirect('/' . $pageLink);
        } elseif (st_dependency_count($con, $id) > 0) {
            $errors[] = 'Shift Type is already used and cannot be deleted.';
        } else {
            st_delete($con, $id);
            st_flash('Shift Type deleted successfully.');
            redirect('/' . $pageLink);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'save') {
    $shiftTypeValue = trim((string)($_POST['shift_type'] ?? ''));
    $locationValue = (int)($_POST['location_id'] ?? 0);
} else {
    $shiftTypeValue = $record ? st_text($record, 'name') : '';
    $locationValue = $record && $ready ? st_fetch_location_id($con, $editId) : 0;
}

console_header('Add Shift Type', $pageLink);
st_breadcrumb($isEdit ? 'Edit Shift Type' : ($isAdd ? 'Add Shift Type' : 'Add Shift Type'));
st_alerts($flash, $errors);

if (!$ready) {
    st_error_page($missing);
    console_footer();
    exit;
}

$input = 'mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-4 focus:ring-brand-100';
$locations = st_locations($con);

if ($isAdd || $isEdit):
?>
<form method="post" class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
  <input type="hidden" name="action" value="save">
  <?php if ($isEdit): ?><input type="hidden" name="id" value="<?= (int)$editId ?>"><?php endif; ?>
  <div class="flex flex-col gap-4 border-b border-slate-100 px-5 py-5 md:flex-row md:items-center md:justify-between">
    <div class="flex items-center gap-4">
      <span class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600"><i class="fa-solid fa-layer-group"></i></span>
      <div>
        <h2 class="text-lg font-bold text-slate-800"><?= $isEdit ? 'Edit Shift Type' : 'New Shift Type' ?></h2>
        <p class="mt-1 text-sm font-medium text-slate-400">Fields marked with * are required.</p>
      </div>
    </div>
    <a href="/<?= h($pageLink) ?>" class="inline-flex items-center justify-center rounded-xl border border-slate-200 px-5 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-arrow-left mr-2"></i>Back to List</a>
  </div>
  <div class="grid gap-5 p-5 md:grid-cols-2">
    <label class="text-sm font-bold text-slate-700">Shift Type *
      <input type="text" name="shift_type" maxlength="150" required value="<?= h($shiftTypeValue) ?>" placeholder="Shift Type" class="<?= h($input) ?>">
    </label>
    <label class="text-sm font-bold text-slate-700">Location *
      <select name="location_id" required class="<?= h($input) ?>">
        <option value="">Select Location</option>
        <?php foreach ($locations as $location): ?>
          <option value="<?= (int)$location['id'] ?>" <?= $locationValue === (int)$location['id'] ? 'selected' : '' ?>><?= h((string)$location['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </label>
  </div>
  <div class="flex justify-center gap-3 px-5 pb-6">
    <button type="submit" class="rounded-xl bg-brand-600 px-8 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-floppy-disk mr-2"></i>Submit</button>
    <a href="/<?= h($pageLink) ?>" class="rounded-xl border border-slate-200 px-8 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50">Cancel</a>
  </div>
</form>
<?php
else:
    $statusColumn = st_status_column($con);
    $safeStatus = preg_replace('/[^A-Za-z0-9_]/', '', $statusColumn);
    $search = trim((string)($_GET['q'] ?? ''));
    $status = (string)($_GET['status'] ?? '');
    $where = [];
    $types = '';
    $params = [];

    if ($search !== '') {
        $where[] = 'name LIKE ?';
        $types .= 's';
        $params[] = '%' . $search . '%';
    }
    if ($status === '1' || $status === '0') {
        $where[] = '`' . $safeStatus . '`=?';
        $types .= 'i';
        $params[] = (int)$status;
    }
    $whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';

    $countStmt = st_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_empshiftgroup' . $whereSql);
    if ($types !== '') {
        $countStmt->bind_param($types, ...$params);
    }
    $countStmt->execute();
    $totalRows = (int)($countStmt->get_result()->fetch_assoc()['total'] ?? 0);
    $countStmt->close();

    $page = max(1, (int)($_GET['page'] ?? 1));
    $perPage = 15;
    $totalPages = max(1, (int)ceil($totalRows / $perPage));
    if ($page > $totalPages) {
        $page = $totalPages;
    }
    $offset = ($page - 1) * $perPage;

    $stmt = st_stmt($con, 'SELECT * FROM jos_app_empshiftgroup' . $whereSql . ' ORDER BY id DESC LIMIT ? OFFSET ?');
    if ($types !== '') {
        $bindTypes = $types . 'ii';
        $bindParams = array_merge($params, [$perPage, $offset]);
        $stmt->bind_param($bindTypes, ...$bindParams);
    } else {
        $stmt->bind_param('ii', $perPage, $offset);
    }
    $stmt->execute();
    $records = [];
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $records[] = $row;
    }
    $stmt->close();
?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-4 border-b border-slate-100 p-5 md:flex-row md:items-center md:justify-between">
    <div>
      <h2 class="text-lg font-bold text-slate-800">Shift Type List</h2>
      <p class="mt-1 text-sm font-medium text-slate-400">Shift types are ordered by latest record.</p>
    </div>
    <?php if (!empty($acl['can_add'])): ?>
      <a href="/<?= h($pageLink) ?>?mode=add" class="inline-flex items-center justify-center rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add</a>
    <?php endif; ?>
  </div>
  <form method="get" class="flex flex-col gap-3 border-b border-slate-100 p-5 md:flex-row md:items-center">
    <input type="search" name="q" value="<?= h($search) ?>" placeholder="Search shift type" class="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-4 focus:ring-brand-100 md:max-w-sm">
    <select name="status" class="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none transition focus:border-brand-500 focus:ring-4 focus:ring-brand-100 md:max-w-xs">
      <option value="">All Status</option>
      <option value="1" <?= $status === '1' ? 'selected' : '' ?>>Active</option>
      <option value="0" <?= $status === '0' ? 'selected' : '' ?>>Inactive</option>
    </select>
    <button type="submit" class="inline-flex items-center justify-center rounded-xl bg-slate-900 px-5 py-3 text-sm font-bold text-white hover:bg-slate-800"><i class="fa-solid fa-filter mr-2"></i>Filter</button>
    <a href="/<?= h($pageLink) ?>" class="inline-flex items-center justify-center rounded-xl border border-slate-200 px-5 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50">Clear</a>
  </form>
  <div class="overflow-x-auto">
    <table class="w-full min-w-[760px] text-left text-sm">
      <thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600">
        <tr>
          <th class="w-20 px-5 py-4">Sr No</th>
          <th class="px-5 py-4">Shift Type</th>
          <th class="w-36 px-5 py-4">Status</th>
          <th class="w-52 px-5 py-4 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
      <?php if (!$records): ?>
        <tr><td colspan="4" class="px-5 py-16 text-center text-sm font-bold text-slate-400">No shift types found.</td></tr>
      <?php else: foreach ($records as $index => $row): ?>
        <?php $isActive = st_status_value($con, $row) === 1; ?>
        <tr class="align-top hover:bg-slate-50/70">
          <td class="px-5 py-4 font-semibold text-slate-500"><?= h((string)($offset + $index + 1)) ?></td>
          <td class="px-5 py-4 font-bold text-slate-800"><?= h(st_text($row, 'name', '-')) ?></td>
          <td class="px-5 py-4"><span class="inline-flex rounded-full <?= $isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500' ?> px-3 py-1 text-xs font-bold"><?= $isActive ? 'Active' : 'Inactive' ?></span></td>
          <td class="px-5 py-4">
            <div class="flex items-center justify-end gap-2">
              <?php if (!empty($acl['can_edit'])): ?>
                <a href="/<?= h($pageLink) ?>?edit=<?= (int)$row['id'] ?>" class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 hover:border-brand-200 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen-to-square"></i></a>
              <?php endif; ?>
              <?php if (!empty($acl['can_delete'])): ?>
                <form method="post" onsubmit="return confirm('<?= $isActive ? 'Deactivate' : 'Activate' ?> this Shift Type?');">
                  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                  <input type="hidden" name="action" value="toggle">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <input type="hidden" name="target" value="<?= $isActive ? 'inactive' : 'active' ?>">
                  <button type="submit" class="rounded-xl <?= $isActive ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-slate-700 hover:bg-slate-800' ?> px-4 py-2 text-xs font-bold text-white"><?= $isActive ? 'Deactivate' : 'Activate' ?></button>
                </form>
                <form method="post" onsubmit="return confirm('Delete this Shift Type?');">
                  <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                  <button type="submit" class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 hover:border-red-200 hover:bg-red-50 hover:text-red-600" title="Delete"><i class="fa-solid fa-trash-can"></i></button>
                </form>
              <?php endif; ?>
            </div>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
  <?php if ($totalPages > 1): ?>
    <div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm font-semibold text-slate-500">
      <span>Page <?= h((string)$page) ?> of <?= h((string)$totalPages) ?></span>
      <div class="flex gap-2">
        <?php $queryBase = 'q=' . urlencode($search) . '&status=' . urlencode($status) . '&page='; ?>
        <?php if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-3 py-2 hover:bg-slate-50" href="?<?= h($queryBase . ($page - 1)) ?>">Previous</a><?php endif; ?>
        <?php if ($page < $totalPages): ?><a class="rounded-lg border border-slate-200 px-3 py-2 hover:bg-slate-50" href="?<?= h($queryBase . ($page + 1)) ?>">Next</a><?php endif; ?>
      </div>
    </div>
  <?php endif; ?>
</section>
<?php
endif;
console_footer();
