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

billing_require_auth();
billing_ensure_expense_support();
billing_ensure_recurring_expense_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 = 'recurring_expenses';

$expenseAccounts = billing_expense_accounts((int) $user['id'], (int) $organization['id']);
$customers = billing_expense_customer_options((int) $user['id'], (int) $organization['id']);
$recurringProfiles = billing_get_recurring_expenses((int) $user['id'], (int) $organization['id']);
$rawRecurringProfiles = $recurringProfiles;
$selectedRecurringId = (int) ($_GET['id'] ?? 0);
$selectedRecurring = $selectedRecurringId > 0 ? billing_get_recurring_expense((int) $user['id'], (int) $organization['id'], $selectedRecurringId) : null;
$showNewForm = isset($_GET['new']) && $_GET['new'] === '1';
$showCustomViewBuilder = isset($_GET['modal']) && $_GET['modal'] === 'custom-view';
$flashInfo = billing_flash('success');

function billing_recurring_normalize_key(string $value): string
{
    $value = strtolower(trim($value));
    $value = preg_replace('/[^a-z0-9]+/', '-', $value) ?? '';
    return trim($value, '-');
}

function billing_recurring_view_options(): array
{
    return [
        ['key' => 'all', 'label' => 'All'],
        ['key' => 'active', 'label' => 'Active'],
        ['key' => 'stopped', 'label' => 'Stopped'],
        ['key' => 'expired', 'label' => 'Expired'],
    ];
}

function billing_recurring_profile_matches(array $profile, array $view): bool
{
    $type = (string) ($view['type'] ?? 'status');
    $statusKey = billing_recurring_normalize_key((string) ($profile['status_label'] ?? ''));
    if ($type === 'status') {
        $key = (string) ($view['key'] ?? 'all');
        if ($key === 'all') {
            return true;
        }
        return $statusKey === $key;
    }

    $criteria = $view['criteria'] ?? [];
    if (!is_array($criteria) || $criteria === []) {
        return true;
    }

    $fieldMap = [
        'profile_name' => (string) ($profile['profile_name'] ?? ''),
        'expense_account' => (string) ($profile['category_name'] ?? ''),
        'customer_name' => (string) ($profile['customer_name'] ?? ''),
        'frequency' => (string) ($profile['repeat_every'] ?? ''),
        'status' => (string) ($profile['status_label'] ?? ''),
    ];

    foreach ($criteria as $criterion) {
        $field = (string) ($criterion['field'] ?? '');
        $comparator = (string) ($criterion['comparator'] ?? '');
        $value = trim((string) ($criterion['value'] ?? ''));
        if ($field === '' || $comparator === '' || !array_key_exists($field, $fieldMap)) {
            continue;
        }

        $haystack = strtolower(trim($fieldMap[$field]));
        $needle = strtolower($value);
        $matched = true;

        if ($comparator === 'is') {
            $matched = $haystack === $needle;
        } elseif ($comparator === 'contains') {
            $matched = $needle === '' ? true : strpos($haystack, $needle) !== false;
        } elseif ($comparator === 'starts_with') {
            $matched = $needle === '' ? true : strpos($haystack, $needle) === 0;
        }

        if (!$matched) {
            return false;
        }
    }

    return true;
}

$recurringSessionKey = 'recurring_expense_custom_views';
if (!isset($_SESSION[$recurringSessionKey]) || !is_array($_SESSION[$recurringSessionKey])) {
    $_SESSION[$recurringSessionKey] = [];
}

$customViews = $_SESSION[$recurringSessionKey];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string) ($_POST['recurring_action'] ?? '') === 'save_custom_view') {
    $viewName = billing_clean((string) ($_POST['view_name'] ?? ''));
    $favorite = !empty($_POST['favorite']);
    $shareWith = billing_clean((string) ($_POST['share_with'] ?? 'only_me'));
    $field = billing_clean((string) ($_POST['criterion_field'][0] ?? ''));
    $comparator = billing_clean((string) ($_POST['criterion_comparator'][0] ?? ''));
    $value = billing_clean((string) ($_POST['criterion_value'][0] ?? ''));
    $criteria = [];
    if ($field !== '' && $comparator !== '' && $value !== '') {
        $criteria[] = [
            'field' => $field,
            'comparator' => $comparator,
            'value' => $value,
        ];
    }

    if ($viewName !== '') {
        $slug = billing_recurring_normalize_key($viewName);
        $_SESSION[$recurringSessionKey][$slug] = [
            'key' => $slug,
            'label' => $viewName,
            'type' => 'custom',
            'favorite' => $favorite,
            'share_with' => $shareWith,
            'criteria' => $criteria,
        ];
        billing_flash('success', 'Custom view saved successfully.');
        billing_redirect('recurring_expenses.php?view=' . rawurlencode($slug));
    }
}

$allRecurringViews = billing_recurring_view_options();
foreach ($_SESSION[$recurringSessionKey] as $customView) {
    if (is_array($customView)) {
        $allRecurringViews[] = $customView;
    }
}

$currentRecurringView = $allRecurringViews[0];
$requestedView = billing_clean((string) ($_GET['view'] ?? $_GET['filter_by'] ?? 'all'));
if (stripos($requestedView, 'Status.') === 0) {
    $requestedView = billing_recurring_normalize_key(substr($requestedView, 7));
}
foreach ($allRecurringViews as $viewOption) {
    if ((string) ($viewOption['key'] ?? '') === $requestedView) {
        $currentRecurringView = $viewOption;
        break;
    }
}
$currentRecurringViewTitle = (string) ($currentRecurringView['key'] ?? '') === 'all'
    ? 'All Profiles'
    : (string) ($currentRecurringView['label'] ?? 'All Profiles');

$recurringProfiles = array_values(array_filter(
    $rawRecurringProfiles,
    static fn(array $profile): bool => billing_recurring_profile_matches($profile, $currentRecurringView)
));

function billing_recurring_parse_date(string $value): string
{
    $value = trim($value);
    if ($value === '') {
        return '';
    }
    $formats = ['d/m/Y', 'Y-m-d', 'm/d/Y'];
    foreach ($formats as $format) {
        $date = DateTime::createFromFormat($format, $value);
        if ($date instanceof DateTime) {
            return $date->format('Y-m-d');
        }
    }
    $time = strtotime($value);
    return $time ? date('Y-m-d', $time) : '';
}

function billing_recurring_next_run_date(string $startDate, string $repeatEvery): string
{
    $parsed = billing_recurring_parse_date($startDate);
    if ($parsed === '') {
        return '';
    }
    $date = new DateTime($parsed);
    $map = [
        'Day' => '+1 day',
        'Week' => '+1 week',
        'Month' => '+1 month',
        'Year' => '+1 year',
    ];
    $date->modify($map[$repeatEvery] ?? '+1 week');
    return $date->format('Y-m-d');
}

function billing_ui_next_recurring_date(string $startDate, string $repeatEvery): string
{
    $date = DateTime::createFromFormat('d/m/Y', $startDate) ?: new DateTime();
    $map = [
        'Day' => '+1 day',
        'Week' => '+1 week',
        'Month' => '+1 month',
        'Year' => '+1 year',
    ];
    $date->modify($map[$repeatEvery] ?? '+1 week');
    return $date->format('d/m/Y');
}

$form = [
    'profile_name' => '',
    'repeat_every' => 'Week',
    'start_date' => date('d/m/Y'),
    'ends_on' => '',
    'never_expires' => '1',
    'category_name' => '',
    'currency_code' => 'INR',
    'amount' => '',
    'notes_text' => '',
    'customer_name' => '',
];

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['profile_name'] = billing_clean((string) ($_POST['profile_name'] ?? ''));
    $form['repeat_every'] = billing_clean((string) ($_POST['repeat_every'] ?? 'Week'));
    $form['start_date'] = billing_clean((string) ($_POST['start_date'] ?? date('d/m/Y')));
    $form['ends_on'] = billing_clean((string) ($_POST['ends_on'] ?? ''));
    $form['never_expires'] = !empty($_POST['never_expires']) ? '1' : '';
    $form['category_name'] = billing_clean((string) ($_POST['category_name'] ?? ''));
    $form['currency_code'] = billing_clean((string) ($_POST['currency_code'] ?? 'INR'));
    $form['amount'] = billing_clean((string) ($_POST['amount'] ?? ''));
    $form['notes_text'] = billing_clean((string) ($_POST['notes_text'] ?? ''));
    $form['customer_name'] = billing_clean((string) ($_POST['customer_name'] ?? ''));

    if ($form['profile_name'] === '') {
        $errors['profile_name'] = 'Enter a profile name.';
    }
    if ($form['category_name'] === '') {
        $errors['category_name'] = 'Select a category.';
    }
    if ($form['amount'] === '' || !is_numeric($form['amount']) || (float) $form['amount'] <= 0) {
        $errors['amount'] = 'Enter a valid amount.';
    }
    if (billing_recurring_parse_date($form['start_date']) === '') {
        $errors['start_date'] = 'Enter a valid start date.';
    }
    if ($form['never_expires'] !== '1' && $form['ends_on'] !== '' && billing_recurring_parse_date($form['ends_on']) === '') {
        $errors['ends_on'] = 'Enter a valid end date.';
    }

    if ($errors === []) {
        $savedId = billing_save_recurring_expense(
            (int) $user['id'],
            (int) $organization['id'],
            [
                'profile_name' => $form['profile_name'],
                'repeat_every' => $form['repeat_every'],
                'start_date' => billing_recurring_parse_date($form['start_date']),
                'next_run_date' => billing_recurring_next_run_date($form['start_date'], $form['repeat_every']),
                'ends_on' => $form['never_expires'] === '1' ? null : billing_recurring_parse_date($form['ends_on']),
                'never_expires' => $form['never_expires'] === '1',
                'category_name' => $form['category_name'],
                'currency_code' => $form['currency_code'],
                'amount' => $form['amount'],
                'notes_text' => $form['notes_text'],
                'customer_name' => $form['customer_name'],
            ]
        );

        if ($savedId) {
            billing_flash('success', 'Recurring expense saved successfully.');
            billing_redirect('recurring_expenses.php?id=' . $savedId);
        }

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

$nextRunDate = billing_ui_next_recurring_date($form['start_date'], $form['repeat_every']);
?>
<!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>Recurring Expenses | 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">
<style>
.recurring-page { background:#fff; border:1px solid #e7edf5; border-radius:24px; overflow:hidden; }
.recurring-page.has-detail { display:grid; grid-template-columns:380px minmax(0,1fr); }
.recurring-list-pane, .recurring-detail-pane { min-width:0; }
.recurring-detail-pane { border-left:1px solid #e8edf5; }
.recurring-alert { margin:18px 26px 0; padding:14px 16px; border:1px solid #d8e8ff; border-radius:12px; background:#f5f9ff; color:#2c5ea8; }
.recurring-table-head { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:18px 22px; border-bottom:1px solid #e8edf5; }
.recurring-table-head h2 { margin:0; font-size:19px; color:#111f35; }
.recurring-table-actions { display:flex; align-items:center; gap:12px; }
.recurring-table-more { width:40px; height:40px; border:1px solid #d9e2ee; border-radius:10px; background:#fff; color:#31445f; display:inline-flex; align-items:center; justify-content:center; text-decoration:none; }
.recurring-table-new { display:inline-flex; align-items:center; gap:8px; min-height:42px; padding:0 18px; border-radius:10px; background:#20c45d; color:#fff; font-weight:700; text-decoration:none; }
.recurring-table-wrap { overflow:auto; }
.recurring-table { width:100%; border-collapse:collapse; min-width:1100px; }
.recurring-table th, .recurring-table td { padding:16px 14px; border-bottom:1px solid #edf2f8; text-align:left; font-size:14px; vertical-align:top; }
.recurring-table th { color:#71809a; font-weight:700; }
.recurring-table-name { color:#1f68e5; text-decoration:none; font-weight:600; }
.recurring-table-status { color:#1bb45b; font-weight:700; }
.recurring-table-amount { text-align:right; white-space:nowrap; font-weight:700; color:#15263d; }
.recurring-table-empty { padding:56px 24px; text-align:center; color:#6c7a8f; }
.recurring-list-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px; border-bottom:1px solid #e8edf5; }
.recurring-list-head h2 { margin:0; font-size:18px; color:#111f35; }
.recurring-list-actions { display:flex; align-items:center; gap:10px; }
.recurring-mini-btn { width:40px; height:40px; border:1px solid #d9e2ee; border-radius:10px; background:#fff; color:#31445f; display:inline-flex; align-items:center; justify-content:center; text-decoration:none; }
.recurring-mini-btn.is-green { background:#21c45d; border-color:#21c45d; color:#fff; }
.recurring-profile-list { max-height:calc(100vh - 290px); overflow:auto; }
.recurring-profile-card { display:grid; grid-template-columns:18px minmax(0,1fr) auto; gap:14px; padding:16px 18px; border-bottom:1px solid #edf2f8; color:inherit; text-decoration:none; }
.recurring-profile-card.is-active { background:#f5f7fb; }
.recurring-profile-check { width:16px; height:16px; border:1px solid #c0cbdc; border-radius:4px; margin-top:4px; }
.recurring-profile-title { display:block; font-size:16px; font-weight:700; color:#15263d; }
.recurring-profile-sub { display:block; margin-top:6px; color:#3d4f69; font-size:14px; }
.recurring-profile-status { display:block; margin-top:6px; color:#1bb45b; font-size:14px; font-weight:700; }
.recurring-profile-next { display:block; margin-top:6px; color:#52647f; font-size:14px; }
.recurring-profile-amount { display:block; text-align:right; font-size:16px; font-weight:700; color:#15263d; white-space:nowrap; }
.recurring-profile-repeat { display:block; margin-top:6px; text-align:right; color:#52647f; font-size:14px; }
.recurring-detail-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:18px 24px; border-bottom:1px solid #e8edf5; }
.recurring-detail-title { margin:0; display:flex; align-items:center; gap:10px; font-size:18px; color:#111f35; }
.recurring-badge { display:inline-flex; align-items:center; padding:3px 8px; border-radius:6px; background:#39b54a; color:#fff; font-size:14px; }
.recurring-detail-tools { display:flex; align-items:center; gap:12px; }
.recurring-detail-tool-link { min-height:40px; padding:0 14px; border:1px solid #d9e2ee; border-radius:10px; background:#fff; color:#1d2f46; text-decoration:none; display:inline-flex; align-items:center; gap:8px; }
.recurring-detail-close { width:40px; height:40px; border:0; background:transparent; color:#6d7480; font-size:28px; text-decoration:none; display:inline-flex; align-items:center; justify-content:center; }
.recurring-detail-tabs { display:flex; align-items:center; gap:34px; padding:0 18px; border-bottom:1px solid #edf2f8; }
.recurring-detail-tab { display:inline-flex; align-items:center; min-height:54px; text-decoration:none; color:#425774; font-size:15px; }
.recurring-detail-tab.is-active { color:#16263e; font-weight:700; box-shadow:inset 0 -3px 0 #2b79ff; }
.recurring-overview { padding:28px 24px 30px; }
.recurring-kpis { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:26px; }
.recurring-kpi { display:grid; grid-template-columns:58px minmax(0,1fr); gap:14px; align-items:center; }
.recurring-kpi-icon { width:52px; height:52px; border-radius:50%; display:grid; place-items:center; font-size:26px; }
.recurring-kpi-icon.is-green { background:#e8f7ee; color:#1cb15c; }
.recurring-kpi-icon.is-amber { background:#fff2df; color:#ff9800; }
.recurring-kpi-icon.is-blue { background:#e8efff; color:#4a6cf7; }
.recurring-kpi-value { font-size:20px; font-weight:800; color:#111f35; }
.recurring-kpi-label { margin-top:4px; color:#65758d; font-size:14px; }
.recurring-summary { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:24px; margin-top:28px; }
.recurring-summary-group { padding-right:20px; }
.recurring-summary-group.is-accent { border-left:3px solid #ff9800; padding-left:20px; }
.recurring-summary-row + .recurring-summary-row { margin-top:8px; }
.recurring-summary-label { color:#65758d; font-size:15px; }
.recurring-summary-value { margin-top:4px; color:#111f35; font-size:16px; font-weight:600; }
.recurring-section-title { margin:24px 0 12px; padding-top:24px; border-top:1px solid #edf2f8; font-size:16px; font-weight:800; color:#111f35; }
.recurring-history-item { display:grid; grid-template-columns:170px 40px minmax(0,1fr); gap:18px; align-items:start; padding:14px 0; }
.recurring-history-time { color:#7a8ba2; font-size:14px; }
.recurring-history-icon { width:32px; height:32px; border:1px solid #dce6f2; border-radius:50%; color:#f7a21b; display:grid; place-items:center; }
.recurring-history-text { color:#111f35; font-size:15px; line-height:1.45; }
.recurring-history-text small, .recurring-history-text a { color:#2a67e8; text-decoration:none; }
.recurring-head { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:22px 26px; border-bottom:1px solid #e8edf5; }
.recurring-head h1 { margin:0; display:inline-flex; align-items:center; gap:12px; font-size:24px; color:#111f35; }
.recurring-head h1 i { color:#1f2f46; font-size:23px; }
.recurring-close { width:40px; height:40px; border:0; background:transparent; color:#6d7480; font-size:28px; text-decoration:none; display:inline-flex; align-items:center; justify-content:center; }
.recurring-form { padding:0 0 18px; }
.recurring-section { padding:28px 26px; border-bottom:1px solid #edf2f8; }
.recurring-grid { max-width:920px; }
.recurring-row { display:grid; grid-template-columns:210px minmax(0,1fr); gap:14px; align-items:start; }
.recurring-row + .recurring-row { margin-top:18px; }
.recurring-label { padding-top:12px; font-size:16px; color:#111f35; }
.recurring-label.is-required { color:#ff3030; }
.recurring-control input[type="text"], .recurring-control select, .recurring-control textarea { width:100%; border:1px solid #d7dfeb; border-radius:10px; background:#fff; color:#1f2f46; font:inherit; padding:12px 14px; }
.recurring-control input[type="text"]:focus, .recurring-control select:focus, .recurring-control textarea:focus { outline:none; border-color:#3f86ff; box-shadow:0 0 0 2px rgba(63,134,255,0.08); }
.recurring-control textarea { min-height:92px; resize:vertical; }
.recurring-note { margin-top:8px; color:#90a0b0; font-size:15px; }
.recurring-inline-check { display:inline-flex; align-items:center; gap:10px; margin-top:10px; color:#111f35; font-size:15px; }
.recurring-inline-check input { width:18px; height:18px; accent-color:#3b82f6; }
.recurring-amount { display:grid; grid-template-columns:72px minmax(0,1fr); }
.recurring-amount select { border-radius:10px 0 0 10px; }
.recurring-amount input { border-left:0; border-radius:0 10px 10px 0; }
.recurring-customer { display:grid; grid-template-columns:minmax(0,1fr) 44px; }
.recurring-customer select { border-radius:10px 0 0 10px; }
.recurring-customer button { border:0; border-radius:0 10px 10px 0; background:#22c565; color:#fff; font-size:18px; }
.recurring-footer { display:flex; align-items:center; gap:12px; padding:18px 26px 0; }
.recurring-btn { display:inline-flex; align-items:center; justify-content:center; min-height:40px; padding:0 22px; border-radius:8px; border:1px solid #d4dce8; background:#fff; color:#24364d; text-decoration:none; font:inherit; cursor:pointer; }
.recurring-btn--green { border-color:#1db85a; background:#1db85a; color:#fff; font-weight:700; }
.recurring-view-switcher { position:relative; display:inline-block; }
.recurring-view-trigger { display:inline-flex; align-items:center; gap:10px; min-height:42px; padding:0 14px; border:1px solid #d8e2ef; border-radius:12px; background:#f3f7ff; color:#13243d; font-size:20px; font-weight:800; text-decoration:none; }
.recurring-view-trigger i { color:#2a67e8; font-size:15px; }
.recurring-view-menu { position:absolute; top:calc(100% + 8px); left:0; z-index:50; width:318px; background:#fff; border:1px solid #e3eaf4; border-radius:12px; box-shadow:0 14px 36px rgba(15, 23, 42, 0.14); overflow:hidden; display:none; }
.recurring-view-menu.is-open { display:block; }
.recurring-view-search { padding:8px; border-bottom:1px solid #eef2f7; }
.recurring-view-search input { width:100%; height:44px; border:1px solid #b7cdfd; border-radius:10px; padding:0 14px; font:inherit; }
.recurring-view-options { max-height:412px; overflow:auto; padding:8px 0; }
.recurring-view-option { display:flex; align-items:center; justify-content:space-between; gap:12px; min-height:48px; padding:0 24px; color:#303d52; text-decoration:none; font-size:16px; }
.recurring-view-option.is-active { margin:0 10px; border-radius:10px; background:#4d86e6; color:#fff; }
.recurring-view-option-star { color:#b9c2d3; font-size:16px; }
.recurring-view-option.is-active .recurring-view-option-star { color:#fff; }
.recurring-view-footer { border-top:1px solid #eef2f7; padding:10px 16px; }
.recurring-view-footer a { display:inline-flex; align-items:center; gap:10px; color:#425774; text-decoration:none; font-size:16px; }
.recurring-view-footer i { color:#2a67e8; }
.recurring-custom-page { background:#fff; border:1px solid #e7edf5; border-radius:24px; overflow:hidden; }
.recurring-custom-head { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:26px 26px 24px; border-bottom:1px solid #edf2f8; }
.recurring-custom-head h1 { margin:0; font-size:22px; color:#111f35; }
.recurring-custom-close { width:40px; height:40px; border:0; background:transparent; color:#6d7480; font-size:28px; text-decoration:none; display:inline-flex; align-items:center; justify-content:center; }
.recurring-custom-section { padding:28px 26px; border-bottom:1px solid #edf2f8; }
.recurring-custom-top { display:grid; grid-template-columns:minmax(0, 480px) auto; gap:36px; align-items:start; }
.recurring-custom-label { display:block; margin-bottom:8px; font-size:16px; color:#ff3030; }
.recurring-custom-text { width:100%; height:46px; border:1px solid #b7cdfd; border-radius:12px; padding:0 14px; font:inherit; }
.recurring-custom-check { display:inline-flex; align-items:center; gap:10px; padding-top:38px; color:#111f35; font-size:16px; }
.recurring-custom-check input { width:18px; height:18px; accent-color:#3b82f6; }
.recurring-custom-section h2 { margin:0 0 24px; font-size:18px; color:#111f35; }
.recurring-custom-criterion { display:grid; grid-template-columns:58px 240px 206px minmax(0,1fr) 30px 30px; gap:16px; align-items:center; }
.recurring-custom-criterion-number { height:44px; border:1px solid #d7dfeb; border-radius:10px; display:flex; align-items:center; justify-content:center; color:#2d3b50; }
.recurring-custom-criterion select, .recurring-custom-criterion input { height:44px; border:1px solid #d7dfeb; border-radius:10px; padding:0 12px; font:inherit; width:100%; }
.recurring-custom-criterion-action { width:30px; height:30px; border:0; background:transparent; color:#7b8699; font-size:18px; }
.recurring-custom-add { display:inline-flex; align-items:center; gap:10px; margin-top:18px; color:#2a67e8; text-decoration:none; font-size:16px; }
.recurring-custom-columns { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); border:1px solid #dfe7f1; border-radius:16px; overflow:hidden; }
.recurring-custom-column { min-height:380px; }
.recurring-custom-column + .recurring-custom-column { border-left:1px solid #dfe7f1; }
.recurring-custom-column-title { display:flex; align-items:center; gap:10px; padding:0 0 12px; font-size:15px; font-weight:700; color:#50627d; text-transform:uppercase; letter-spacing:.04em; }
.recurring-custom-column-title i { color:#19b36b; }
.recurring-custom-column-search { padding:0 0 14px; }
.recurring-custom-column-search input { width:100%; height:44px; border:1px solid #d7dfeb; border-radius:10px; padding:0 14px; font:inherit; }
.recurring-custom-column-box { padding:18px; }
.recurring-custom-column-list { list-style:none; margin:0; padding:0; }
.recurring-custom-column-list li { display:flex; align-items:center; gap:14px; min-height:38px; font-size:16px; color:#111f35; }
.recurring-custom-column-list i { color:#7b8699; }
.recurring-custom-visibility { border:1px solid #e4ebf4; border-radius:16px; background:#f8fafc; padding:24px; max-width:980px; }
.recurring-custom-visibility-title { margin:0 0 18px; font-size:16px; color:#111f35; }
.recurring-custom-visibility-options { display:flex; align-items:center; gap:16px; flex-wrap:wrap; }
.recurring-custom-visibility-options label { display:inline-flex; align-items:center; gap:12px; min-height:40px; padding:0 16px; border:1px solid #d7dfeb; border-radius:12px; background:#fff; color:#111f35; font-size:15px; }
.recurring-custom-visibility-options input { width:18px; height:18px; accent-color:#3b82f6; }
.recurring-custom-footer { display:flex; align-items:center; gap:12px; padding:20px 26px 24px; }
@media (max-width: 900px) {
  .recurring-page.has-detail { grid-template-columns:1fr; }
  .recurring-detail-pane { border-left:0; border-top:1px solid #e8edf5; }
  .recurring-kpis, .recurring-summary { grid-template-columns:1fr; }
  .recurring-row { grid-template-columns:1fr; }
  .recurring-label { padding-top:0; }
  .recurring-grid { max-width:none; }
  .recurring-custom-top,
  .recurring-custom-criterion,
  .recurring-custom-columns { grid-template-columns:1fr; }
  .recurring-custom-column + .recurring-custom-column { border-left:0; border-top:1px solid #dfe7f1; }
}
</style>
</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'; ?>
        <?php if ($showCustomViewBuilder): ?>
            <main class="recurring-custom-page">
                <div class="recurring-custom-head">
                    <h1>New Custom View</h1>
                    <a class="recurring-custom-close" href="recurring_expenses.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>
                <form method="post">
                    <input type="hidden" name="recurring_action" value="save_custom_view">
                    <div class="recurring-custom-section">
                        <div class="recurring-custom-top">
                            <div>
                                <label class="recurring-custom-label" for="view_name">Name*</label>
                                <input class="recurring-custom-text" id="view_name" type="text" name="view_name" value="">
                            </div>
                            <label class="recurring-custom-check">
                                <input type="checkbox" name="favorite" value="1">
                                <span>Mark as Favorite</span>
                            </label>
                        </div>
                    </div>

                    <div class="recurring-custom-section">
                        <h2>Define the criteria ( if any )</h2>
                        <div class="recurring-custom-criterion">
                            <div class="recurring-custom-criterion-number">1</div>
                            <select name="criterion_field[]">
                                <option value="">Select a field</option>
                                <option value="profile_name">Profile Name</option>
                                <option value="expense_account">Expense Account</option>
                                <option value="customer_name">Customer Name</option>
                                <option value="frequency">Frequency</option>
                                <option value="status">Status</option>
                            </select>
                            <select name="criterion_comparator[]">
                                <option value="">Select a comparator</option>
                                <option value="is">is</option>
                                <option value="contains">contains</option>
                                <option value="starts_with">starts with</option>
                            </select>
                            <input type="text" name="criterion_value[]" value="">
                            <button class="recurring-custom-criterion-action" type="button" aria-label="Add criterion"><i class="fa-solid fa-plus"></i></button>
                            <button class="recurring-custom-criterion-action" type="button" aria-label="Remove criterion"><i class="fa-regular fa-trash-can"></i></button>
                        </div>
                        <a class="recurring-custom-add" href="#"><i class="fa-solid fa-circle-plus"></i> Add Criterion</a>
                    </div>

                    <div class="recurring-custom-section">
                        <h2>Columns Preference:</h2>
                        <div class="recurring-custom-columns">
                            <div class="recurring-custom-column">
                                <div class="recurring-custom-column-box">
                                    <div class="recurring-custom-column-title">AVAILABLE COLUMNS</div>
                                    <div class="recurring-custom-column-search"><input type="text" value="" placeholder="Search"></div>
                                    <ul class="recurring-custom-column-list">
                                        <li><i class="fa-solid fa-grip-vertical"></i> Customer Name</li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Last Expense Date</li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Vendor Name</li>
                                    </ul>
                                </div>
                            </div>
                            <div class="recurring-custom-column">
                                <div class="recurring-custom-column-box">
                                    <div class="recurring-custom-column-title"><i class="fa-regular fa-circle-check"></i> SELECTED COLUMNS</div>
                                    <ul class="recurring-custom-column-list">
                                        <li><i class="fa-solid fa-grip-vertical"></i> Profile Name <span style="color:#ff3030;">*</span></li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Expense Account <span style="color:#ff3030;">*</span></li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Frequency <span style="color:#ff3030;">*</span></li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Next Expense Date <span style="color:#ff3030;">*</span></li>
                                        <li><i class="fa-solid fa-grip-vertical"></i> Status <span style="color:#ff3030;">*</span></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="recurring-custom-section" style="border-bottom:0;">
                        <h2>Visibility Preference</h2>
                        <div class="recurring-custom-visibility">
                            <div class="recurring-custom-visibility-title">Share With</div>
                            <div class="recurring-custom-visibility-options">
                                <label><input type="radio" name="share_with" value="only_me" checked> <span>Only Me</span></label>
                                <label><input type="radio" name="share_with" value="selected_users"> <span>Only Selected Users &amp; Roles</span></label>
                                <label><input type="radio" name="share_with" value="everyone"> <span>Everyone</span></label>
                            </div>
                        </div>
                    </div>

                    <div class="recurring-custom-footer">
                        <button class="recurring-btn recurring-btn--green" type="submit">Save</button>
                        <a class="recurring-btn" href="recurring_expenses.php">Cancel</a>
                    </div>
                </form>
            </main>
        <?php else: ?>
        <main class="recurring-page<?php echo $selectedRecurring ? ' has-detail' : ''; ?>">
            <?php if ($selectedRecurring): ?>
                <div class="recurring-list-pane">
                    <?php if ($flashInfo): ?><div class="recurring-alert"><?php echo billing_escape($flashInfo); ?></div><?php endif; ?>
                    <div class="recurring-list-head">
                        <div class="recurring-view-switcher" data-recurring-view>
                            <a class="recurring-view-trigger" href="#" data-recurring-view-trigger><?php echo billing_escape($currentRecurringViewTitle); ?> <i class="fa-solid fa-angle-down"></i></a>
                            <div class="recurring-view-menu" data-recurring-view-menu>
                                <div class="recurring-view-search"><input type="text" placeholder="Search" data-recurring-view-search></div>
                                <div class="recurring-view-options" data-recurring-view-options>
                                    <?php foreach ($allRecurringViews as $viewOption): ?>
                                        <?php $isActiveView = (string) ($viewOption['key'] ?? '') === (string) ($currentRecurringView['key'] ?? ''); ?>
                                        <?php $viewHref = !empty($viewOption['type']) && $viewOption['type'] === 'custom' ? 'recurring_expenses.php?view=' . rawurlencode((string) $viewOption['key']) : 'recurring_expenses.php?filter_by=' . rawurlencode((string) $viewOption['key']); ?>
                                        <a class="recurring-view-option<?php echo $isActiveView ? ' is-active' : ''; ?>" href="<?php echo billing_escape($viewHref); ?>" data-view-option>
                                            <span><?php echo billing_escape((string) ($viewOption['label'] ?? '')); ?></span>
                                            <i class="fa-regular fa-star recurring-view-option-star"></i>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                                <div class="recurring-view-footer"><a href="recurring_expenses.php?modal=custom-view"><i class="fa-solid fa-circle-plus"></i> New Custom View</a></div>
                            </div>
                        </div>
                        <div class="recurring-list-actions">
                            <a class="recurring-mini-btn is-green" href="recurring_expenses.php?new=1" aria-label="New recurring expense"><i class="fa-solid fa-plus"></i></a>
                            <a class="recurring-mini-btn" href="#" aria-label="More actions"><i class="fa-solid fa-ellipsis"></i></a>
                        </div>
                    </div>
                    <div class="recurring-profile-list">
                        <?php foreach ($recurringProfiles as $profile): ?>
                            <a class="recurring-profile-card<?php echo (int) $profile['id'] === $selectedRecurringId ? ' is-active' : ''; ?>" href="recurring_expenses.php?id=<?php echo (int) $profile['id']; ?>">
                                <span class="recurring-profile-check" aria-hidden="true"></span>
                                <span>
                                    <span class="recurring-profile-title"><?php echo billing_escape((string) ($profile['profile_name'] ?? '')); ?></span>
                                    <span class="recurring-profile-sub"><?php echo billing_escape((string) ($profile['category_name'] ?? '')); ?></span>
                                    <span class="recurring-profile-status"><?php echo billing_escape(strtoupper((string) ($profile['status_label'] ?? 'Active'))); ?></span>
                                    <span class="recurring-profile-next">Next expense date <?php echo billing_escape(date('d/m/Y', strtotime((string) ($profile['next_run_date'] ?? 'now')))); ?></span>
                                </span>
                                <span>
                                    <span class="recurring-profile-amount">&#8377;<?php echo billing_escape(number_format((float) ($profile['amount'] ?? 0), 2)); ?></span>
                                    <span class="recurring-profile-repeat"><?php echo billing_escape((string) ($profile['repeat_every'] ?? '')); ?>ly</span>
                                </span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>

                <aside class="recurring-detail-pane">
                    <div class="recurring-detail-head">
                        <h1 class="recurring-detail-title"><?php echo billing_escape((string) ($selectedRecurring['profile_name'] ?? '')); ?> <span class="recurring-badge"><?php echo billing_escape((string) ($selectedRecurring['status_label'] ?? 'Active')); ?></span></h1>
                        <div class="recurring-detail-tools">
                            <a class="recurring-detail-tool-link" href="recurring_expenses.php?new=1"><i class="fa-regular fa-pen-to-square"></i></a>
                            <a class="recurring-detail-tool-link" href="#">More <i class="fa-solid fa-angle-down"></i></a>
                            <a class="recurring-detail-close" href="recurring_expenses.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                        </div>
                    </div>
                    <div class="recurring-detail-tabs">
                        <a class="recurring-detail-tab is-active" href="#">Overview</a>
                        <a class="recurring-detail-tab" href="#">All Expenses</a>
                    </div>
                    <div class="recurring-overview">
                        <div class="recurring-kpis">
                            <div class="recurring-kpi">
                                <div class="recurring-kpi-icon is-green"><i class="fa-solid fa-wallet"></i></div>
                                <div><div class="recurring-kpi-value">&#8377;<?php echo billing_escape(number_format((float) ($selectedRecurring['amount'] ?? 0), 2)); ?></div><div class="recurring-kpi-label">Expense Amount</div></div>
                            </div>
                            <div class="recurring-kpi">
                                <div class="recurring-kpi-icon is-amber"><i class="fa-solid fa-rotate"></i></div>
                                <div><div class="recurring-kpi-value"><?php echo billing_escape((string) ($selectedRecurring['repeat_every'] ?? '')); ?>ly</div><div class="recurring-kpi-label">Repeats</div></div>
                            </div>
                            <div class="recurring-kpi">
                                <div class="recurring-kpi-icon is-blue"><i class="fa-solid fa-bookmark"></i></div>
                                <div><div class="recurring-kpi-value"><?php echo billing_escape(date('d/m/Y', strtotime((string) ($selectedRecurring['next_run_date'] ?? 'now')))); ?></div><div class="recurring-kpi-label">Next Expense Date</div></div>
                            </div>
                        </div>

                        <div class="recurring-summary">
                            <div class="recurring-summary-group">
                                <div class="recurring-summary-row"><div class="recurring-summary-label">Expense Account</div><div class="recurring-summary-value"><?php echo billing_escape((string) ($selectedRecurring['category_name'] ?? '')); ?></div></div>
                                <div class="recurring-summary-row"><div class="recurring-summary-label">Paid Through</div><div class="recurring-summary-value">Undeposited Funds</div></div>
                            </div>
                            <div class="recurring-summary-group is-accent">
                                <div class="recurring-summary-row"><div class="recurring-summary-label">Start On</div><div class="recurring-summary-value"><?php echo billing_escape(date('d/m/Y', strtotime((string) ($selectedRecurring['start_date'] ?? 'now')))); ?></div></div>
                                <div class="recurring-summary-row"><div class="recurring-summary-label">Ends On</div><div class="recurring-summary-value"><?php echo !empty($selectedRecurring['never_expires']) ? 'Goes on forever' : billing_escape(date('d/m/Y', strtotime((string) ($selectedRecurring['ends_on'] ?? 'now')))); ?></div></div>
                            </div>
                            <div class="recurring-summary-group">
                                <div class="recurring-summary-row"><div class="recurring-summary-label">Customer</div><div class="recurring-summary-value"><?php echo billing_escape((string) (($selectedRecurring['customer_name'] ?? '') !== '' ? $selectedRecurring['customer_name'] : '-')); ?></div></div>
                            </div>
                        </div>

                        <div class="recurring-section-title">OTHER DETAILS</div>
                        <div class="recurring-summary-row"><div class="recurring-summary-label">Notes</div><div class="recurring-summary-value"><?php echo billing_escape((string) (($selectedRecurring['notes_text'] ?? '') !== '' ? $selectedRecurring['notes_text'] : '-')); ?></div></div>

                        <div class="recurring-section-title">HISTORY</div>
                        <div class="recurring-history-item">
                            <div class="recurring-history-time"><?php echo billing_escape(date('d/m/Y h:i A')); ?></div>
                            <div class="recurring-history-icon"><i class="fa-regular fa-note-sticky"></i></div>
                            <div class="recurring-history-text">Recurring expense created for &#8377;<?php echo billing_escape(number_format((float) ($selectedRecurring['amount'] ?? 0), 2)); ?><br><small>by <?php echo billing_escape((string) ($organizationName ?: 'billing user')); ?></small></div>
                        </div>
                    </div>
                </aside>
            <?php elseif ($showNewForm): ?>
                <div class="recurring-head">
                    <h1><i class="fa-regular fa-bookmark"></i> New Recurring Expense</h1>
                    <a class="recurring-close" href="recurring_expenses.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <form method="post" class="recurring-form">
                    <?php if ($flashInfo): ?><div class="recurring-alert"><?php echo billing_escape($flashInfo); ?></div><?php endif; ?>
                    <?php if (isset($errors['save'])): ?><div class="recurring-alert" style="border-color:#ffd7d2;background:#fff2f1;color:#c4312b;"><?php echo billing_escape($errors['save']); ?></div><?php endif; ?>

                    <div class="recurring-section">
                        <div class="recurring-grid">
                            <div class="recurring-row">
                                <label class="recurring-label is-required" for="profile_name">Profile Name*</label>
                                <div class="recurring-control">
                                    <input id="profile_name" type="text" name="profile_name" value="<?php echo billing_escape($form['profile_name']); ?>">
                                    <?php if (isset($errors['profile_name'])): ?><div class="recurring-note" style="color:#d93025;"><?php echo billing_escape($errors['profile_name']); ?></div><?php endif; ?>
                                </div>
                            </div>

                            <div class="recurring-row">
                                <label class="recurring-label is-required" for="repeat_every">Repeat Every*</label>
                                <div class="recurring-control">
                                    <select id="repeat_every" name="repeat_every" data-repeat-every>
                                        <?php foreach (['Day', 'Week', 'Month', 'Year'] as $option): ?>
                                            <option value="<?php echo billing_escape($option); ?>" <?php echo $form['repeat_every'] === $option ? 'selected' : ''; ?>><?php echo billing_escape($option); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="recurring-row">
                                <label class="recurring-label" for="start_date">Start Date</label>
                                <div class="recurring-control">
                                    <input id="start_date" type="text" name="start_date" value="<?php echo billing_escape($form['start_date']); ?>" data-start-date>
                                    <div class="recurring-note">The recurring expense will be created on <span data-next-run><?php echo billing_escape($nextRunDate); ?></span></div>
                                    <?php if (isset($errors['start_date'])): ?><div class="recurring-note" style="color:#d93025;"><?php echo billing_escape($errors['start_date']); ?></div><?php endif; ?>
                                </div>
                            </div>

                            <div class="recurring-row">
                                <label class="recurring-label" for="ends_on">Ends On</label>
                                <div class="recurring-control">
                                    <input id="ends_on" type="text" name="ends_on" placeholder="dd/MM/yyyy" value="<?php echo billing_escape($form['ends_on']); ?>" data-ends-on <?php echo $form['never_expires'] === '1' ? 'disabled' : ''; ?>>
                                    <label class="recurring-inline-check">
                                        <input type="checkbox" name="never_expires" value="1" <?php echo $form['never_expires'] === '1' ? 'checked' : ''; ?> data-never-expires>
                                        <span>Never Expires</span>
                                    </label>
                                    <?php if (isset($errors['ends_on'])): ?><div class="recurring-note" style="color:#d93025;"><?php echo billing_escape($errors['ends_on']); ?></div><?php endif; ?>
                                </div>
                            </div>

                            <div class="recurring-row">
                                <label class="recurring-label is-required" for="category_name">Category Name*</label>
                                <div class="recurring-control">
                                    <select id="category_name" name="category_name">
                                        <option value=""></option>
                                        <?php foreach ($expenseAccounts as $account): ?>
                                            <option value="<?php echo billing_escape($account); ?>" <?php echo $form['category_name'] === $account ? 'selected' : ''; ?>><?php echo billing_escape($account); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (isset($errors['category_name'])): ?><div class="recurring-note" style="color:#d93025;"><?php echo billing_escape($errors['category_name']); ?></div><?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="recurring-section">
                        <div class="recurring-grid">
                            <div class="recurring-row">
                                <label class="recurring-label is-required" for="amount">Amount*</label>
                                <div class="recurring-control">
                                    <div class="recurring-amount">
                                        <select name="currency_code">
                                            <option value="INR" <?php echo $form['currency_code'] === 'INR' ? 'selected' : ''; ?>>INR</option>
                                        </select>
                                        <input id="amount" type="text" name="amount" value="<?php echo billing_escape($form['amount']); ?>">
                                    </div>
                                    <?php if (isset($errors['amount'])): ?><div class="recurring-note" style="color:#d93025;"><?php echo billing_escape($errors['amount']); ?></div><?php endif; ?>
                                </div>
                            </div>

                            <div class="recurring-row">
                                <label class="recurring-label" for="notes_text">Notes</label>
                                <div class="recurring-control"><textarea id="notes_text" name="notes_text" placeholder="Max. 500 characters"><?php echo billing_escape($form['notes_text']); ?></textarea></div>
                            </div>
                        </div>
                    </div>

                    <div class="recurring-section">
                        <div class="recurring-grid">
                            <div class="recurring-row">
                                <label class="recurring-label" for="customer_name">Customer Name</label>
                                <div class="recurring-control">
                                    <div class="recurring-customer">
                                        <select id="customer_name" name="customer_name">
                                            <option value=""></option>
                                            <?php foreach ($customers as $customer): ?>
                                                <?php $customerName = (string) ($customer['customer_name'] ?? ''); ?>
                                                <option value="<?php echo billing_escape($customerName); ?>" <?php echo $form['customer_name'] === $customerName ? 'selected' : ''; ?>><?php echo billing_escape($customerName); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="button" aria-label="Search customer"><i class="fa-solid fa-magnifying-glass"></i></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="recurring-footer">
                        <button class="recurring-btn recurring-btn--green" type="submit">Save</button>
                        <a class="recurring-btn" href="recurring_expenses.php">Cancel</a>
                    </div>
                </form>
            <?php else: ?>
                <?php if ($flashInfo): ?><div class="recurring-alert"><?php echo billing_escape($flashInfo); ?></div><?php endif; ?>
                <div class="recurring-table-head">
                    <div class="recurring-view-switcher" data-recurring-view>
                        <a class="recurring-view-trigger" href="#" data-recurring-view-trigger><?php echo billing_escape($currentRecurringViewTitle); ?> <i class="fa-solid fa-angle-down"></i></a>
                        <div class="recurring-view-menu" data-recurring-view-menu>
                            <div class="recurring-view-search"><input type="text" placeholder="Search" data-recurring-view-search></div>
                            <div class="recurring-view-options" data-recurring-view-options>
                                <?php foreach ($allRecurringViews as $viewOption): ?>
                                    <?php $isActiveView = (string) ($viewOption['key'] ?? '') === (string) ($currentRecurringView['key'] ?? ''); ?>
                                    <?php $viewHref = !empty($viewOption['type']) && $viewOption['type'] === 'custom' ? 'recurring_expenses.php?view=' . rawurlencode((string) $viewOption['key']) : 'recurring_expenses.php?filter_by=' . rawurlencode((string) $viewOption['key']); ?>
                                    <a class="recurring-view-option<?php echo $isActiveView ? ' is-active' : ''; ?>" href="<?php echo billing_escape($viewHref); ?>" data-view-option>
                                        <span><?php echo billing_escape((string) ($viewOption['label'] ?? '')); ?></span>
                                        <i class="fa-regular fa-star recurring-view-option-star"></i>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                            <div class="recurring-view-footer"><a href="recurring_expenses.php?modal=custom-view"><i class="fa-solid fa-circle-plus"></i> New Custom View</a></div>
                        </div>
                    </div>
                    <div class="recurring-table-actions">
                        <a class="recurring-table-new" href="recurring_expenses.php?new=1"><i class="fa-solid fa-plus"></i> New</a>
                        <a class="recurring-table-more" href="#" aria-label="More actions"><i class="fa-solid fa-ellipsis"></i></a>
                    </div>
                </div>
                <div class="recurring-table-wrap">
                    <table class="recurring-table">
                        <thead>
                            <tr>
                                <th style="width:48px;"><i class="fa-solid fa-sliders" style="color:#2a73ee;"></i></th>
                                <th style="width:48px;"><input type="checkbox" aria-label="Select all"></th>
                                <th>PROFILE NAME</th>
                                <th>CATEGORY NAME</th>
                                <th>CUSTOMER NAME</th>
                                <th>FREQUENCY</th>
                                <th>LAST EXPENSE DATE</th>
                                <th>NEXT EXPENSE DATE</th>
                                <th>STATUS</th>
                                <th style="text-align:right;">AMOUNT</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($recurringProfiles === []): ?>
                                <tr><td class="recurring-table-empty" colspan="10">No recurring expenses recorded yet.</td></tr>
                            <?php else: ?>
                                <?php foreach ($recurringProfiles as $profile): ?>
                                    <tr>
                                        <td></td>
                                        <td><input type="checkbox" aria-label="Select profile"></td>
                                        <td><a class="recurring-table-name" href="recurring_expenses.php?id=<?php echo (int) $profile['id']; ?>"><?php echo billing_escape((string) ($profile['profile_name'] ?? '')); ?></a></td>
                                        <td><?php echo billing_escape((string) ($profile['category_name'] ?? '')); ?></td>
                                        <td><?php echo billing_escape((string) ($profile['customer_name'] ?? '')); ?></td>
                                        <td><?php echo billing_escape((string) ($profile['repeat_every'] ?? '')); ?>ly</td>
                                        <td><?php echo billing_escape(date('d/m/Y', strtotime((string) ($profile['start_date'] ?? 'now')))); ?></td>
                                        <td><?php echo billing_escape(date('d/m/Y', strtotime((string) ($profile['next_run_date'] ?? 'now')))); ?></td>
                                        <td><span class="recurring-table-status"><?php echo billing_escape(strtoupper((string) ($profile['status_label'] ?? 'Active'))); ?></span></td>
                                        <td class="recurring-table-amount">&#8377;<?php echo billing_escape(number_format((float) ($profile['amount'] ?? 0), 2)); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </main>
        <?php endif; ?>
    </div>
</div>
<script>
(function () {
    var repeatInput = document.querySelector('[data-repeat-every]');
    var startInput = document.querySelector('[data-start-date]');
    var nextRun = document.querySelector('[data-next-run]');
    var neverExpires = document.querySelector('[data-never-expires]');
    var endsOn = document.querySelector('[data-ends-on]');

    function parseDate(value) {
        var parts = value.split('/');
        if (parts.length !== 3) return null;
        var day = parseInt(parts[0], 10);
        var month = parseInt(parts[1], 10) - 1;
        var year = parseInt(parts[2], 10);
        var date = new Date(year, month, day);
        return isNaN(date.getTime()) ? null : date;
    }

    function formatDate(date) {
        var dd = String(date.getDate()).padStart(2, '0');
        var mm = String(date.getMonth() + 1).padStart(2, '0');
        var yyyy = date.getFullYear();
        return dd + '/' + mm + '/' + yyyy;
    }

    function updateNextRun() {
        if (!repeatInput || !startInput || !nextRun) return;
        var date = parseDate(startInput.value);
        if (!date) return;
        if (repeatInput.value === 'Day') date.setDate(date.getDate() + 1);
        else if (repeatInput.value === 'Week') date.setDate(date.getDate() + 7);
        else if (repeatInput.value === 'Month') date.setMonth(date.getMonth() + 1);
        else if (repeatInput.value === 'Year') date.setFullYear(date.getFullYear() + 1);
        nextRun.textContent = formatDate(date);
    }

    function updateEndsOnState() {
        if (!neverExpires || !endsOn) return;
        endsOn.disabled = neverExpires.checked;
    }

    if (repeatInput) repeatInput.addEventListener('change', updateNextRun);
    if (startInput) startInput.addEventListener('input', updateNextRun);
    if (neverExpires) neverExpires.addEventListener('change', updateEndsOnState);
    updateNextRun();
    updateEndsOnState();

    document.querySelectorAll('[data-recurring-view]').forEach(function (root) {
        var trigger = root.querySelector('[data-recurring-view-trigger]');
        var menu = root.querySelector('[data-recurring-view-menu]');
        var search = root.querySelector('[data-recurring-view-search]');
        var options = Array.prototype.slice.call(root.querySelectorAll('[data-view-option]'));
        if (!trigger || !menu) return;

        trigger.addEventListener('click', function (event) {
            event.preventDefault();
            var opening = !menu.classList.contains('is-open');
            document.querySelectorAll('[data-recurring-view-menu].is-open').forEach(function (openMenu) {
                openMenu.classList.remove('is-open');
            });
            if (opening) {
                menu.classList.add('is-open');
                if (search) {
                    search.value = '';
                    options.forEach(function (option) {
                        option.style.display = 'flex';
                    });
                    var optionsWrap = root.querySelector('[data-recurring-view-options]');
                    if (optionsWrap) {
                        optionsWrap.scrollTop = 0;
                    }
                    search.focus();
                }
            }
        });

        if (search) {
            search.addEventListener('input', function () {
                var term = search.value.toLowerCase().trim();
                options.forEach(function (option) {
                    var label = option.textContent.toLowerCase();
                    option.style.display = term === '' || label.indexOf(term) !== -1 ? 'flex' : 'none';
                });
            });
        }
    });

    document.addEventListener('click', function (event) {
        document.querySelectorAll('[data-recurring-view]').forEach(function (root) {
            if (!root.contains(event.target)) {
                var menu = root.querySelector('[data-recurring-view-menu]');
                if (menu) {
                    menu.classList.remove('is-open');
                }
            }
        });
    });
}());
</script>
</body>
</html>



