<?php
$assetBase =
    basename(rtrim(FCPATH, "\\/")) === "public" ? "assets/" : "public/assets/";
$isEdit = $mode === "edit";
$value = static function ($field, $default = "") use ($quotation) {
    return old($field, $quotation[$field] ?? $default);
};
$oldNames = old("item_name");
if (is_array($oldNames)) {
    $rows = [];
    $oldDescriptions = (array) old("description");
    $oldQuantities = (array) old("quantity");
    $oldPrices = (array) old("price");
    foreach ($oldNames as $index => $name) {
        $rows[] = [
            "item_name" => $name,
            "description" => $oldDescriptions[$index] ?? "",
            "quantity" => $oldQuantities[$index] ?? "1",
            "price" => $oldPrices[$index] ?? "0",
        ];
    }
} elseif ($items) {
    $rows = $items;
} else {
    $rows = [
        [
            "item_name" => "",
            "description" => "",
            "quantity" => "1",
            "price" => "0",
        ],
    ];
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $isEdit
        ? "Edit " . esc($quotation["quotation_number"])
        : "New Quotation" ?> · BrandSquare Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Manrope:wght@600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= base_url($assetBase . "css/admin.css") ?>">
</head>
<body class="admin-page">
    <aside class="admin-sidebar">
        <a href="<?= base_url(
            "admin/leads",
        ) ?>" class="admin-logo">Brand<span>Square.</span></a>
        <nav><a href="<?= base_url(
            "admin/leads",
        ) ?>"><i>◎</i> Leads</a><a href="<?= base_url(
    "admin/clients",
) ?>"><i>◉</i> Clients</a><a class="active" href="<?= base_url(
    "admin/quotations",
) ?>"><i>₹</i> Quotations</a><a href="<?= base_url(
    "admin/invoices",
) ?>"><i>▤</i> Invoices</a><a href="<?= base_url(
    "admin/industries",
) ?>"><i>◆</i> Industries</a><a href="<?= base_url(
    "admin/email-templates",
) ?>"><i>✦</i> Email templates</a><a href="<?= base_url(
    "admin/articles",
) ?>"><i>▤</i> Articles</a><a href="<?= base_url(
    "admin/settings",
) ?>"><i>⚙</i> Settings</a><a href="<?= base_url() ?>" target="_blank"><i>↗</i> View website</a></nav>
        <div class="admin-user"><span><?= esc(
            strtoupper(substr((string) session("admin_name"), 0, 2)),
        ) ?></span><div><b><?= esc(session("admin_name")) ?></b><small><?= esc(
    session("admin_email"),
) ?></small></div></div>
        <form action="<?= base_url(
            "admin/logout",
        ) ?>" method="post"><?= csrf_field() ?><button class="logout" type="submit">Sign out →</button></form>
    </aside>
    <main class="admin-main quotation-form-main">
        <header class="admin-heading"><div><a class="back-to-templates" href="<?= $isEdit
            ? base_url("admin/quotations/" . $quotation["id"])
            : base_url("admin/quotations") ?>">← <?= $isEdit
    ? "Quotation details"
    : "Quotation register" ?></a><h1><?= $isEdit
    ? "Edit quotation"
    : "Create quotation" ?></h1><p>Add services, quantities, and prices. Totals update automatically.</p></div><?php if (
    $isEdit
): ?><span class="quotation-document-id"><?= esc(
    $quotation["quotation_number"],
) ?></span><?php endif; ?></header>

        <?php if (session("error")): ?><div class="alert error"><?= esc(
    session("error"),
) ?></div><?php endif; ?>
        <?php if (
            !$clients
        ): ?><div class="alert error">Create a client before preparing a quotation. <a href="<?= base_url(
    "admin/clients/new",
) ?>">Add a client now →</a></div><?php endif; ?>

        <form method="post" class="quotation-form" data-quotation-form>
            <?= csrf_field() ?>
            <section class="quotation-form-card">
                <div class="quotation-form-section-title"><span>01</span><div><h2>Quotation details</h2><p>Choose the client, dates, and current document status.</p></div></div>
                <div class="quotation-details-grid">
                    <label>Client<select name="client_id" required><option value="">Select a client</option><?php foreach (
                        $clients
                        as $client
                    ): ?><option value="<?= esc(
    $client["id"],
) ?>" <?= (string) $value("client_id") === (string) $client["id"]
    ? "selected"
    : "" ?>><?= esc(
    $client["first_name"] . " " . $client["last_name"],
) ?> · <?= esc(
     $client["email"],
 ) ?></option><?php endforeach; ?></select></label>
                    <label>Quotation date<input type="date" name="quotation_date" required value="<?= esc(
                        $value("quotation_date", date("Y-m-d")),
                    ) ?>"></label>
                    <label>Valid until<input type="date" name="valid_until" value="<?= esc(
                        $value(
                            "valid_until",
                            date("Y-m-d", strtotime("+14 days")),
                        ),
                    ) ?>"></label>
                    <label>Status<select name="status" required><?php foreach (
                        $statuses
                        as $status
                    ): ?><option value="<?= esc($status) ?>" <?= $value(
    "status",
    "draft",
) === $status
    ? "selected"
    : "" ?>><?= esc(
    ucfirst($status),
) ?></option><?php endforeach; ?></select></label>
                </div>
            </section>

            <section class="quotation-form-card quotation-items-card">
                <div class="quotation-form-section-title"><span>02</span><div><h2>Items</h2><p>Add or remove rows as needed. Prices are entered before tax.</p></div><button type="button" class="add-quotation-item" data-add-item>＋ Add item</button></div>
                <div class="quotation-items-head"><span>Item</span><span>Description</span><span>Qty</span><span>Price</span><span>Amount</span><span></span></div>
                <div class="quotation-items" data-items>
                    <?php foreach ($rows as $row): ?>
                        <div class="quotation-item-row" data-item-row>
                            <label><span>Item</span><input name="item_name[]" required maxlength="150" value="<?= esc(
                                $row["item_name"],
                            ) ?>" placeholder="Logo design"></label>
                            <label><span>Description</span><textarea name="description[]" maxlength="2000" rows="2" placeholder="Scope or deliverables"><?= esc(
                                $row["description"],
                            ) ?></textarea></label>
                            <label><span>Quantity</span><input name="quantity[]" data-quantity type="number" required min="0.01" step="0.01" value="<?= esc(
                                $row["quantity"],
                            ) ?>"></label>
                            <label><span>Price</span><input name="price[]" data-price type="number" required min="0" step="0.01" value="<?= esc(
                                $row["price"],
                            ) ?>"></label>
                            <output data-line-total>₹0.00</output>
                            <button type="button" class="remove-quotation-item" data-remove-item aria-label="Remove item">×</button>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="add-item-mobile" data-add-item>＋ Add another item</button>
                <div class="quotation-summary">
                    <span>Total cost</span>
                    <strong data-grand-total>₹0.00</strong>
                    <small>Calculated from all item rows</small>
                </div>
            </section>

            <section class="quotation-form-card">
                <div class="quotation-form-section-title"><span>03</span><div><h2>Notes</h2><p>Add payment terms, exclusions, or a short client message.</p></div></div>
                <label class="quotation-notes">Notes<textarea name="notes" rows="5" maxlength="3000" placeholder="Optional terms and notes"><?= esc(
                    $value("notes"),
                ) ?></textarea></label>
            </section>

            <div class="quotation-form-actions"><a href="<?= $isEdit
                ? base_url("admin/quotations/" . $quotation["id"])
                : base_url(
                    "admin/quotations",
                ) ?>">Cancel</a><button type="submit" <?= !$clients
    ? "disabled"
    : "" ?>>Save quotation <span>→</span></button></div>
        </form>

        <template data-item-template>
            <div class="quotation-item-row" data-item-row>
                <label><span>Item</span><input name="item_name[]" required maxlength="150" placeholder="Logo design"></label>
                <label><span>Description</span><textarea name="description[]" maxlength="2000" rows="2" placeholder="Scope or deliverables"></textarea></label>
                <label><span>Quantity</span><input name="quantity[]" data-quantity type="number" required min="0.01" step="0.01" value="1"></label>
                <label><span>Price</span><input name="price[]" data-price type="number" required min="0" step="0.01" value="0"></label>
                <output data-line-total>₹0.00</output>
                <button type="button" class="remove-quotation-item" data-remove-item aria-label="Remove item">×</button>
            </div>
        </template>
    </main>
    <script src="<?= base_url(
        $assetBase . "js/admin-quotation.js",
    ) ?>"></script>
</body>
</html>
