<?php

function ensure_tax_forms_schema(mysqli $conn): void
{
    $query = "CREATE TABLE IF NOT EXISTS tax_details (
        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        org_id VARCHAR(50) NOT NULL,
        pan VARCHAR(10) DEFAULT NULL,
        tan VARCHAR(10) DEFAULT NULL,
        tds_circle VARCHAR(3) DEFAULT NULL,
        tds_ao_code VARCHAR(2) DEFAULT NULL,
        tds_ao_number VARCHAR(3) DEFAULT NULL,
        tds_ao_type VARCHAR(2) DEFAULT NULL,
        tax_payment_frequency VARCHAR(20) NOT NULL DEFAULT 'Monthly',
        deductor_type ENUM('employee','non-employee') NOT NULL DEFAULT 'employee',
        deductor_name VARCHAR(150) DEFAULT NULL,
        deductor_father_name VARCHAR(150) DEFAULT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_tax_org (org_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    $conn->query($query);
}

function tax_forms_org_context(mysqli $conn): array
{
    $result = $conn->query("SELECT * FROM organizations ORDER BY id DESC LIMIT 1");
    $row = $result ? $result->fetch_assoc() : null;

    return [
        'org_name' => $_SESSION['org_name'] ?? ($row['organisation_name'] ?? 'demo'),
        'org_id' => (string) ($_SESSION['org_id'] ?? ($row['organisation_id'] ?? ($row['id'] ?? '60066881652'))),
    ];
}

function tax_details_defaults(string $orgId): array
{
    return [
        'org_id' => $orgId,
        'pan' => '',
        'tan' => '',
        'tds_circle' => '',
        'tds_ao_code' => '',
        'tds_ao_number' => '',
        'tds_ao_type' => '',
        'tax_payment_frequency' => 'Monthly',
        'deductor_type' => 'employee',
        'deductor_name' => '',
        'deductor_father_name' => '',
    ];
}

function tax_details_get(mysqli $conn, string $orgId): array
{
    $defaults = tax_details_defaults($orgId);
    $stmt = $conn->prepare("SELECT * FROM tax_details WHERE org_id = ? LIMIT 1");
    if (!$stmt) {
        return $defaults;
    }

    $stmt->bind_param('s', $orgId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return $row ? array_merge($defaults, $row) : $defaults;
}

function tax_details_save(mysqli $conn, string $orgId, array $values): bool
{
    $stmt = $conn->prepare(
        "INSERT INTO tax_details
            (org_id, pan, tan, tds_circle, tds_ao_code, tds_ao_number, tds_ao_type, tax_payment_frequency, deductor_type, deductor_name, deductor_father_name)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
            pan = VALUES(pan),
            tan = VALUES(tan),
            tds_circle = VALUES(tds_circle),
            tds_ao_code = VALUES(tds_ao_code),
            tds_ao_number = VALUES(tds_ao_number),
            tds_ao_type = VALUES(tds_ao_type),
            tax_payment_frequency = VALUES(tax_payment_frequency),
            deductor_type = VALUES(deductor_type),
            deductor_name = VALUES(deductor_name),
            deductor_father_name = VALUES(deductor_father_name)"
    );

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param(
        'sssssssssss',
        $orgId,
        $values['pan'],
        $values['tan'],
        $values['tds_circle'],
        $values['tds_ao_code'],
        $values['tds_ao_number'],
        $values['tds_ao_type'],
        $values['tax_payment_frequency'],
        $values['deductor_type'],
        $values['deductor_name'],
        $values['deductor_father_name']
    );

    $ok = $stmt->execute();
    $stmt->close();

    return $ok;
}
