<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();
billing_ensure_product_catalog_support();

$user = billing_current_user();
$organization = billing_current_organization();
if (!$user) {
    billing_redirect('signin.php');
}
if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

$stats = billing_dashboard_stats((int) $user['id']);
$organizationName = (string) ($organization['organization_name'] ?? 'bala');
$userLabel = (string) ($user['email'] ?? 'billing-user');
$billingTopbarOrganizationName = $organizationName;
$billingTopbarUserLabel = $userLabel;
$billingActiveNav = 'items';

$itemId = (int) ($_GET['id'] ?? 0);
$existing = $itemId > 0 ? billing_get_item((int) $user['id'], (int) $organization['id'], $itemId) : null;
$isEditMode = $existing !== null;

$form = [
    'item_name' => (string) ($existing['item_name'] ?? ''),
    'item_type' => strtolower((string) ($existing['item_type'] ?? 'Goods')) === 'service' ? 'service' : 'goods',
    'unit_name' => (string) ($existing['unit_name'] ?? ''),
    'unit_price' => (string) ($existing['unit_price'] ?? ''),
    'sales_account' => (string) ($existing['sales_account'] ?? 'Sales'),
    'item_description' => (string) ($existing['item_description'] ?? ''),
];
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (array_keys($form) as $field) {
        $form[$field] = billing_clean((string) ($_POST[$field] ?? ''));
    }

    if ($form['item_name'] === '') {
        $errors['item_name'] = 'Enter the item name.';
    }
    if ($form['unit_price'] === '' || !is_numeric($form['unit_price'])) {
        $errors['unit_price'] = 'Enter a valid selling price.';
    }

    if ($errors === []) {
        $savedId = $isEditMode
            ? (billing_update_item($itemId, (int) $user['id'], (int) $organization['id'], $form, $userLabel) ? $itemId : null)
            : billing_create_item((int) $user['id'], (int) $organization['id'], $form, $userLabel);

        if ($savedId) {
            billing_flash('success', $isEditMode ? 'Item updated successfully.' : 'Item created successfully.');
            billing_redirect('items.php?id=' . $savedId);
        }

        $errors['save'] = 'Unable to save the item right now.';
    }
}

$units = billing_catalog_units();
$accounts = billing_catalog_accounts();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title><?php echo $isEditMode ? 'Edit Item' : 'New Item'; ?> | Zoho Billing</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="assets/billing.css?v=20260507-css-recovery-2">
</head>
<body>
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="catalog-form-page">
            <form method="post" class="catalog-form-card">
                <div class="customer-form-header">
                    <h1><?php echo $isEditMode ? 'Edit Item' : 'New Item'; ?></h1>
                </div>
                <?php if (isset($errors['save'])): ?><div class="customer-error-banner"><span><?php echo billing_escape($errors['save']); ?></span></div><?php endif; ?>

                <div class="catalog-item-grid">
                    <div class="catalog-item-main">
                        <div class="catalog-item-row">
                            <div class="catalog-item-label">
                                <label class="is-required" for="item_name">Name*</label>
                            </div>
                            <div class="catalog-item-control">
                                <input class="catalog-form-control" id="item_name" type="text" name="item_name" value="<?php echo billing_escape($form['item_name']); ?>" placeholder="Enter item name">
                                <?php if (isset($errors['item_name'])): ?><div class="field-error"><?php echo billing_escape($errors['item_name']); ?></div><?php endif; ?>
                            </div>
                        </div>

                        <div class="catalog-item-row">
                            <div class="catalog-item-label">
                                <label>Type</label>
                            </div>
                            <div class="catalog-item-control">
                                <div class="catalog-radio-group">
                                    <label><input type="radio" name="item_type" value="goods" <?php echo $form['item_type'] === 'goods' ? 'checked' : ''; ?>> Goods</label>
                                    <label><input type="radio" name="item_type" value="service" <?php echo $form['item_type'] === 'service' ? 'checked' : ''; ?>> Service</label>
                                </div>
                            </div>
                        </div>

                        <div class="catalog-item-row">
                            <div class="catalog-item-label">
                                <label for="unit_name">Unit</label>
                            </div>
                            <div class="catalog-item-control">
                                <select class="catalog-form-control" id="unit_name" name="unit_name">
                                    <option value="">Select or type to add</option>
                                    <?php foreach ($units as $unit): ?>
                                        <option value="<?php echo billing_escape($unit); ?>" <?php echo $form['unit_name'] === $unit ? 'selected' : ''; ?>><?php echo billing_escape($unit); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="catalog-image-box catalog-image-box--form">
                        <div class="catalog-image-placeholder"><i class="fa-regular fa-image"></i></div>
                        <span>Drag image(s) here or <strong>Browse images</strong></span>
                        <small>PNG, JPG, or WEBP up to 5 MB</small>
                    </div>
                </div>

                <section class="catalog-section catalog-section--lined">
                    <div class="catalog-section-head">
                        <h2>Sales Information</h2>
                        <p>Control how this item appears in invoices, subscriptions, and checkout flows.</p>
                    </div>
                    <div class="catalog-item-stack">
                        <div class="catalog-item-row">
                            <div class="catalog-item-label">
                                <label class="is-required" for="unit_price">Selling Price*</label>
                            </div>
                            <div class="catalog-item-control">
                                <div class="customer-prefix-field customer-prefix-field--catalog">
                                    <span>INR</span>
                                    <input class="catalog-form-control" id="unit_price" type="text" name="unit_price" value="<?php echo billing_escape($form['unit_price']); ?>" placeholder="0.00">
                                </div>
                                <?php if (isset($errors['unit_price'])): ?><div class="field-error"><?php echo billing_escape($errors['unit_price']); ?></div><?php endif; ?>
                            </div>
                        </div>

                        <div class="catalog-item-row">
                            <div class="catalog-item-label">
                                <label class="is-required" for="sales_account">Account*</label>
                            </div>
                            <div class="catalog-item-control">
                                <select class="catalog-form-control" id="sales_account" name="sales_account">
                                    <?php foreach ($accounts as $account): ?>
                                        <option value="<?php echo billing_escape($account); ?>" <?php echo $form['sales_account'] === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="catalog-item-row catalog-item-row--top">
                            <div class="catalog-item-label">
                                <label for="item_description">Description</label>
                            </div>
                            <div class="catalog-item-control">
                                <textarea class="catalog-form-control" id="item_description" name="item_description" placeholder="Add a short description for internal teams or customer-facing documents"><?php echo billing_escape($form['item_description']); ?></textarea>
                            </div>
                        </div>
                    </div>
                </section>

                <div class="customer-form-footer">
                    <button class="customer-btn customer-btn--green" type="submit">Save</button>
                    <a class="customer-btn" href="items.php<?php echo $isEditMode ? '?id=' . $itemId : ''; ?>">Cancel</a>
                </div>
            </form>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



