#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys, io, cgitb, html
from fiscal_tools import fetch_latest_row, FINANCE_DB_PATH, THISYEAR_DB_PATH
from settings import get_fiscal_settings

cgitb.enable()
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print('Content-Type: text/html; charset=utf-8\n')

TEMPLATE_HEADER = 'temp/header.txt'
TEMPLATE_FOOTER = 'temp/footer.txt'

def read_template(path):
    try:
        with open(path, encoding='utf-8') as f:
            return f.read()
    except:
        return f'<!-- {path} が読み込めませんでした -->'

def h(s):
    return html.escape(str(s) if s is not None else '')

def month_options(selected):
    buf = []
    for m in range(1, 13):
        sel = 'selected' if m == selected else ''
        buf.append(f'<option value="{m}" {sel}>{m}月</option>')
    return ''.join(buf)

header = read_template(TEMPLATE_HEADER)
footer = read_template(TEMPLATE_FOOTER)

zen = fetch_latest_row(FINANCE_DB_PATH, 'zen_finance', prefixes=('zu','zk','ze','zg'))
yos = fetch_latest_row(FINANCE_DB_PATH, 'yosan_budget', prefixes=('yu','yk','ye','yg'))
hon = fetch_latest_row(THISYEAR_DB_PATH, 'hon_finance', prefixes=('hu','hk','he','hg'))
cfg = get_fiscal_settings()

hon_nendo = (hon['nendo'] if hon and 'nendo' in hon.keys() else '') or ''
zen_nendo = (zen['nendo'] if zen and 'nendo' in zen.keys() else '') or ''
yos_nendo = (yos['nendo'] if yos and 'nendo' in yos.keys() else '') or ''

print(header)
print(f'''
<div class="container py-4">
  <h2 class="mb-3">初期設定・年度切替・バックアップ</h2>
  <p class="text-muted">会社ごとの会計年度に合わせて初期設定を行い、そのまま年度切替とバックアップまで進められるページです。</p>

  <div class="row g-3 mb-4">
    <div class="col-md-3"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">開始月</div><div class="fs-5">{h(cfg['start_month'])}月</div></div></div>
    <div class="col-md-3"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">最終月</div><div class="fs-5">{h(cfg['end_month'])}月</div></div></div>
    <div class="col-md-3"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">決算月</div><div class="fs-5">{h(cfg['closing_month'])}月</div></div></div>
    <div class="col-md-3"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">年度並び</div><div class="fs-6">{h(str(cfg['start_month']) + '月開始 / ' + str(cfg['end_month']) + '月終了')}</div></div></div>
  </div>

  <div class="card mb-4">
    <div class="card-header">A. 初期設定</div>
    <div class="card-body">
      <p class="text-muted">導入先ごとに会計年度の開始月・最終月・決算月を設定します。月の表示順には開始月が使われます。</p>
      <form method="post" action="settings_save.py">
        <input type="hidden" name="return_to" value="year_rollover.py">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">開始月</label>
            <select name="start_month" class="form-select">{month_options(cfg['start_month'])}</select>
          </div>
          <div class="col-md-4">
            <label class="form-label">最終月</label>
            <select name="end_month" class="form-select">{month_options(cfg['end_month'])}</select>
          </div>
          <div class="col-md-4">
            <label class="form-label">決算月</label>
            <select name="closing_month" class="form-select">{month_options(cfg['closing_month'])}</select>
          </div>
        </div>
        <div class="form-text mt-2">例：4月開始 / 3月終了 / 3月決算 の会社、1月開始 / 12月終了 / 12月決算 の会社、どちらにも対応できます。</div>
        <div class="mt-3 d-flex gap-2 flex-wrap">
          <button type="submit" class="btn btn-outline-primary">初期設定を保存</button>
          <a href="settings_page.py" class="btn btn-outline-secondary">設定画面だけ開く</a>
        </div>
      </form>
    </div>
  </div>

  <div class="row g-3 mb-4">
    <div class="col-md-4"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">現在の前年</div><div class="fs-5">{h(zen_nendo or '未設定')}</div></div></div>
    <div class="col-md-4"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">現在の予算</div><div class="fs-5">{h(yos_nendo or '未設定')}</div></div></div>
    <div class="col-md-4"><div class="border rounded p-3 bg-white h-100"><div class="small text-muted">現在の本年</div><div class="fs-5">{h(hon_nendo or '未設定')}</div></div></div>
  </div>

  <div class="alert alert-warning">
    <b>動作内容</b><br>
    1. まず現在の前年・予算・本年をバックアップ保存します。<br>
    2. 本年実績を新しい前年実績として登録します。<br>
    3. 新しい本年は空の状態で開始できます。<br>
    4. 必要なら最新の予算も新年度用に複製できます。
  </div>

  <div class="card mb-4">
    <div class="card-header">B. 現在の状態をバックアップだけする</div>
    <div class="card-body">
      <form method="post" action="year_rollover_exec.py">
        <input type="hidden" name="mode" value="backup_only">
        <div class="mb-3">
          <label class="form-label">バックアップ名</label>
          <input type="text" name="archive_label" class="form-control" value="{h(hon_nendo or zen_nendo or '年度バックアップ')}" required>
        </div>
        <div class="mb-3">
          <label class="form-label">メモ</label>
          <input type="text" name="note" class="form-control" value="例：2025/4〜2026/3 の締め保存">
        </div>
        <button type="submit" class="btn btn-outline-primary">バックアップ実行</button>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="card-header">C. 新年度へ切り替える</div>
    <div class="card-body">
      <form method="post" action="year_rollover_exec.py">
        <input type="hidden" name="mode" value="rollover">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">バックアップ名</label>
            <input type="text" name="archive_label" class="form-control" value="{h(hon_nendo or '年度切替前バックアップ')}" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">メモ</label>
            <input type="text" name="note" class="form-control" value="例：年度切替前の自動保存">
          </div>
          <div class="col-md-6">
            <label class="form-label">移行先の前年年度名</label>
            <input type="text" name="new_prev_nendo" class="form-control" value="{h(hon_nendo)}" placeholder="例：2025/4〜2026/3">
            <div class="form-text">現在の本年実績を、この年度名で前年実績へ保存します。</div>
          </div>
          <div class="col-md-6">
            <label class="form-label">新しい本年度名</label>
            <input type="text" name="new_current_nendo" class="form-control" value="" placeholder="例：2026/4〜2027/3">
            <div class="form-text">切替後の本年入力画面に表示される年度名です。</div>
          </div>
        </div>
        <div class="form-check mt-3">
          <input class="form-check-input" type="checkbox" name="create_blank_current" value="1" checked id="chk1">
          <label class="form-check-label" for="chk1">新しい本年データを空の状態で作成する</label>
        </div>
        <div class="form-check mt-2">
          <input class="form-check-input" type="checkbox" name="copy_budget" value="1" id="chk2">
          <label class="form-check-label" for="chk2">最新の予算を新年度用に複製する</label>
        </div>
        <div class="mt-4 d-flex gap-2 flex-wrap">
          <button type="submit" class="btn btn-primary">年度切替を実行</button>
          <a href="index.html" class="btn btn-secondary">戻る</a>
          <a href="year_archive_list.py" class="btn btn-outline-dark">バックアップ一覧</a>
        </div>
      </form>
    </div>
  </div>
</div>
''')
print(footer)
