"""
Builds docs/manual/manual.html from the content below. The PDF is printed from it with
Chromium (docs/manual/print_pdf.js). Screenshots live in docs/manual/img (demo school data).

    python3 docs/manual/build_manual.py && node docs/manual/print_pdf.js
"""
import html
from pathlib import Path

HERE = Path(__file__).parent
fig_no = 0


def esc(s):
    return html.escape(s, quote=False)


def md(s):
    """Tiny inline markup: **bold**, `code`."""
    out, bold, code = [], False, False
    i = 0
    while i < len(s):
        if s.startswith('**', i):
            out.append('</strong>' if bold else '<strong>'); bold = not bold; i += 2
        elif s[i] == '`':
            out.append('</code>' if code else '<code>'); code = not code; i += 1
        else:
            out.append(esc(s[i])); i += 1
    return ''.join(out)


def P(t): return f'<p>{md(t)}</p>'
def H(t): return f'<h3>{md(t)}</h3>'
def STEPS(*items): return '<ol class="steps">' + ''.join(f'<li>{md(i)}</li>' for i in items) + '</ol>'
def LIST(*items): return '<ul>' + ''.join(f'<li>{md(i)}</li>' for i in items) + '</ul>'
def TIP(t): return f'<div class="box tip"><b>Tip</b> {md(t)}</div>'
def NOTE(t): return f'<div class="box note"><b>Important</b> {md(t)}</div>'
def TABLE(head, *rows):
    h = ''.join(f'<th>{md(c)}</th>' for c in head)
    b = ''.join('<tr>' + ''.join(f'<td>{md(c)}</td>' for c in r) + '</tr>' for r in rows)
    return f'<table class="grid"><thead><tr>{h}</tr></thead><tbody>{b}</tbody></table>'


CONTENT_MM = 180  # A4 width minus margins
MAX_MM = 225      # tallest picture that still fits on a page with its caption


def IMG(name, caption, crop=None):
    """Full-width screenshot; taller ones are cut to `crop` mm (top part kept) so they stay readable."""
    global fig_no
    fig_no += 1
    from PIL import Image
    src = HERE / 'img' / f'{name}.jpg'
    im = Image.open(src)
    limit = min(crop or MAX_MM, MAX_MM)
    max_px = int(im.width * limit / CONTENT_MM)
    rel = f'img/{name}.jpg'
    if im.height > max_px:
        out = HERE / 'img' / 'print' / f'{name}.jpg'
        out.parent.mkdir(exist_ok=True)
        im.crop((0, 0, im.width, max_px)).convert('RGB').save(out, quality=80)
        rel = f'img/print/{name}.jpg'
    return (f'<figure><img src="{rel}">'
            f'<figcaption>Figure {fig_no}. {md(caption)}</figcaption></figure>')


CHAPTERS = []


def chapter(title, intro, *sections):
    CHAPTERS.append((title, intro, sections))


def section(title, *blocks):
    return (title, blocks)


# --------------------------------------------------------------------------------------------
chapter('Introduction', 'What the School ERP does, who uses it and how to reach it.',
    section('What the system covers',
        P('School ERP is an online school management system. Each school gets its own web address and its own data; '
          'one school can never see another school\'s records. The Basic plan includes three modules:'),
        TABLE(['Module', 'What it is for'],
              ['**Academic**', 'Academic years, classes, streams, sections, subjects, teachers, bell schedules and timetables.'],
              ['**Students**', 'Admissions, guardians and siblings, documents, parent and student logins, import, promotion.'],
              ['**Fees**', 'Fee structures, dues, concessions, late fines, the fee counter, receipts, online payment, refunds, DCR and reports.']),
        P('Every screen and button is controlled by permissions. If you do not see a menu item, your role does not include it; '
          'ask your School Super Admin.'),
    ),
    section('Who uses it',
        TABLE(['User', 'Where they log in', 'What they do'],
              ['Platform Owner', '`admin.<domain>`', 'Creates schools, switches modules on and off, suspends schools.'],
              ['School Super Admin', '`<school>.<domain>`', 'Everything inside their school: branches, users, roles, settings, DCR time.'],
              ['Staff (accountant, office, teacher...)', '`<school>.<domain>`', 'What their role allows, only for the branches their role allows.'],
              ['Parent / Student', '`<school>.<domain>`', 'The portal: profile, timetable, fees, receipts and online payment.']),
    ),
    section('Addresses',
        P('Each school has its own address, for example `https://abc.example.in` for ABC Public School. The Platform Owner '
          'panel is at `https://admin.example.in`. On a local test machine the addresses are `http://abc.erp.localhost` and '
          '`http://admin.erp.localhost`.'),
        P('Use a recent Chrome, Edge or Firefox. The system works on phones and tablets too; printing (receipts, DCR, '
          'timetables) works best from a computer.'),
    ),
    section('About the pictures',
        P('The screenshots in this manual come from the demo school "ABC Public School" with sample students and payments. '
          'Your school\'s names, amounts and numbers will be different.'),
    ),
)

chapter('Getting started', 'Logging in, your profile, the dashboard and moving around.',
    section('Logging in',
        IMG('s-login', 'The school login page.', crop=90),
        STEPS('Open your school\'s address in the browser.',
              'Type your **username, email or phone** in the first box and your password in the second.',
              'Click **Log in**. Parents use their mobile number; students use their student ID.',
              'The first time, or after a password reset, you are asked to choose a new password.'),
        NOTE('After 10 wrong passwords in a row the account is locked for safety. A user with permission to edit users can '
             'unlock it. School Super Admins are never locked out, but they too are slowed down after 5 tries a minute.'),
        P('**Forgot your password?** Click *Forgot password?* on the login page and enter your email. You receive a link to set '
          'a new password. If you have no email in the system, ask your administrator to reset it.'),
    ),
    section('The dashboard and the menu',
        IMG('a-dashboard', 'The school dashboard with the fee tiles.'),
        P('The left menu shows only the modules your school has and only the screens you may use. Click a module (for example '
          '**Fees**) to open its sub-menu.'),
        P('The dashboard shows tiles for your work: your collection today, total collected today, overdue fees, fees due in '
          'the next 7 days, and items waiting for your approval (concessions, refunds). Click a tile to open the list behind it.'),
        TIP('Schools with more than one branch see a **branch switcher** in the top bar. Choosing a branch narrows every list '
            'and report to it. "All branches" appears only if you may see more than one.'),
    ),
    section('My profile and two-factor login',
        IMG('a-profile', 'My profile: name, email, phone, password and two-factor authentication.', crop=120),
        STEPS('Click your name in the top-right corner and choose **My profile**.',
              'Change your name, email or phone and click **Save**.',
              'Use **Change password** to set a new password (you need the current one).',
              'To protect your account, turn on **Two-factor authentication**: scan the QR code with Google Authenticator, '
              'Microsoft Authenticator or Authy and type the 6-digit code. Save the 8 recovery codes in a safe place.'),
        TIP('If you lose your phone, log in with one of the recovery codes, or ask a user with permission to edit users to turn '
            'two-factor off for you.'),
    ),
)

chapter('Platform Owner', 'For the company running the service: creating and managing schools.',
    section('Logging in to the platform panel',
        IMG('p-login', 'Platform Owner login.', crop=80),
        P('Open `admin.<domain>`, enter your email and password, then the 6-digit code from your authenticator app. '
          'Two-factor login is always required for the Platform Owner.'),
    ),
    section('Dashboard and schools',
        IMG('p-dashboard', 'Platform dashboard: schools by status and module renewals due.', crop=90),
        IMG('p-schools', 'All schools.', crop=80),
        P('The dashboard counts schools by status (trial, active, suspended, cancelled) and lists modules expiring in the next '
          '30 days. **Schools** lists every school with its address, plan and status.'),
    ),
    section('Creating a school',
        IMG('p-school-create', 'New school: name, code, address (subdomain), main branch and its School Super Admin.'),
        STEPS('Click **New school**.',
              'Enter the school name and a short **code** (used in student IDs and receipt numbers, e.g. `ABC`).',
              'Choose the **subdomain**: the school\'s address will be `<subdomain>.<domain>`. It cannot be changed later.',
              'Fill in the main branch and the **School Super Admin** login (name, username, email, password).',
              'Choose the plan and status (trial or active) and click **Create**.',
              'Give the School Super Admin their login. They are asked to change the password at the first login.'),
        NOTE('The school code and subdomain cannot be changed after creation, because IDs, links and bookmarks use them.'),
    ),
    section('Modules, expiry and suspension',
        IMG('p-school-show', 'A school: details, modules with their status and expiry, suspend or activate.'),
        P('Open a school to switch modules on or off, set trial or expiry dates, and suspend or re-activate the school. A '
          'suspended school sees a message instead of its screens; its data is kept.'),
    ),
)

chapter('School administration', 'For the School Super Admin and staff with administration permissions.',
    section('Branches',
        IMG('c-branches', 'Branches of the school.', crop=70),
        P('**Administration > Branches** lists the school\'s branches. Add a branch with its name, code, address and contact '
          'details. The main branch cannot be deleted. Users are given access to one or more branches.'),
    ),
    section('Users',
        IMG('c-users', 'Users with their roles, branches and status.', crop=80),
        IMG('c-user-create', 'Adding a user: login, roles and branches.'),
        STEPS('Open **Administration > Users** and click **New user**.',
              'Enter name, username, email and phone, and a first password (the user must change it at first login).',
              'Tick the user\'s **roles** and the **branches** they work in.',
              'Tick **Teaching staff** for teachers so they can be assigned to classes and subjects.',
              'Click **Save**.'),
        P('To stop someone from logging in, set the status to **inactive**. If a teacher still holds classes or timetable '
          'periods, the system lists them first so you can hand them over.'),
    ),
    section('Roles and permissions',
        IMG('c-roles', 'Roles with their data scope and number of users.', crop=70),
        IMG('c-role-edit', 'Editing a role: the permission grid and the data scope.'),
        P('A role is a set of permissions. Each role also has a **data scope** that decides which records its users see:'),
        TABLE(['Data scope', 'Users see'],
              ['All branches', 'Records of every branch of the school.'],
              ['Assigned branches', 'Only records of the branches given to the user.'],
              ['Own records', 'Only their own: a teacher sees the classes they teach; a parent sees their children.']),
        STEPS('Open **Roles** and click **New role** (or Edit).',
              'Name the role, choose the data scope, and tick the permissions in the grid. You can only give permissions you '
              'have yourself.',
              'Click **Save**. Users with this role get the change at their next page.'),
        TIP('Useful roles: **Accountant** (fees.view, fees.collect, fees.close_day), **Office** (students.view, '
            'students.create, students.edit), **Teacher** (students.view, academic.view, timetable.view, own records).'),
        NOTE('The roles **School Super Admin**, **Parent** and **Student** are system roles and cannot be changed.'),
    ),
    section('Settings',
        IMG('c-settings', 'School settings: general, academic, fees, notifications.'),
        P('**Settings** holds the school\'s options in groups. A multi-branch school can override some values for one branch.'),
        LIST('**General**: academic year start month, letterhead text for receipts and print-outs, working days.',
             '**Fees**: receipt footer, using student credit automatically, mid-year admission rule, Razorpay keys, convenience fee.',
             '**Fees: DCR time**: the time every branch\'s DCR closes each day (School Super Admin only).',
             '**Notifications**: email reminders and the WhatsApp reminder text.'),
        IMG('c-settings-dcr', 'The DCR time, set by the School Super Admin.', crop=60),
    ),
    section('ID formats',
        IMG('c-id-formats', 'Number formats for student IDs, admission numbers, receipts, refunds and DCRs.', crop=90),
        P('Each kind of number (student ID, admission number, staff ID, receipt, refund voucher, DCR) has a pattern such as '
          '`{PREFIX}-R{YY}-{SEQ}` and a next number. Yearly series restart when the academic year starts. Every fee account has '
          'its own receipt series. The next number can only go up, so numbers already given out never repeat.'),
    ),
    section('Custom fields and the activity log',
        IMG('c-custom-fields', 'Custom fields for students, guardians, classes, sections and subjects.', crop=60),
        P('**Custom fields** add your own boxes to forms (for example "House" or "Transport route"). They can be required, '
          'appear in the student list filters and on the profile.'),
        IMG('c-activity', 'The activity log: who changed what and when.', crop=110),
        P('**Activity log** records every create, change and delete, logins, denied access and receipt cancellations, with '
          'the user, time and the old and new values.'),
    ),
)

chapter('Academic', 'Setting up the year, classes, subjects, teachers and timetable.',
    section('Overview and the setup wizard',
        IMG('ac-overview', 'Academic overview for the current year.', crop=80),
        IMG('ac-setup', 'Setup wizard: start from a board template.', crop=110),
        P('The **setup wizard** (School Super Admin) creates a year with classes, wings and common subjects from a board '
          'template (CBSE, State board...). Everything it creates can be edited afterwards.'),
    ),
    section('Academic years',
        IMG('ac-years', 'Academic years: upcoming, active (current) and closed.', crop=60),
        P('Create a year with its start and end dates and mark one as **current**. A **closed** year becomes read-only '
          'everywhere: nothing of that year can be changed.'),
    ),
    section('Classes, streams and sections',
        IMG('ac-classes', 'Classes in promotion order, with their next class and streams.', crop=80),
        IMG('ac-sections', 'Sections of the year with capacity, room and class teacher.', crop=90),
        STEPS('Add classes in order (Class 1, Class 2...) and set each class\'s **next class** for promotion.',
              'Tick **has streams** for classes like 11 and 12, and create the streams (Science, Commerce...).',
              'Add sections for the year: A, B, C... with capacity, room and class teacher. Use **bulk add** to create many at once.'),
    ),
    section('Subjects and class subjects',
        IMG('ac-subjects', 'The school\'s subjects; paste a list to add many.', crop=80),
        IMG('ac-class-subjects', 'Subjects of each class with periods per week and elective groups.', crop=80),
        P('Make the school\'s subject list once, then choose which subjects each class studies, how many periods a week, and '
          'elective groups (for example "Second language: Hindi or Telugu").'),
    ),
    section('Teachers, bell schedules and timetable',
        IMG('ac-teachers', 'Teacher assignment: class teachers and subject teachers.', crop=70),
        IMG('ac-bells', 'Bell schedules: periods and breaks for each working day.', crop=90),
        IMG('ac-timetable', 'Timetable of a section.', crop=80),
        STEPS('Assign a class teacher to each section and a teacher to each subject of each section.',
              'Create a bell schedule with periods and breaks and attach it to classes.',
              'Open **Timetable**, choose a section and fill each period with a subject. The system warns about teacher '
              'clashes (even across branches and schedules), room clashes and subjects over their weekly target.',
              'Print a section\'s or teacher\'s timetable with **Print** (or save it as PDF).'),
        P('Teachers see their own timetable and classes under **My classes**. The **Free teachers** view shows who is free in '
          'a period, useful for substitutions.'),
    ),
    section('Copy to next year and import',
        IMG('ac-copy', 'Copy the year\'s setup (sections, subjects, teachers, timetable) to the next year.', crop=90),
        P('At the end of the year, **Copy to next year** copies what you choose into the new year. A preview shows exactly what '
          'will be created before you confirm.'),
        IMG('ac-import', 'Import classes, sections or subjects from Excel or CSV.', crop=70),
        P('**Import** reads classes, sections or subjects from an Excel/CSV file. Download the template, fill it, upload it, '
          'check the preview (rows with errors are listed and can be downloaded as an error file) and click **Import**.'),
    ),
)

chapter('Students', 'Admissions, the student list, profiles, imports and promotion.',
    section('The student list',
        IMG('st-list', 'Students with filters, search, bulk actions and column picker.', crop=120),
        P('Search by name, student ID, admission number or guardian phone; filter by year, class, section, status, gender and '
          'custom fields. Tick students to **change section**, **create logins** or **export** them. **Columns** chooses which '
          'columns you see (remembered in your browser).'),
    ),
    section('New admission',
        IMG('st-admission', 'The admission form: student, guardians, custom fields, documents and logins.', crop=210),
        STEPS('Click **New admission**.',
              '**Student**: name, gender, date of birth, Aadhaar (stored encrypted), address, previous school.',
              '**Class**: choose the section; the roll number is filled in.',
              '**Guardians**: type a phone number to find an existing guardian (siblings share guardians) or add new ones; choose '
              'the primary guardian.',
              '**Documents and photo**: upload birth certificate, TC and others.',
              '**Logins**: tick to create a parent login (username = mobile number) and/or a student login (username = student ID).',
              'Click **Admit**. The student ID and admission number are given automatically, and the fee dues of the class are created.'),
        TIP('After saving, the new logins and passwords are shown once with a WhatsApp button to send them to the parent.'),
    ),
    section('The student profile',
        IMG('st-profile', 'Student profile: overview, status and tabs.', crop=110),
        P('The profile has tabs: **Overview**, **Guardians & siblings**, **Class history**, **Documents**, **Login**, '
          '**Activity log** and **Fees** (opens the student\'s fees page).'),
        IMG('st-guardians', 'Guardians and siblings.', crop=90),
        IMG('st-history', 'Class history: every year\'s class and section; change section during the year.', crop=90),
        P('**Change status** (left, transferred, suspended, active again) is on the profile. When a student leaves, their '
          'future unpaid fees are cancelled; past dues stay. Their logins are switched off.'),
        IMG('st-login', 'Login tab: create or reset the parent and student logins.', crop=90),
    ),
    section('Bulk import',
        IMG('st-import', 'Bulk import of students from Excel or CSV.', crop=80),
        STEPS('Download the template and fill one row per student.',
              'Upload it. The preview shows each row with its problems (missing class, wrong date, duplicate Aadhaar...).',
              'Download the **error file** to fix rows, or click **Import** for the good rows.',
              'Large files (over 300 rows) are imported in the background; the page shows the progress.'),
    ),
    section('Promotion and elective choices',
        IMG('st-promotion', 'Promotion: from year, to year, section and each student\'s decision.', crop=80),
        STEPS('Choose the year to promote from and to, and the section.',
              'For each student choose **promote**, **detain** or **leave**; the target section and roll numbers are filled in.',
              'Click **Promote**. Students of the final class are marked passed out.',
              'Unpaid fees of the old year move into the new year automatically as "Previous year dues".'),
        TIP('A promotion can be **undone** from the same screen as long as no fees have been paid in the new year.'),
        IMG('st-electives', 'Elective choices per student.', crop=70),
    ),
)

chapter('Fees setup', 'Fee heads, accounts, structures, concessions and fine rules. Done once a year.',
    section('Fee heads',
        IMG('f-heads', 'Fee heads with their priority, type and account.', crop=90),
        IMG('f-head-create', 'A fee head: type, priority, refundable, concession and fee account.', crop=110),
        P('Fee heads are the school\'s own list: Tuition, Admission, Annual charges, Books, Transport, Caution deposit...'),
        LIST('**Recurring** heads are split across installments; **one-time** heads are charged once.',
             '**Priority**: lower is paid first when a payment does not cover everything (online payments).',
             '**Refundable**: can be refunded later (caution deposit).',
             '**Concessions may apply**: whether concessions reduce this head.',
             '**Fee account**: which account\'s receipt this head appears on.'),
    ),
    section('Fee accounts and bank / cash accounts',
        IMG('f-accounts', 'Fee accounts, which head belongs to which account, and the bank accounts and cash boxes.'),
        P('A **fee account** groups heads that are receipted separately, for example "School Trust" for tuition and "Society" '
          'for books and uniform. Each fee account has its own receipt number series and the name printed on its receipts.'),
        P('List the school\'s **bank accounts and cash boxes**, then link each fee account to one cash box and one bank account. '
          'Cash payments go to the cash box; card, UPI, transfers and cheques go to the bank account. Every receipt records where '
          'the money went, and the DCR shows how much to deposit in each account.'),
        STEPS('Add the cash box and bank accounts on the right (bank name, last 4 digits, IFSC).',
              'Add a fee account with its receipt prefix (for example `SOC`) and the title printed on its receipts.',
              'In **Which account each head belongs to**, choose the account for each head and click **Save assignments**.'),
        TIP('When one payment covers heads of two accounts, the system makes two receipts, one per account, and prints them '
            'together on separate pages.'),
    ),
    section('Fee structures',
        IMG('f-structures', 'Fee structures of the year: one per class (and stream).', crop=70),
        IMG('f-structure-create', 'New structure: year, class, stream and installment plan.', crop=110),
        IMG('f-grid', 'The structure grid: heads down the side, installments across the top.'),
        STEPS('Click **New structure** and choose year, class (and stream), the plan (monthly, quarterly, term-wise, annual or '
              'custom) and the due day.',
              'In the grid, type each head\'s **yearly** amount. Recurring heads are split equally across installments; one-time '
              'heads go into the installment you choose. You can also type each cell yourself.',
              'Rename installments, change due dates, add or remove an installment, then **Save**.',
              'Click **Publish**. A preview shows how many students and due lines will be created. Publishing creates the dues.'),
        NOTE('After publishing, changes affect only **unpaid future** installments. Paid and past lines stay as they are.'),
        IMG('f-copy', 'Copy a structure to other classes or the next year with an increase.', crop=100),
        P('**Copy** copies a structure to other classes or to the next year, optionally raising amounts by a percentage '
          '(rounded to the nearest ₹10). Copies start as drafts.'),
    ),
    section('Concessions',
        IMG('f-concessions', 'Concessions: approvals, types and giving a concession.'),
        P('Concession types are the school\'s own list (Sibling, Staff ward, Merit, RTE, Need-based...), each a **percent** or an '
          '**amount**, for chosen heads, with or without approval and a document.'),
        STEPS('Under **Concession types**, add the types your school uses.',
              'In **Give a concession**, enter the student ID, choose the type and year (and another value if needed), attach a '
              'document if required, and save.',
              'If the type needs approval, a user with *Approve concessions* approves or rejects it with a remark.',
              'Approved concessions reduce only the lines nothing has been paid on. Paid lines are never changed.'),
        TIP('**Sibling suggestions** lists students who share a guardian with another student and have no sibling concession yet.'),
    ),
    section('Late fine rules',
        IMG('f-fines', 'Fine rules: per day, fixed or slab, with grace days and a cap.', crop=120),
        LIST('**Per day**: e.g. ₹10 a day after 7 grace days.',
             '**Fixed**: one amount once the grace days pass.',
             '**Slab**: different amounts by days late, e.g. `1-15:50`, `16-30:150`, `31-:300`.',
             'A rule can apply to all or chosen heads and classes, with a maximum fine per line.'),
        P('Fines are recalculated every night. They stop growing once a line is paid. Users with *Waive fines* can waive a fine '
          '(fully or partly) with a reason from the student\'s fees page; every waiver is logged.'),
    ),
)

chapter('Collecting fees', 'The daily work of the fee counter.',
    section('Finding the student',
        IMG('f-collect-search', 'Collect Fees: search by name, student ID, admission number or guardian phone.', crop=70),
        P('Open **Fees > Collect Fees** and search. Siblings appear together, so a parent paying for two children is quick; each '
          'child gets their own receipt.'),
    ),
    section('The counter screen',
        IMG('f-collect', 'The counter: dues with fee, fine and balance; Pay now boxes; amount, mode and receipt date.'),
        STEPS('Every unpaid line is listed, oldest first; overdue lines are red.',
              '**You decide what is paid**: tick a line to pay it in full, or type an amount in its **Pay now** box. A line\'s fine '
              'is paid before its fee. **Spread amount oldest first** fills the boxes from the amount received.',
              'Check the **Amount received**. Anything above what you applied becomes the student\'s **credit** (advance). To take '
              'money with nothing applied, tick **Advance**.',
              'If the student has credit, tick **Use credit first**.',
              'Choose the **mode**: cash, UPI, card, bank transfer, cheque (number, date and bank needed) or scholarship (payer name).',
              'Check the **Receipt date** shown, then click **Save receipt**.'),
        NOTE('The receipt date is given by the system. After the DCR time, or once your branch\'s DCR is closed, receipts are '
             'dated the **next day**, and the counter says so.'),
    ),
    section('The receipt',
        IMG('f-receipt', 'Receipts of one payment (one per fee account) with the collector\'s details.'),
        LIST('The heading shows the fee account\'s title, the receipt number and date.',
             'Each line shows the fee, the due date, the amount and the fine paid.',
             'At the bottom: amount and mode, reference or cheque, the account deposited to and the balance still due.',
             '**Collected by**: name, username, role and phone of the person who took the money, the time it was received, who '
             'printed it, and a signature line.'),
        P('Use **A4 / A5 size** and **Print / PDF** to print, or **WhatsApp** to send the receipt details to the parent.'),
    ),
    section('Cancelling a receipt or a bounced cheque',
        P('On the receipt, a user with *Cancel receipts* gives a reason and clicks **Cancel receipt**. The receipt stays (marked '
          'cancelled), its payments are taken off the dues, and any credit it added or used is reversed.'),
        P('For a cheque, **Cheque bounced** does the same and can add a bounce charge to the student\'s dues.'),
        NOTE('Receipts of a **closed DCR** cannot be cancelled. A bounced cheque can still be marked at any time. Receipts are never '
             'deleted.'),
    ),
    section('Receipts list and a student\'s fees',
        IMG('f-receipts', 'All receipts with search and filters.', crop=90),
        IMG('f-student', 'A student\'s fees: every due line, receipts, credit ledger, concessions and one-off charges.', crop=140),
        P('The student fees page (also the **Fees** tab of the profile) shows every due line with concession, fine, paid and '
          'balance, the receipts, the credit ledger and concessions. Users with *Add one-off charges* add a charge (lost ID card, '
          'trip) with a reason.'),
    ),
    section('My day close',
        IMG('f-my-day', 'My day close: your own collection by mode for a day.', crop=90),
        P('Each collector sees their own receipts and totals by mode for the day, to hand over cash.'),
    ),
)

chapter('DCR - Day Challan Receipt', 'Closing each branch\'s collection day.',
    section('How the DCR works',
        P('Every branch closes its collection day with a **DCR (Day Challan Receipt)**:'),
        LIST('**Automatically** at the DCR time set by the School Super Admin (Settings > Fees: DCR time), for every branch.',
             '**Earlier**, by branch accounts: users with the permission *Close the day (DCR) for their branches* close their own branch.',
             'Each DCR gets a number (for example `ABC-DCR26-0001`) and keeps the day\'s totals.',
             'After a branch\'s DCR is closed, **new receipts of that branch are dated the next day**. Other branches keep their own day.',
             'Receipts of a closed DCR cannot be cancelled.'),
    ),
    section('Closing a DCR',
        IMG('f-dcr', 'DCR screen: each branch\'s open day and the closed DCRs.'),
        STEPS('Open **Fees > DCR (Day Challan)**.',
              'Each of your branches shows its open day, receipts and total.',
              'Click **Close DCR for <date>** and confirm. You are taken to the printable DCR.'),
    ),
    section('The printed DCR',
        IMG('f-dcr-print', 'A printed DCR.'),
        LIST('Totals by **mode** (cash, UPI, card, cheque, online), by **collector** and by **account to deposit in**.',
             'Every receipt of the day with student, account, mode, reference, collector, amount and status (cancelled in red).',
             'Refunds paid that day (money out).',
             'Signature lines for **Prepared by**, **Cashier** and **Accounts / Principal**.'),
        TIP('Print the DCR every evening and file it with the bank deposit slips.'),
    ),
)

chapter('Unpaid fees, refunds, online payments and carry forward', 'Follow-up work.',
    section('Unpaid & reminders',
        IMG('f-unpaid', 'Unpaid list with filters and one-click WhatsApp per guardian.'),
        STEPS('Filter by class, section, installment, days overdue or amount.',
              'Click a guardian\'s **WhatsApp** button: WhatsApp opens with the amount, due date and payment link filled in.',
              'Or tick many students and click **WhatsApp ticked** (a list of links to open one after another) or **Email ticked**.'),
        P('Every reminder is recorded, and the **Reminded** column shows how many times and when. Automatic email reminders '
          'before and after the due date can be switched on in Settings > Notifications.'),
    ),
    section('Refunds',
        IMG('f-refunds', 'Refunds: request, approval by another person, payout.', crop=100),
        STEPS('Find the student and choose what to refund: a **refundable head** (caution deposit), **credit**, or an **online payment**.',
              'Enter amount, mode and reason and click **Request refund**.',
              'Another user with *Approve refunds* approves or rejects it. The person who asked can never approve it.',
              'Click **Pay out**: a refund voucher number is given, and credit or the online payment is updated.'),
    ),
    section('Online payments (Razorpay)',
        IMG('f-online', 'Online payments with their Razorpay order and payment IDs.', crop=70),
        P('Parents pay from the portal through the school\'s own Razorpay account; the money goes straight to the school. The '
          'receipt is made automatically when Razorpay confirms the payment, and a check every 15 minutes settles any payment '
          'whose confirmation was missed. One payment can never make two receipts.'),
        P('Set up: enter the Razorpay key ID, key secret and webhook secret in Fee Settings, and add the webhook address shown '
          'in the setup guide in the Razorpay dashboard. Start with Razorpay **test keys**.'),
    ),
    section('Carry forward',
        IMG('f-carry', 'Carry forward unpaid dues into the next year.', crop=70),
        P('Unpaid dues of a year become one **"Previous year dues"** line in the next year. This happens automatically when a '
          'student is promoted, or here for the whole school. Students who left keep their dues in the old year and are listed '
          'under "Former students with dues".'),
    ),
)

chapter('Reports', 'All fee reports can be printed, saved as PDF or exported to Excel.',
    section('Choosing a report',
        P('Open **Fees > Fee Reports**, choose the report tab, set the dates or filters and click **Show**. Use **Excel** to '
          'download it, or **Print / PDF**. Every report shows only the branches you may see.'),
        TABLE(['Report', 'Shows'],
              ['Day collection', 'Every receipt and refund of one day, by collector and mode, with cancellations.'],
              ['Day-wise collection', 'One row per day: receipts, each mode, total, cancelled, refunds and net.'],
              ['Staff / day / head', 'Collected by, day and head, with a column for cash, UPI, card, cheque, online.'],
              ['Account-wise', 'Each fee account and where its money was deposited, by mode.'],
              ['Collection summary', 'Totals by mode, head and class for a date range.'],
              ['Dues and defaulters', 'Who owes what, with days overdue.'],
              ['Student ledger', 'Every due, receipt, credit and refund of one student.'],
              ['Concessions, Fines, Online payments, Refunds, Carry forward', 'As named.']),
    ),
    section('Examples',
        IMG('r-daywise', 'Day-wise collection.', crop=90),
        IMG('r-staffwise', 'Staff / day / head-wise collection with a column per mode.', crop=120),
        IMG('r-accounts', 'Account-wise collection.', crop=80),
        IMG('r-dues', 'Dues and defaulters.', crop=110),
        IMG('r-ledger', 'Student ledger.', crop=110),
    ),
)

chapter('Parent and student portal', 'What parents and students see.',
    section('Logging in',
        P('Parents log in at the school\'s address with their **mobile number**; students with their **student ID**. The first '
          'password is given by the school, and they must change it at the first login.'),
    ),
    section('The portal',
        IMG('pt-home', 'Portal home: the parent\'s children.', crop=70),
        IMG('pt-student', 'A child\'s profile and timetable.', crop=110),
        IMG('pt-fees', 'Fees: dues for each child, receipts and Pay online.', crop=110),
        STEPS('Open **Fees** in the top bar.',
              'Tick the lines to pay for each child, or **Pay everything due**.',
              'Click **Pay online** and pay with UPI, card or net banking in the Razorpay window.',
              'The receipt appears at once and can be printed or saved as PDF.'),
        P('Students can see their fees but cannot pay; only parents can.'),
    ),
)

chapter('Checklists and help', 'Quick routines and answers to common questions.',
    section('Start of the year',
        STEPS('Create the new academic year (or copy the old one with **Copy to next year**).',
              'Check classes, sections, subjects and teachers; build the timetable.',
              'Copy last year\'s fee structures with an increase, check them and **publish**.',
              'Promote students; unpaid dues move to the new year automatically.',
              'Check concessions for the new year (sibling suggestions, RTE).'),
    ),
    section('Every day at the fee counter',
        STEPS('Collect fees; give every parent a printed or WhatsApp receipt.',
              'Before closing time, check **My day close** and hand over cash.',
              'Branch accounts close the **DCR** (or it closes automatically at the DCR time), print it and deposit the money.',
              'Follow up overdue fees from **Unpaid & reminders**.'),
    ),
    section('Common questions',
        TABLE(['Question', 'Answer'],
              ['I can\'t see a menu item.', 'Your role does not have that permission. Ask the School Super Admin.'],
              ['A student does not appear.', 'Check the branch switcher, the year and the status filter (left students are hidden).'],
              ['The receipt has tomorrow\'s date.', 'Today\'s DCR is closed (or the DCR time has passed). This is intended.'],
              ['I can\'t cancel a receipt.', 'Its DCR is closed. Correct it with a refund, or mark a cheque as bounced.'],
              ['A parent paid online but sees no receipt.', 'Wait 30 minutes; the 15-minute check settles it. Then see Online payments.'],
              ['The fee amount is wrong for a student.', 'Check concessions and the class structure; a one-off charge can be cancelled while unpaid.'],
              ['Account locked.', 'A user with permission to edit users sets it back to active.']),
    ),
    section('Glossary',
        TABLE(['Term', 'Meaning'],
              ['DCR', 'Day Challan Receipt: a branch\'s closed collection day with its number and totals.'],
              ['Due line', 'One fee head in one installment for one student.'],
              ['Credit', 'Money paid above the dues, kept for future fees or refunded.'],
              ['Fee account', 'A group of heads with its own receipts and receipt numbers.'],
              ['Data scope', 'Which branches\' records a role can see.'],
              ['Carry forward', 'Moving last year\'s unpaid balance into the new year.']),
    ),
)

# --------------------------------------------------------------------------------------------
CSS = """
@page { size: A4; margin: 16mm 15mm 18mm 15mm; }
* { box-sizing: border-box; }
body { font-family: 'Inter', 'Segoe UI', Arial, sans-serif; color: #1d273b; font-size: 10.5pt; line-height: 1.5; margin: 0; }
.cover { height: 260mm; display: flex; flex-direction: column; justify-content: center; page-break-after: always; }
.cover .band { background: #1d273b; color: #fff; padding: 22mm 18mm; border-radius: 6px; }
.cover h1 { font-size: 34pt; margin: 0 0 4mm; } .cover .sub { font-size: 14pt; opacity: .85; }
.cover .meta { margin-top: 14mm; color: #616876; font-size: 10pt; }
.cover img { width: 100%; margin-top: 10mm; border: 1px solid #dce1e7; border-radius: 4px; }
.toc { page-break-after: always; } .toc h2 { border: 0; }
.toc ol { padding-left: 6mm; } .toc li { margin: 1.6mm 0; } .toc li li { margin: .6mm 0; font-size: 9.5pt; color: #444; }
.toc a { color: inherit; text-decoration: none; }
h2 { font-size: 20pt; color: #1d273b; border-bottom: 3px solid #206bc4; padding-bottom: 2mm; margin: 0 0 3mm; page-break-before: always; }
.intro { color: #616876; font-size: 11pt; margin-bottom: 6mm; }
h3 { font-size: 13pt; color: #206bc4; margin: 7mm 0 2mm; page-break-after: avoid; }
p { margin: 1.8mm 0; }
figure { margin: 4mm 0 5mm; page-break-inside: avoid; text-align: center; }
figure img { width: 100%; border: 1px solid #c9d1db; border-radius: 3px; box-shadow: 0 1px 4px rgba(0,0,0,.12); }
figcaption { font-size: 8.8pt; color: #616876; margin-top: 1.5mm; font-style: italic; }
ol.steps { counter-reset: s; list-style: none; padding-left: 0; }
ol.steps li { counter-increment: s; position: relative; padding-left: 9mm; margin: 2mm 0; }
ol.steps li::before { content: counter(s); position: absolute; left: 0; top: .2mm; width: 6mm; height: 6mm; border-radius: 50%;
  background: #206bc4; color: #fff; font-size: 8.5pt; font-weight: 700; display: flex; align-items: center; justify-content: center; }
ul li { margin: 1.2mm 0; }
.box { border-radius: 4px; padding: 3mm 4mm; margin: 3mm 0; page-break-inside: avoid; }
.box b { display: inline-block; margin-right: 2mm; text-transform: uppercase; font-size: 8.5pt; letter-spacing: .04em; }
.tip { background: #eaf5ee; border-left: 4px solid #2fb344; } .tip b { color: #2fb344; }
.note { background: #fff4e5; border-left: 4px solid #f76707; } .note b { color: #f76707; }
table.grid { width: 100%; border-collapse: collapse; margin: 3mm 0; font-size: 9.5pt; page-break-inside: avoid; }
table.grid th { background: #f1f5f9; text-align: left; padding: 2mm; border-bottom: 2px solid #c9d1db; }
table.grid td { padding: 1.8mm 2mm; border-bottom: 1px solid #e6e7e9; vertical-align: top; }
code { background: #f1f5f9; padding: 0 1mm; border-radius: 2px; font-size: 9pt; }
"""


def build():
    toc, body = [], []
    for ci, (title, intro, sections) in enumerate(CHAPTERS, 1):
        cid = f'ch{ci}'
        subs = ''.join(f'<li><a href="#{cid}s{si}">{ci}.{si} {md(s[0])}</a></li>' for si, s in enumerate(sections, 1))
        toc.append(f'<li><a href="#{cid}"><b>{md(title)}</b></a><ol>{subs}</ol></li>')
        parts = [f'<h2 id="{cid}">{ci}. {md(title)}</h2><div class="intro">{md(intro)}</div>']
        for si, (stitle, blocks) in enumerate(sections, 1):
            parts.append(f'<h3 id="{cid}s{si}">{ci}.{si} {md(stitle)}</h3>' + ''.join(blocks))
        body.append(''.join(parts))

    cover = ('<div class="cover"><div class="band"><h1>School ERP</h1><div class="sub">User Manual</div>'
             '<div class="sub" style="font-size:11pt;margin-top:4mm">Academic · Students · Fees · DCR · Parent portal</div></div>'
             '<img src="img/a-dashboard.jpg"><div class="meta">For School Super Admins, office and accounts staff, teachers, '
             'parents and the Platform Owner. Screenshots show the demo school "ABC Public School".</div></div>')
    toc_html = '<div class="toc"><h2>Contents</h2><ol>' + ''.join(toc) + '</ol></div>'
    doc = (f'<!doctype html><html lang="en"><head><meta charset="utf-8"><title>School ERP - User Manual</title>'
           f'<style>{CSS}</style></head><body>{cover}{toc_html}{"".join(body)}</body></html>')
    (HERE / 'manual.html').write_text(doc, encoding='utf-8')
    print('manual.html written,', fig_no, 'figures,', len(CHAPTERS), 'chapters')


if __name__ == '__main__':
    build()
