<?php
/**
 * Offering types - add and manage types of offerings (e.g. Tithes, General Offering) (finance or admin)
 */

$pageTitle = 'Offering types';
$currentPage = 'finance';

// Ensure is_personal column exists (for personal offerings e.g. tithes)
try {
    $pdo->query("SELECT is_personal FROM funds LIMIT 1");
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Unknown column') !== false) {
        $pdo->exec("ALTER TABLE funds ADD COLUMN is_personal TINYINT(1) DEFAULT 0");
    } else {
        throw $e;
    }
}
// Phase 5: ensure target columns exist
try {
    $pdo->query("SELECT target_amount, target_year FROM funds LIMIT 1");
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Unknown column') !== false) {
        $pdo->exec("ALTER TABLE funds ADD COLUMN target_amount DECIMAL(12,2) NULL");
        $pdo->exec("ALTER TABLE funds ADD COLUMN target_year SMALLINT NULL");
    } else {
        throw $e;
    }
}
// Roll-up: ensure parent_fund_id exists
try {
    $pdo->query("SELECT parent_fund_id FROM funds LIMIT 1");
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Unknown column') !== false) {
        $pdo->exec("ALTER TABLE funds ADD COLUMN parent_fund_id INT NULL");
    } else {
        throw $e;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['action'] ?? '';

    if ($postAction === 'add_fund') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '') ?: null;
        $isPersonal = !empty($_POST['is_personal']);
        $targetAmount = trim($_POST['target_amount'] ?? '') !== '' ? (float) $_POST['target_amount'] : null;
        $targetYear = trim($_POST['target_year'] ?? '') !== '' ? (int) $_POST['target_year'] : null;
        $parentFundId = trim($_POST['parent_fund_id'] ?? '') !== '' ? (int) $_POST['parent_fund_id'] : null;
        if ($name === '') {
            header('Location: ' . BASE_PATH . '/finance/funds?toast_error=' . urlencode('Fund name is required.'));
            exit;
        }
        if ($parentFundId !== null) {
            $check = $pdo->prepare('SELECT id FROM funds WHERE id = ? AND parent_fund_id IS NULL');
            $check->execute([$parentFundId]);
            if (!$check->fetch()) {
                $parentFundId = null;
            }
        }
        try {
            $pdo->prepare('INSERT INTO funds (name, description, is_personal, target_amount, target_year, parent_fund_id) VALUES (?, ?, ?, ?, ?, ?)')->execute([$name, $description, $isPersonal ? 1 : 0, $targetAmount, $targetYear, $parentFundId]);
        } catch (PDOException $e) {
            $pdo->prepare('INSERT INTO funds (name, description) VALUES (?, ?)')->execute([$name, $description]);
        }
        header('Location: ' . BASE_PATH . '/finance/funds?toast=' . urlencode('Fund added.'));
        exit;
    }

    if ($postAction === 'update_fund') {
        $id = (int) ($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '') ?: null;
        $isPersonal = !empty($_POST['is_personal']);
        $targetAmount = trim($_POST['target_amount'] ?? '') !== '' ? (float) $_POST['target_amount'] : null;
        $targetYear = trim($_POST['target_year'] ?? '') !== '' ? (int) $_POST['target_year'] : null;
        $parentFundId = trim($_POST['parent_fund_id'] ?? '') !== '' ? (int) $_POST['parent_fund_id'] : null;
        if ($id <= 0 || $name === '') {
            header('Location: ' . BASE_PATH . '/finance/funds?toast_error=' . urlencode('Invalid fund or name required.'));
            exit;
        }
        if ($parentFundId !== null) {
            if ($parentFundId === $id) {
                $parentFundId = null;
            } else {
                $check = $pdo->prepare('SELECT id FROM funds WHERE id = ? AND parent_fund_id IS NULL');
                $check->execute([$parentFundId]);
                if (!$check->fetch()) {
                    $parentFundId = null;
                }
            }
        }
        try {
            $pdo->prepare('UPDATE funds SET name = ?, description = ?, is_personal = ?, target_amount = ?, target_year = ?, parent_fund_id = ? WHERE id = ?')->execute([$name, $description, $isPersonal ? 1 : 0, $targetAmount, $targetYear, $parentFundId, $id]);
        } catch (PDOException $e) {
            $pdo->prepare('UPDATE funds SET name = ?, description = ? WHERE id = ?')->execute([$name, $description, $id]);
        }
        header('Location: ' . BASE_PATH . '/finance/funds?toast=' . urlencode('Fund updated.'));
        exit;
    }

    if ($postAction === 'delete_fund') {
        $id = (int) ($_POST['id'] ?? 0);
        if ($id <= 0) {
            header('Location: ' . BASE_PATH . '/finance/funds?toast_error=' . urlencode('Invalid fund.'));
            exit;
        }
        $count = $pdo->prepare('SELECT COUNT(*) FROM transactions WHERE fund_id = ?');
        $count->execute([$id]);
        if ($count->fetchColumn() > 0) {
            header('Location: ' . BASE_PATH . '/finance/funds?toast_error=' . urlencode('Cannot delete a fund that has transactions.'));
            exit;
        }
        $pdo->prepare('DELETE FROM funds WHERE id = ?')->execute([$id]);
        header('Location: ' . BASE_PATH . '/finance/funds?toast=' . urlencode('Fund deleted.'));
        exit;
    }
}

try {
    $funds = $pdo->query("
        SELECT f.id, f.name, f.description, COALESCE(f.is_personal, 0) AS is_personal,
               f.target_amount, f.target_year, f.parent_fund_id,
               parent.name AS parent_fund_name,
               (SELECT COUNT(*) FROM transactions t WHERE t.fund_id = f.id) AS transaction_count
        FROM funds f
        LEFT JOIN funds parent ON f.parent_fund_id = parent.id
        ORDER BY parent.name IS NULL DESC, parent.name, f.name
    ")->fetchAll();
} catch (PDOException $e) {
    $funds = $pdo->query("
        SELECT f.id, f.name, f.description,
               (SELECT COUNT(*) FROM transactions t WHERE t.fund_id = f.id) AS transaction_count
        FROM funds f
        ORDER BY f.name
    ")->fetchAll();
    foreach ($funds as &$f) {
        $f['is_personal'] = 0;
        $f['target_amount'] = null;
        $f['target_year'] = null;
        $f['parent_fund_id'] = null;
        $f['parent_fund_name'] = null;
    }
    unset($f);
}
$editId = isset($_GET['edit']) ? (int) $_GET['edit'] : 0;
// Top-level funds only (for "Contributes to" dropdown)
$parentFundOptions = array_filter($funds, function ($f) use ($editId) {
    $hasParent = isset($f['parent_fund_id']) && $f['parent_fund_id'] !== null && $f['parent_fund_id'] !== '';
    if ($editId > 0 && (int) $f['id'] === $editId) {
        return false;
    }
    return !$hasParent;
});
$editFund = null;
if ($editId > 0) {
    foreach ($funds as $f) {
        if ((int) $f['id'] === $editId) {
            $editFund = $f;
            break;
        }
    }
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1>Offering types</h1>
    <p class="text-muted" style="margin: 0.25rem 0 0; font-size: 0.9375rem;">Add and manage the types of offerings you record (e.g. Tithes, General Offering, Building Fund).</p>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/finance" class="link-muted">← Back to Finance</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if ($editFund): ?>
<div class="card" style="max-width: 560px; margin-left: auto; margin-right: auto;">
    <h2>Edit fund</h2>
    <form method="post">
        <input type="hidden" name="action" value="update_fund">
        <input type="hidden" name="id" value="<?= (int) $editFund['id'] ?>">
        <div class="form-group">
            <label for="edit_fund_name">Fund name *</label>
            <input type="text" id="edit_fund_name" name="name" required value="<?= htmlspecialchars($editFund['name']) ?>">
        </div>
        <div class="form-group">
            <label for="edit_fund_description">Description (optional)</label>
            <input type="text" id="edit_fund_description" name="description" value="<?= htmlspecialchars($editFund['description'] ?? '') ?>">
        </div>
        <div class="form-group checkbox-row">
            <label>
                <input type="checkbox" name="is_personal" value="1" <?= !empty($editFund['is_personal']) ? 'checked' : '' ?>>
                Personal offering (attach to member, e.g. tithes)
            </label>
        </div>
        <div class="form-group">
            <label for="edit_fund_target_amount">Target amount (optional)</label>
            <input type="number" id="edit_fund_target_amount" name="target_amount" min="0" step="0.01" placeholder="50000" value="<?= isset($editFund['target_amount']) && $editFund['target_amount'] !== null && $editFund['target_amount'] !== '' ? htmlspecialchars($editFund['target_amount']) : '' ?>">
        </div>
        <div class="form-group">
            <label for="edit_fund_target_year">Target year (optional)</label>
            <input type="number" id="edit_fund_target_year" name="target_year" min="2000" max="2100" placeholder="2026" value="<?= isset($editFund['target_year']) && $editFund['target_year'] !== null && $editFund['target_year'] !== '' ? (int) $editFund['target_year'] : '' ?>">
        </div>
        <div class="form-group">
            <label for="edit_fund_parent">Contributes to fund (optional)</label>
            <select id="edit_fund_parent" name="parent_fund_id">
                <option value="">— None (standalone fund) —</option>
                <?php foreach ($parentFundOptions as $pf): ?>
                <option value="<?= (int) $pf['id'] ?>" <?= (isset($editFund['parent_fund_id']) && (int) $editFund['parent_fund_id'] === (int) $pf['id']) ? 'selected' : '' ?>><?= htmlspecialchars($pf['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <span class="text-muted" style="font-size: 0.875rem;">This fund’s total counts toward the chosen fund’s target (e.g. day offerings → Harvest).</span>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn">Update fund</button>
            <a href="<?= BASE_PATH ?>/finance/funds" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>
<?php else: ?>
<div class="card" style="max-width: 560px; margin-left: auto; margin-right: auto;">
    <h2>Add fund</h2>
    <form method="post">
        <input type="hidden" name="action" value="add_fund">
        <div class="form-group">
            <label for="fund_name">Fund name *</label>
            <input type="text" id="fund_name" name="name" required placeholder="Tithes, Thanksgiving Offering">
        </div>
        <div class="form-group">
            <label for="fund_description">Description (optional)</label>
            <input type="text" id="fund_description" name="description" placeholder="Short description">
        </div>
        <div class="form-group checkbox-row">
            <label>
                <input type="checkbox" name="is_personal" value="1">
                Personal offering (attach to member, e.g. tithes)
            </label>
        </div>
        <div class="form-group">
            <label for="fund_target_amount">Target amount (optional)</label>
            <input type="number" id="fund_target_amount" name="target_amount" min="0" step="0.01" placeholder="50000">
        </div>
        <div class="form-group">
            <label for="fund_target_year">Target year (optional)</label>
            <input type="number" id="fund_target_year" name="target_year" min="2000" max="2100" placeholder="2026">
        </div>
        <div class="form-group">
            <label for="fund_parent">Contributes to fund (optional)</label>
            <select id="fund_parent" name="parent_fund_id">
                <option value="">— None (standalone fund) —</option>
                <?php foreach ($parentFundOptions as $pf): ?>
                <option value="<?= (int) $pf['id'] ?>"><?= htmlspecialchars($pf['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <span class="text-muted" style="font-size: 0.875rem;">This fund’s total counts toward the chosen fund’s target (e.g. day offerings → Harvest).</span>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn">Add fund</button>
        </div>
    </form>
</div>
<?php endif; ?>

<div class="card" style="margin-top: 1.5rem;">
    <h2>Funds</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">Delete only funds that have no transactions. You can add new funds and remove ones that don’t apply.</p>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Fund</th>
                    <th>Description</th>
                    <th>Type</th>
                    <th>Contributes to</th>
                    <th>Target</th>
                    <th style="text-align: right;">Transactions</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($funds as $f): ?>
                <tr>
                    <td><?= htmlspecialchars($f['name']) ?></td>
                    <td><?= htmlspecialchars($f['description'] ?? '—') ?></td>
                    <td><?= !empty($f['is_personal']) ? 'Personal' : 'General' ?></td>
                    <td><?= !empty($f['parent_fund_name']) ? htmlspecialchars($f['parent_fund_name']) : '—' ?></td>
                    <td><?php
                        $ta = isset($f['target_amount']) && $f['target_amount'] !== null && $f['target_amount'] !== '' ? (float) $f['target_amount'] : null;
                        $ty = isset($f['target_year']) && $f['target_year'] !== null && $f['target_year'] !== '' ? (int) $f['target_year'] : null;
                        if ($ta !== null && $ty !== null) {
                            echo 'GH&#8373; ' . number_format($ta, 2) . ' (' . $ty . ')';
                        } else {
                            echo '—';
                        }
                    ?></td>
                    <td style="text-align: right;"><?= (int) $f['transaction_count'] ?></td>
                    <td class="actions">
                        <a href="<?= BASE_PATH ?>/finance/funds?edit=<?= (int) $f['id'] ?>" class="btn btn-sm btn-outline">Edit</a>
                        <?php if ((int) $f['transaction_count'] === 0): ?>
                        <form method="post" style="display: inline;" onsubmit="return confirm('Delete this fund?');">
                            <input type="hidden" name="action" value="delete_fund">
                            <input type="hidden" name="id" value="<?= (int) $f['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
                        </form>
                        <?php else: ?>
                        <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (empty($funds)): ?>
    <p class="text-muted">No funds yet. Add one above.</p>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
