<?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';

$action = (string) ($_GET['action'] ?? '');
$actionId = (int) ($_GET['id'] ?? 0);
if ($actionId > 0) {
    if ($action === 'clone') {
        $newId = billing_clone_item($actionId, (int) $user['id'], (int) $organization['id'], $userLabel);
        billing_flash('success', $newId ? 'Item cloned successfully.' : 'Unable to clone the item.');
        billing_redirect('items.php' . ($newId ? '?id=' . $newId : ''));
    }
    if ($action === 'mark_inactive') {
        billing_set_item_inactive($actionId, (int) $user['id'], (int) $organization['id'], true, $userLabel);
        billing_flash('success', 'Item marked as inactive.');
        billing_redirect('items.php?id=' . $actionId);
    }
    if ($action === 'mark_active') {
        billing_set_item_inactive($actionId, (int) $user['id'], (int) $organization['id'], false, $userLabel);
        billing_flash('success', 'Item marked as active.');
        billing_redirect('items.php?id=' . $actionId);
    }
}

$view = (string) ($_GET['view'] ?? 'active');
if (!in_array($view, ['active', 'all', 'inactive'], true)) {
    $view = 'active';
}
$tab = (string) ($_GET['tab'] ?? 'overview');
if (!in_array($tab, ['overview', 'transactions', 'history'], true)) {
    $tab = 'overview';
}

$items = billing_get_items((int) $user['id'], (int) $organization['id'], $view);
$selectedId = (int) ($_GET['id'] ?? 0);
$selectedItem = $selectedId > 0 ? billing_get_item((int) $user['id'], (int) $organization['id'], $selectedId) : null;
$itemHistory = $selectedItem ? billing_get_item_history((int) $selectedItem['id'], (int) $user['id'], (int) $organization['id']) : [];
$relatedPlans = $selectedItem ? billing_fetch_all(
    'SELECT plan_name, status_label, price FROM catalog_plans WHERE user_id = ? AND organization_id = ? AND product_item_id = ? ORDER BY id DESC',
    'iii',
    [(int) $user['id'], (int) $organization['id'], (int) $selectedItem['id']]
) : [];
$relatedAddons = $selectedItem ? billing_fetch_all(
    'SELECT addon_name, status_label, price FROM catalog_addons WHERE user_id = ? AND organization_id = ? AND product_item_id = ? ORDER BY id DESC',
    'iii',
    [(int) $user['id'], (int) $organization['id'], (int) $selectedItem['id']]
) : [];
$flashSuccess = billing_flash('success');

function billing_items_query(array $changes = []): string
{
    $query = $_GET;
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }
    return 'items.php' . ($query !== [] ? '?' . http_build_query($query) : '');
}
?>
<!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>Items | 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">
</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-page">
            <?php if ($flashSuccess): ?><div class="customer-flash"><?php echo billing_escape($flashSuccess); ?></div><?php endif; ?>

            <section class="catalog-split-card<?php echo !$selectedItem && $items !== [] ? ' catalog-split-card--list-only' : ''; ?>">
                <div class="catalog-list-pane">
                    <div class="catalog-list-head">
                        <div class="catalog-view-links">
                            <a class="<?php echo $view === 'active' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['view' => 'active', 'id' => null])); ?>">Active Items</a>
                            <a class="<?php echo $view === 'all' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['view' => 'all', 'id' => null])); ?>">All Items</a>
                            <a class="<?php echo $view === 'inactive' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['view' => 'inactive', 'id' => null])); ?>">Inactive</a>
                        </div>
                        <div class="customer-view-actions">
                            <a class="customer-btn customer-btn--green" href="item_new.php"><i class="fa-solid fa-plus"></i> New</a>
                            <div class="customer-menu-wrap customer-menu-wrap--table">
                                <button class="customer-btn customer-btn--icon" type="button" data-menu-toggle="itemTableMenu"><i class="fa-solid fa-ellipsis"></i></button>
                                <div class="customer-pop-menu customer-pop-menu--table" id="itemTableMenu" hidden>
                                    <button class="menu-item" type="button" data-customer-note="Import items can be added next."><i class="fa-solid fa-file-import"></i><span>Import Items</span></button>
                                    <button class="menu-item" type="button" data-customer-note="Export items can be added next."><i class="fa-solid fa-file-export"></i><span>Export</span></button>
                                    <button class="menu-item" type="button" data-customer-note="Preferences can be added next."><i class="fa-solid fa-gear"></i><span>Preferences</span></button>
                                    <a class="menu-item" href="<?php echo billing_escape(billing_items_query()); ?>"><i class="fa-solid fa-rotate"></i><span>Refresh List</span></a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="customer-table-wrap">
                        <table class="customer-table-view">
                            <thead>
                                <tr>
                                    <th class="customer-table-filter-col"><i class="fa-solid fa-sliders"></i></th>
                                    <th>NAME</th>
                                    <th>DESCRIPTION</th>
                                    <th>RATE</th>
                                    <th>USAGE UNIT</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($items === []): ?>
                                    <tr><td colspan="5" class="customer-table-empty">There aren't any items in this view.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($items as $item): ?>
                                        <tr class="<?php echo $selectedItem && (int) $selectedItem['id'] === (int) $item['id'] ? 'catalog-row-active' : ''; ?>">
                                            <td><input type="checkbox" aria-label="Select item"></td>
                                            <td><a class="customer-name-link" href="<?php echo billing_escape(billing_items_query(['id' => (int) $item['id'], 'tab' => 'overview'])); ?>"><?php echo billing_escape((string) $item['item_name']); ?></a></td>
                                            <td><?php echo billing_escape((string) ($item['item_description'] ?? '')); ?></td>
                                            <td>â‚¹<?php echo billing_escape(number_format((float) ($item['unit_price'] ?? 0), 2)); ?></td>
                                            <td><?php echo billing_escape((string) ($item['unit_name'] ?? '')); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <?php if ($selectedItem || $items === []): ?>
                <div class="catalog-detail-pane">
                    <?php if (!$selectedItem): ?>
                        <div class="catalog-empty-state">
                            <i class="fa-solid fa-box-open"></i>
                            <h2>Create your first item</h2>
                            <p>Items let you reuse products and services across plans, addons, and one-time billing.</p>
                            <a class="customer-btn customer-btn--green" href="item_new.php">New Item</a>
                        </div>
                    <?php else: ?>
                        <div class="catalog-detail-head">
                            <div>
                                <h1><?php echo billing_escape((string) $selectedItem['item_name']); ?></h1>
                                <?php if (!empty($selectedItem['is_inactive'])): ?><span class="catalog-badge">INACTIVE</span><?php endif; ?>
                            </div>
                            <div class="catalog-detail-actions">
                                <a class="customer-btn" href="item_new.php?id=<?php echo (int) $selectedItem['id']; ?>"><i class="fa-solid fa-pen"></i> Edit</a>
                                <div class="customer-menu-wrap">
                                    <button class="customer-btn" type="button" data-menu-toggle="itemDetailMenu">More <i class="fa-solid fa-angle-down"></i></button>
                                    <div class="customer-pop-menu" id="itemDetailMenu" hidden>
                                        <a class="menu-item" href="items.php?action=clone&id=<?php echo (int) $selectedItem['id']; ?>"><span>Clone Item</span></a>
                                        <?php if (!empty($selectedItem['is_inactive'])): ?>
                                            <a class="menu-item" href="items.php?action=mark_active&id=<?php echo (int) $selectedItem['id']; ?>"><span>Mark as Active</span></a>
                                        <?php else: ?>
                                            <a class="menu-item" href="items.php?action=mark_inactive&id=<?php echo (int) $selectedItem['id']; ?>"><span>Mark as Inactive</span></a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <nav class="catalog-tab-nav">
                            <a class="<?php echo $tab === 'overview' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['id' => (int) $selectedItem['id'], 'tab' => 'overview'])); ?>">Overview</a>
                            <a class="<?php echo $tab === 'transactions' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['id' => (int) $selectedItem['id'], 'tab' => 'transactions'])); ?>">Transactions</a>
                            <a class="<?php echo $tab === 'history' ? 'is-active' : ''; ?>" href="<?php echo billing_escape(billing_items_query(['id' => (int) $selectedItem['id'], 'tab' => 'history'])); ?>">History</a>
                        </nav>

                        <?php if ($tab === 'overview'): ?>
                            <div class="catalog-overview-grid">
                                <div class="catalog-overview-copy">
                                    <dl class="catalog-definition-list">
                                        <div><dt>Item Type</dt><dd>Sales Items</dd></div>
                                        <div><dt>Unit</dt><dd><?php echo billing_escape((string) ($selectedItem['unit_name'] ?? '')); ?></dd></div>
                                        <div><dt>Created Source</dt><dd>User</dd></div>
                                    </dl>

                                    <h3>Sales Information</h3>
                                    <dl class="catalog-definition-list">
                                        <div><dt>Selling Price</dt><dd>â‚¹<?php echo billing_escape(number_format((float) ($selectedItem['unit_price'] ?? 0), 2)); ?></dd></div>
                                        <div><dt>Sales Account</dt><dd><?php echo billing_escape((string) ($selectedItem['sales_account'] ?? 'Sales')); ?></dd></div>
                                        <div><dt>Description</dt><dd><?php echo billing_escape((string) ($selectedItem['item_description'] ?? '')); ?></dd></div>
                                    </dl>

                                    <h3>Reporting Tags</h3>
                                    <p class="catalog-muted-copy">No reporting tag has been associated with this item.</p>
                                </div>
                                <div class="catalog-image-box">
                                    <div class="catalog-image-placeholder"><i class="fa-regular fa-image"></i></div>
                                    <a href="item_new.php?id=<?php echo (int) $selectedItem['id']; ?>">Change Image</a>
                                </div>
                            </div>
                        <?php elseif ($tab === 'transactions'): ?>
                            <div class="catalog-transaction-panel">
                                <div class="catalog-transaction-group">
                                    <h3>Plans</h3>
                                    <?php if ($relatedPlans === []): ?>
                                        <p class="catalog-muted-copy">No plans created yet.</p>
                                    <?php else: ?>
                                        <table class="customer-table-view">
                                            <thead><tr><th>PLAN</th><th>STATUS</th><th>PRICE</th></tr></thead>
                                            <tbody>
                                                <?php foreach ($relatedPlans as $plan): ?>
                                                    <tr><td><?php echo billing_escape((string) $plan['plan_name']); ?></td><td><?php echo billing_escape((string) $plan['status_label']); ?></td><td>â‚¹<?php echo billing_escape(number_format((float) $plan['price'], 2)); ?></td></tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    <?php endif; ?>
                                </div>
                                <div class="catalog-transaction-group">
                                    <h3>Addons</h3>
                                    <?php if ($relatedAddons === []): ?>
                                        <p class="catalog-muted-copy">No addons created yet.</p>
                                    <?php else: ?>
                                        <table class="customer-table-view">
                                            <thead><tr><th>ADDON</th><th>STATUS</th><th>PRICE</th></tr></thead>
                                            <tbody>
                                                <?php foreach ($relatedAddons as $addon): ?>
                                                    <tr><td><?php echo billing_escape((string) $addon['addon_name']); ?></td><td><?php echo billing_escape((string) $addon['status_label']); ?></td><td>â‚¹<?php echo billing_escape(number_format((float) $addon['price'], 2)); ?></td></tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <table class="customer-table-view">
                                <thead><tr><th>DATE</th><th>DETAILS</th></tr></thead>
                                <tbody>
                                    <?php if ($itemHistory === []): ?>
                                        <tr><td colspan="2" class="customer-table-empty">No history yet.</td></tr>
                                    <?php else: ?>
                                        <?php foreach ($itemHistory as $history): ?>
                                            <tr>
                                                <td><?php echo billing_escape(date('d/m/Y h:i A', strtotime((string) $history['created_at']))); ?></td>
                                                <td><?php echo billing_escape((string) $history['action_label']); ?> by - <?php echo billing_escape((string) $history['actor_label']); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



