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

billing_require_auth();

$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;

billing_ensure_customer_view_support();

$fieldOptions = [
    'display_name' => 'Display Name',
    'company_name' => 'Company Name',
    'email' => 'Email',
    'work_phone' => 'Work Phone',
    'customer_type' => 'Customer Type',
    'portal_status' => 'Portal Status',
];

$comparatorOptions = [
    'contains' => 'contains',
    'is' => 'is',
    'is_not' => 'is not',
    'starts_with' => 'starts with',
    'ends_with' => 'ends with',
];

$availableColumns = [
    'company_name' => 'Company Name',
    'work_phone' => 'Work Phone',
    'receivables' => 'Receivables',
    'receivables_bcy' => 'Receivables (BCY)',
    'unused_credits_bcy' => 'Unused Credits (BCY)',
    'created_by' => 'Created By',
    'first_name' => 'First Name',
    'last_name' => 'Last Name',
    'mobile' => 'Mobile',
    'payment_terms' => 'Payment Terms',
];

$selectedColumns = ['name' => 'Name', 'email' => 'Email'];
$errors = [];
$criteriaCount = max(1, (int) ($_POST['criteria_count'] ?? 1));
$criteriaRows = [];

for ($index = 0; $index < $criteriaCount; $index++) {
    $criteriaRows[] = [
        'field' => (string) ($_POST['criteria_field'][$index] ?? ''),
        'comparator' => (string) ($_POST['criteria_comparator'][$index] ?? ''),
        'value' => (string) ($_POST['criteria_value'][$index] ?? ''),
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_custom_view') {
    $viewName = billing_clean((string) ($_POST['view_name'] ?? ''));
    $logic = strtoupper((string) ($_POST['criteria_logic'] ?? 'AND')) === 'OR' ? 'OR' : 'AND';
    $favorite = !empty($_POST['favorite']);
    $visibility = (string) ($_POST['visibility'] ?? 'only_me');

    if ($viewName === '') {
        $errors[] = 'View name is required.';
    }

    $cleanCriteria = [];
    foreach ($criteriaRows as $row) {
        $field = (string) ($row['field'] ?? '');
        $comparator = (string) ($row['comparator'] ?? '');
        $value = billing_clean((string) ($row['value'] ?? ''));

        if ($field === '' && $comparator === '' && $value === '') {
            continue;
        }

        if ($field === '' || $comparator === '') {
            $errors[] = 'Each criterion needs a field and comparator.';
            break;
        }

        $cleanCriteria[] = [
            'field' => $field,
            'comparator' => $comparator,
            'value' => $value,
        ];
    }

    if ($errors === []) {
        $slug = 'custom_' . strtolower(preg_replace('/[^a-z0-9]+/', '_', $viewName));
        $slug = trim($slug, '_');
        if ($slug === 'custom') {
            $slug = 'custom_view_' . time();
        }

        $saved = billing_save_customer_view((int) $user['id'], (int) $organization['id'], $slug, [
            'name' => $viewName,
            'logic' => $logic,
            'favorite' => $favorite,
            'visibility' => $visibility,
            'criteria' => $cleanCriteria,
            'selected_columns' => ['name', 'email'],
        ]);

        if ($saved) {
            billing_redirect('customers.php?view=' . urlencode($slug));
        }

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

$criteriaPattern = '(' . implode(' ' . strtoupper((string) ($_POST['criteria_logic'] ?? 'AND')) . ' ', range(1, max(1, $criteriaCount))) . ')';
?>
<!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>New Custom View | 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 $billingActiveNav = 'customers'; include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="customer-custom-view-page">
            <section class="customer-custom-view-card">
                <div class="customer-custom-view-head">
                    <h1>New Custom View</h1>
                    <a class="customer-close-link" href="customers.php"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <?php if ($errors !== []): ?>
                    <div class="customer-flash">
                        <?php echo billing_escape(implode(' ', $errors)); ?>
                    </div>
                <?php endif; ?>

                <form method="post" data-custom-view-form>
                    <input type="hidden" name="action" value="save_custom_view">
                    <input type="hidden" name="criteria_count" value="<?php echo count($criteriaRows); ?>" data-criteria-count>

                    <div class="customer-custom-view-section customer-custom-view-section--header">
                        <label>
                            <span>Name*</span>
                            <input type="text" name="view_name" value="<?php echo billing_escape((string) ($_POST['view_name'] ?? '')); ?>">
                        </label>
                        <label class="customer-favorite-toggle">
                            <input type="checkbox" name="favorite" value="1" <?php echo !empty($_POST['favorite']) ? 'checked' : ''; ?>>
                            <i class="fa-regular fa-star"></i>
                            <span>Mark as Favorite</span>
                        </label>
                    </div>

                    <div class="customer-custom-view-section">
                        <h2>Define the criteria ( if any )</h2>
                        <div class="customer-criteria-list" data-criteria-list>
                            <?php foreach ($criteriaRows as $index => $row): ?>
                                <div class="customer-criterion-row" data-criterion-row>
                                    <div class="customer-criterion-number"><?php echo $index + 1; ?></div>
                                    <select name="criteria_field[]">
                                        <option value="">Select a field</option>
                                        <?php foreach ($fieldOptions as $fieldValue => $fieldLabel): ?>
                                            <option value="<?php echo billing_escape($fieldValue); ?>" <?php echo $row['field'] === $fieldValue ? 'selected' : ''; ?>><?php echo billing_escape($fieldLabel); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <select name="criteria_comparator[]">
                                        <option value="">Select a comparator</option>
                                        <?php foreach ($comparatorOptions as $comparatorValue => $comparatorLabel): ?>
                                            <option value="<?php echo billing_escape($comparatorValue); ?>" <?php echo $row['comparator'] === $comparatorValue ? 'selected' : ''; ?>><?php echo billing_escape($comparatorLabel); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="text" name="criteria_value[]" value="<?php echo billing_escape((string) $row['value']); ?>">
                                    <button class="customer-criterion-add" type="button" data-criterion-add><i class="fa-solid fa-plus"></i></button>
                                    <button class="customer-criterion-remove" type="button" data-criterion-remove><i class="fa-regular fa-trash-can"></i></button>
                                </div>
                                <?php if ($index < count($criteriaRows) - 1): ?>
                                    <div class="customer-criteria-logic-row">
                                        <select name="criteria_logic">
                                            <option value="AND" <?php echo (($_POST['criteria_logic'] ?? 'AND') === 'AND') ? 'selected' : ''; ?>>AND</option>
                                            <option value="OR" <?php echo (($_POST['criteria_logic'] ?? '') === 'OR') ? 'selected' : ''; ?>>OR</option>
                                        </select>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                        <button class="customer-add-criterion-link" type="button" data-criterion-add-link><i class="fa-solid fa-circle-plus"></i> Add Criterion</button>

                        <?php if (count($criteriaRows) > 1): ?>
                            <div class="customer-criteria-pattern">
                                <span>CRITERIA PATTERN:</span>
                                <strong><?php echo billing_escape($criteriaPattern); ?></strong>
                                <button type="button" data-customer-note="Pattern editor will be added next."><i class="fa-regular fa-pen-to-square"></i></button>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="customer-custom-view-section">
                        <h2>Columns Preference:</h2>
                        <div class="customer-columns-grid">
                            <div class="customer-columns-box">
                                <div class="customer-columns-title">AVAILABLE COLUMNS</div>
                                <div class="customer-columns-search">
                                    <i class="fa-solid fa-magnifying-glass"></i>
                                    <input type="search" placeholder="Search">
                                </div>
                                <div class="customer-columns-list">
                                    <?php foreach ($availableColumns as $columnLabel): ?>
                                        <div class="customer-column-chip"><i class="fa-solid fa-grip-vertical"></i><span><?php echo billing_escape($columnLabel); ?></span></div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="customer-columns-box">
                                <div class="customer-columns-title customer-columns-title--selected">SELECTED COLUMNS</div>
                                <div class="customer-columns-list customer-columns-list--selected">
                                    <?php foreach ($selectedColumns as $columnLabel): ?>
                                        <div class="customer-column-chip"><i class="fa-solid fa-grip-vertical"></i><span><?php echo billing_escape($columnLabel); ?> *</span></div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="customer-custom-view-section">
                        <h2>Visibility Preference</h2>
                        <div class="customer-visibility-card">
                            <div class="customer-visibility-title">Share With</div>
                            <label><input type="radio" name="visibility" value="only_me" <?php echo (($_POST['visibility'] ?? 'only_me') === 'only_me') ? 'checked' : ''; ?>> Only Me</label>
                            <label><input type="radio" name="visibility" value="selected" <?php echo (($_POST['visibility'] ?? '') === 'selected') ? 'checked' : ''; ?>> Only Selected Users &amp; Roles</label>
                            <label><input type="radio" name="visibility" value="everyone" <?php echo (($_POST['visibility'] ?? '') === 'everyone') ? 'checked' : ''; ?>> Everyone</label>
                        </div>
                    </div>

                    <div class="customer-form-footer">
                        <button class="customer-btn customer-btn--green" type="submit">Save</button>
                        <a class="customer-btn" href="customers.php">Cancel</a>
                    </div>
                </form>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js"></script>
</body>
</html>



