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

require_once __DIR__ . '/../includes/console_shell.php';
require_login();
require_once __DIR__ . '/financial-year-common.php';

$pageLink = 'organization/financial-year.php';
$acl = require_acl('can_view', $pageLink);
$errors = [];
$flash = $_SESSION['flash_financial_year'] ?? null;
unset($_SESSION['flash_financial_year']);

if (!fy_table_exists($con, 'jos_app_year')) {
    console_header('Financial Year', $pageLink);
    fy_breadcrumb('Financial Year');
    echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Financial Year table is not available.</div>';
    console_footer();
    exit;
}

$columns = fy_columns($con, 'jos_app_year');
if (!fy_has($columns, 'id') || !fy_has($columns, 'year')) {
    console_header('Financial Year', $pageLink);
    fy_breadcrumb('Financial Year');
    echo '<div class="rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700">Required Financial Year columns are missing.</div>';
    console_footer();
    exit;
}

$mode = (string)($_GET['mode'] ?? '');
$editId = max(0, (int)($_GET['edit'] ?? $_POST['id'] ?? 0));
$isAdd = $mode === 'add';
$isEdit = $editId > 0;
$formRecord = $isEdit ? fy_fetch($con, $editId) : null;

if ($isEdit && !$formRecord) {
    fy_flash('Financial Year was not found.');
    redirect('/' . $pageLink);
}
if ($isAdd && empty($acl['can_add'])) {
    fy_flash('You do not have permission to add Financial Year records.');
    redirect('/' . $pageLink);
}
if ($isEdit && empty($acl['can_edit'])) {
    fy_flash('You do not have permission to edit Financial Year records.');
    redirect('/' . $pageLink);
}

$year = (string)($_POST['year'] ?? ($formRecord ? fy_text($formRecord, 'year') : ''));

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 ($action === 'save') {
        if ($id > 0 && empty($acl['can_edit'])) {
            $errors[] = 'You do not have permission to edit Financial Year records.';
        } elseif ($id <= 0 && empty($acl['can_add'])) {
            $errors[] = 'You do not have permission to add Financial Year records.';
        } elseif ($id > 0 && !fy_fetch($con, $id)) {
            $errors[] = 'Financial Year was not found.';
        } else {
            $year = fy_validate_year((string)($_POST['year'] ?? ''), $errors);
            if ($year !== '' && fy_duplicate($con, $year, $id)) {
                $errors[] = 'Financial Year already exists.';
            }
            if (!$errors) {
                fy_save($con, $id, $year);
                fy_flash($id > 0 ? 'Financial Year updated successfully.' : 'Financial Year added successfully.');
                redirect('/' . $pageLink);
            }
        }
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) {
            $errors[] = 'You do not have permission to delete Financial Year records.';
        } elseif (!fy_fetch($con, $id)) {
            $errors[] = 'Financial Year was not found.';
        } elseif (fy_dependency_count($con, $id) > 0) {
            $errors[] = 'Financial Year is already used in configuration records and cannot be deleted.';
        } else {
            fy_delete($con, $id);
            fy_flash('Financial Year deleted successfully.');
            redirect('/' . $pageLink);
        }
    }
}

console_header($isAdd ? 'Add Financial Year' : ($isEdit ? 'Edit Financial Year' : 'Financial Year'), $pageLink);
fy_breadcrumb($isAdd ? 'Add Financial Year' : ($isEdit ? 'Edit Financial Year' : 'Financial Year'));
fy_alerts($flash, $errors);

$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';

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">
  <input type="hidden" name="id" value="<?= (int)$editId ?>">
  <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 <?= $isEdit ? 'fa-pen-to-square' : 'fa-calendar-days' ?>"></i></span>
      <div>
        <h2 class="text-lg font-bold text-slate-800"><?= $isEdit ? 'Edit Financial Year' : 'New Financial Year' ?></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">Financial Year *
      <input type="text" name="year" maxlength="30" required value="<?= h($year) ?>" placeholder="Example: 2026-2027" class="<?= h($input) ?>">
    </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
    console_footer();
    exit;
endif;

$search = trim((string)($_GET['q'] ?? ''));
$where = '';
$types = '';
$params = [];
if ($search !== '') {
    $where = ' WHERE `year` LIKE ?';
    $types = 's';
    $params[] = '%' . $search . '%';
}

$countStmt = fy_stmt($con, 'SELECT COUNT(*) AS total FROM jos_app_year' . $where);
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 = fy_stmt($con, 'SELECT * FROM jos_app_year' . $where . ' ORDER BY id DESC LIMIT ? OFFSET ?');
if ($types !== '') {
    $typesWithLimit = $types . 'ii';
    $paramsWithLimit = array_merge($params, [$perPage, $offset]);
    $stmt->bind_param($typesWithLimit, ...$paramsWithLimit);
} 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">Financial Year List</h2>
      <p class="mt-1 text-sm font-medium text-slate-400">Financial years 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 financial year" 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">
    <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-[720px] 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">Year</th>
          <th class="w-40 px-5 py-4 text-right">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-100">
      <?php if (!$records): ?>
        <tr><td colspan="3" class="px-5 py-16 text-center text-sm font-bold text-slate-400">No financial years found.</td></tr>
      <?php else: foreach ($records as $index => $row): ?>
        <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(fy_text($row, 'year', '-')) ?></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('Delete this Financial Year?');">
                  <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 if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-3 py-2 hover:bg-slate-50" href="?q=<?= urlencode($search) ?>&page=<?= $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="?q=<?= urlencode($search) ?>&page=<?= $page + 1 ?>">Next</a><?php endif; ?>
      </div>
    </div>
  <?php endif; ?>
</section>
<?php
console_footer();
