<?php
require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$extraColumnCheck = $conn->query("SHOW COLUMNS FROM direct_deposit_setups LIKE 'extra_json'");
if ($extraColumnCheck && $extraColumnCheck->num_rows === 0) {
    $conn->query("ALTER TABLE direct_deposit_setups ADD COLUMN extra_json LONGTEXT DEFAULT NULL AFTER notes");
}

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$orgName = $_SESSION['org_name'] ?? 'demo';
$providers = settings_default_direct_deposit_providers();
$providerCode = trim((string) ($_GET['provider'] ?? ''));
$providerCode = isset($providers[$providerCode]) ? $providerCode : '';
$flow = trim((string) ($_GET['flow'] ?? ''));
$step = max(1, min(3, (int) ($_GET['step'] ?? 1)));
$showCreate = isset($_GET['create']) && $_GET['create'] === 'true';
$showHsbcModal = isset($_GET['hsbc_modal']) && $_GET['hsbc_modal'] === 'true';
$flash = settings_flash_message();
$errors = [];

$providerSetups = [];
foreach (array_keys($providers) as $code) {
    $providerSetups[$code] = settings_get_direct_deposit_setup($conn, $orgId, $code);
}

$decode_extra = static function (?string $json): array {
    $decoded = json_decode((string) $json, true);
    return is_array($decoded) ? $decoded : [];
};
$zohoExtra = settings_get_direct_deposit_onboarding_profile($conn, $orgId, 'zoho_payments');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['dd_action'] ?? ''));
    $postedProvider = trim((string) ($_POST['provider_code'] ?? ''));

    if ($action === 'save_setup' && isset($providers[$postedProvider])) {
        $providerCode = $postedProvider;
        $customerId = trim((string) ($_POST['customer_id'] ?? ''));
        $passwordPartOne = trim((string) ($_POST['password_part_one'] ?? ''));
        $passwordPartTwo = trim((string) ($_POST['password_part_two'] ?? ''));
        $bankAccountLabel = trim((string) ($_POST['bank_account_label'] ?? 'B2L Mobitech - Bank Account'));
        $bankAccountNumber = trim((string) ($_POST['bank_account_number'] ?? ''));
        $liveBalance = trim((string) ($_POST['live_balance'] ?? ''));
        $registeredMobile = trim((string) ($_POST['registered_mobile'] ?? ''));
        $secretPin = trim((string) ($_POST['secret_pin'] ?? ''));
        $confirmSecretPin = trim((string) ($_POST['confirm_secret_pin'] ?? ''));
        $notes = trim((string) ($_POST['notes'] ?? ''));

        if ($customerId === '') $errors[] = 'Customer ID is required.';
        if ($passwordPartOne === '' || $passwordPartTwo === '') $errors[] = 'Both password halves are required.';
        if ($bankAccountNumber === '' || !preg_match('/^\d{9,18}$/', $bankAccountNumber)) $errors[] = 'This Bank account has an invalid account number.';
        if ($liveBalance === '' || !is_numeric($liveBalance)) $errors[] = 'Live Balance must be a valid number.';
        if ($registeredMobile === '' || !preg_match('/^\d{10}$/', $registeredMobile)) $errors[] = 'Registered Mobile Number must be 10 digits.';
        if ($secretPin === '' || !preg_match('/^\d{6}$/', $secretPin)) $errors[] = 'Secret PIN must be exactly 6 digits.';
        if ($secretPin !== $confirmSecretPin) $errors[] = 'Confirm Secret PIN must match Secret PIN.';

        if (!$errors) {
            $saved = settings_save_direct_deposit_setup($conn, $orgId, $providerCode, [
                'status' => 'active',
                'customer_id' => $customerId,
                'password_part_one' => $passwordPartOne,
                'password_part_two' => $passwordPartTwo,
                'bank_account_label' => $bankAccountLabel,
                'bank_account_number' => $bankAccountNumber,
                'live_balance' => $liveBalance,
                'registered_mobile' => $registeredMobile,
                'secret_pin' => $secretPin,
                'notes' => $notes,
                'extra_json' => $providerSetups[$providerCode]['extra_json'] ?? '',
            ]);
            if ($saved) {
                settings_set_flash('success', $providers[$providerCode]['name'] . ' was configured successfully.');
                header('Location: direct_deposits.php?provider=' . urlencode($providerCode));
                exit();
            }
            $errors[] = 'Unable to save direct deposit settings.';
        }

        $providerSetups[$providerCode] = array_merge($providerSetups[$providerCode], [
            'customer_id' => $customerId,
            'password_part_one' => $passwordPartOne,
            'password_part_two' => $passwordPartTwo,
            'bank_account_label' => $bankAccountLabel,
            'bank_account_number' => $bankAccountNumber,
            'live_balance' => $liveBalance,
            'registered_mobile' => $registeredMobile,
            'secret_pin' => $secretPin,
            'notes' => $notes,
        ]);
    }

    if ($action === 'hsbc_initiate') {
        settings_save_direct_deposit_setup($conn, $orgId, 'hsbc_bank', [
            'status' => 'initiated',
            'customer_id' => '',
            'password_part_one' => '',
            'password_part_two' => '',
            'bank_account_label' => 'HSBC Payroll Account',
            'bank_account_number' => '',
            'live_balance' => '',
            'registered_mobile' => '',
            'secret_pin' => '',
            'notes' => 'HSBC setup initiated.',
            'extra_json' => '',
        ]);
        settings_set_flash('success', 'HSBC connection initiated successfully.');
        header('Location: direct_deposits.php');
        exit();
    }

    if ($action === 'hsbc_delete') {
        settings_save_direct_deposit_setup($conn, $orgId, 'hsbc_bank', [
            'status' => 'draft',
            'customer_id' => '',
            'password_part_one' => '',
            'password_part_two' => '',
            'bank_account_label' => '',
            'bank_account_number' => '',
            'live_balance' => '',
            'registered_mobile' => '',
            'secret_pin' => '',
            'notes' => '',
            'extra_json' => '',
        ]);
        settings_set_flash('success', 'HSBC connection removed.');
        header('Location: direct_deposits.php');
        exit();
    }

    if ($action === 'zoho_owner_confirm') {
        if (!isset($_POST['owner_confirm'])) {
            $errors[] = 'Please confirm authorization to continue.';
        } else {
            $zohoExtra['owner_confirmed'] = 1;
            $zohoExtra['onboarding_step'] = 1;
            settings_save_direct_deposit_onboarding_profile($conn, $orgId, 'zoho_payments', $zohoExtra);
            header('Location: direct_deposits.php?provider=zoho_payments&flow=onboarding&step=1');
            exit();
        }
    }

    if ($action === 'zoho_onboarding_save') {
        foreach ($_POST as $key => $value) {
            if (in_array($key, ['dd_action', 'provider_code'], true)) {
                continue;
            }
            $zohoExtra[$key] = is_string($value) ? trim($value) : $value;
        }
        $zohoExtra['onboarding_step'] = $step;
        settings_save_direct_deposit_onboarding_profile($conn, $orgId, 'zoho_payments', $zohoExtra);
        settings_save_direct_deposit_setup($conn, $orgId, 'zoho_payments', [
            'status' => $step >= 3 ? 'active' : 'draft',
            'customer_id' => '',
            'password_part_one' => '',
            'password_part_two' => '',
            'bank_account_label' => 'B2L Mobitech - Bank Account',
            'bank_account_number' => '',
            'live_balance' => '',
            'registered_mobile' => '',
            'secret_pin' => '',
            'notes' => 'B2L Payments onboarding in progress',
            'extra_json' => $providerSetups['zoho_payments']['extra_json'] ?? '',
        ]);
        if ($step >= 3) {
            settings_set_flash('success', 'B2L Payments onboarding saved successfully.');
            header('Location: direct_deposits.php');
            exit();
        }
        header('Location: direct_deposits.php?provider=zoho_payments&flow=onboarding&step=' . ($step + 1));
        exit();
    }
}

$selectedSetup = $providerCode !== '' ? $providerSetups[$providerCode] : null;
$hsbcSetup = $providerSetups['hsbc_bank'];
$isHsbcInitiated = (($hsbcSetup['status'] ?? 'draft') === 'initiated');
$ownerName = strtoupper((string) ($_SESSION['username'] ?? 'Account Owner'));
$ownerEmail = (string) ($_SESSION['user'] ?? 'owner@example.com');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Direct Deposits | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <style>
    .dd-shell{display:grid;grid-template-columns:220px minmax(0,1fr);min-height:calc(100vh - 74px);background:#f8fbff;border:1px solid #e7edf8;border-radius:18px;overflow:hidden}
    .dd-side{background:#fff;border-right:1px solid #e7edf8;padding:16px 0}
    .dd-brand{display:flex;align-items:center;gap:12px;padding:0 18px 14px;border-bottom:1px solid #eef2f7}
    .dd-brand-badge{width:38px;height:38px;border:1px solid #e5e7eb;border-radius:10px;display:flex;align-items:center;justify-content:center;color:#ef4444;background:#fff}
    .dd-brand h2{margin:0;font-size:16px}.dd-brand small{display:block;color:#64748b;margin-top:4px}
    .dd-nav-group{padding:16px 0 0}.dd-nav-title{padding:0 18px 10px;font-size:12px;font-weight:800;color:#94a3b8;text-transform:uppercase}
    .dd-nav a{display:flex;align-items:center;gap:10px;padding:11px 18px;color:#334155;text-decoration:none}.dd-nav a.active{background:#3b82f6;color:#fff}
    .dd-main{background:#f8fbff}.dd-top{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;border-bottom:1px solid #e7edf8;background:#fff}
    .dd-search{width:320px;max-width:100%;height:38px;border:1px solid #e5e7eb;border-radius:12px;display:flex;align-items:center;gap:10px;padding:0 14px;background:#f8fafc;color:#94a3b8}
    .dd-close{display:inline-flex;align-items:center;gap:10px;padding:10px 14px;border:1px solid #e5e7eb;border-radius:12px;background:#fff;color:#475569;text-decoration:none}
    .dd-content{padding:22px}.dd-content h1{margin:0 0 18px;font-size:18px}
    .deposit-card,.platform-top{display:grid;grid-template-columns:164px 1fr auto;gap:18px;align-items:center;background:#fff;border:1px solid #e7edf8;border-radius:16px;padding:20px;margin-bottom:18px}
    .platform-card{background:#fff;border:1px solid #e7edf8;border-radius:16px;overflow:hidden;margin-bottom:18px}
    .platform-how{border-top:1px solid #eef2f7;background:#fbfdff;padding:16px 20px}.platform-how h3{margin:0 0 10px;font-size:16px}.platform-how p{margin:0 0 16px;color:#64748b}
    .chip-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.chip{padding:6px 12px;border-radius:999px;background:#eef2ff;color:#334155;font-weight:700;font-size:13px}.chip.green{background:#dff7ef;color:#0f766e}.chip.orange{background:#ffedd5;color:#c2410c}
    .bank-logo{height:86px;border-radius:16px;background:#f7f8ff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:20px;color:#1d4ed8}
    .bank-logo.hsbc{color:#dc2626}.deposit-copy h3{margin:0 0 8px;font-size:17px}.deposit-copy p{margin:0;color:#64748b;line-height:1.5}.deposit-copy .sub-link{display:inline-block;margin-top:8px;color:#60a5fa;text-decoration:none}
    .deposit-btn{display:inline-flex;align-items:center;justify-content:center;height:42px;padding:0 16px;border:none;border-radius:10px;background:#3b82f6;color:#fff;text-decoration:none;font-weight:700;cursor:pointer}
    .deposit-btn.muted{background:#fff;border:1px solid #d7deea;color:#475569}.trial-note,.setup-note{margin-top:16px;padding:14px 18px;border-radius:12px;background:#fff7ed;color:#9a3412}.setup-note ol{margin:8px 0 0 18px;padding:0;line-height:1.7}
    .status-badge{display:inline-flex;align-items:center;padding:4px 10px;border:1px solid #93c5fd;border-radius:999px;color:#3b82f6;font-size:12px;font-weight:800;margin-left:8px}
    .bank-actions{display:flex;align-items:center;gap:10px}
    .modal{position:fixed;inset:0;display:none;align-items:center;justify-content:center;z-index:80}.modal.open{display:flex}.modal-backdrop{position:absolute;inset:0;background:rgba(15,23,42,.45)}
    .modal-card{position:relative;width:560px;max-width:92vw;background:#fff;border-radius:18px;box-shadow:0 28px 60px rgba(15,23,42,.24);overflow:hidden}.modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 24px;border-bottom:1px solid #eef2f7}.modal-head h2{margin:0;font-size:18px}
    .modal-body{padding:20px 24px}.modal-close{border:none;background:#f1f5f9;width:30px;height:30px;border-radius:50%;cursor:pointer;color:#64748b}
    .steps-list{display:grid;gap:14px;margin:0 0 18px}.steps-list li{display:flex;gap:12px;line-height:1.5}.step-index{width:28px;height:28px;border-radius:50%;border:1px solid #d7deea;display:flex;align-items:center;justify-content:center;color:#64748b;font-weight:800;flex:0 0 auto}
    .inline-check{display:flex;align-items:flex-start;gap:10px;color:#374151}.modal-foot{display:flex;align-items:center;gap:10px;padding:14px 24px;border-top:1px solid #eef2f7}
    .setup-layout{display:grid;grid-template-columns:minmax(0,1fr) 360px;gap:0;background:#fff;border:1px solid #e7edf8;border-radius:18px;overflow:hidden}.setup-main{padding:22px 28px}.setup-aside{padding:22px 24px;border-left:1px solid #eef2f7;background:#fff}
    .setup-header{display:flex;align-items:center;gap:16px;padding:18px 22px;border-bottom:1px solid #eef2f7;background:#fff}.setup-header h2{margin:0;font-size:18px}.wizard-steps{margin-left:auto;display:flex;align-items:center;gap:10px}.wizard-step{width:30px;height:30px;border-radius:50%;border:1px solid #cbd5e1;display:flex;align-items:center;justify-content:center;font-weight:800;color:#64748b;background:#fff}.wizard-step.active{background:#2563eb;border-color:#2563eb;color:#fff}
    .wizard-title{margin:18px 0 6px;font-size:16px}.wizard-sub{margin:0 0 18px;color:#64748b}.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px 24px}.form-span{grid-column:1 / -1}.field label{display:block;margin:0 0 8px;font-weight:700;font-size:14px}.field input,.field select,.field textarea{width:100%;height:42px;border:1px solid #dbe3ef;border-radius:10px;padding:0 12px;font:inherit}.field textarea{height:100px;padding:12px;resize:vertical}.field small{display:block;margin-top:8px;color:#94a3b8;line-height:1.5}
    .save-row{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:24px;padding-top:18px;border-top:1px solid #eef2f7}.req-note{color:#ef4444;font-size:13px}
    @media (max-width:1080px){.dd-shell,.setup-layout{grid-template-columns:1fr}.dd-side{display:none}.setup-aside{border-left:none;border-top:1px solid #eef2f7}.deposit-card,.platform-top{grid-template-columns:1fr}}
  </style>
</head>
<body class="orgprofile-page">
  <?php settings_render_header($orgName, 'dashboard.php', 'fa-building-columns'); ?>
  <main style="padding:18px;">
    <section style="padding:0">
      <div class="dd-shell">
        <aside class="dd-side">
          <div class="dd-brand">
            <div class="dd-brand-badge"><i class="fa-regular fa-credit-card"></i></div>
            <div><h2>All Settings</h2><small><?php echo htmlspecialchars($orgName); ?></small></div>
          </div>
          <div class="dd-nav-group">
            <div class="dd-nav-title">Organisation Settings</div>
            <nav class="dd-nav">
              <a href="organization.php">Organisation</a>
              <a href="users.php">Users and Roles</a>
              <a href="tax_details.php">Taxes</a>
              <a href="settings.php">Setup & Configurations</a>
              <a href="actions.php">Customisations</a>
              <a href="workflow_rules.php">Automations</a>
            </nav>
          </div>
          <div class="dd-nav-group">
            <div class="dd-nav-title">Module Settings</div>
            <nav class="dd-nav">
              <a href="settings.php">General</a>
              <a class="active" href="direct_deposits.php">Direct Deposits</a>
            </nav>
          </div>
          <div class="dd-nav-group">
            <div class="dd-nav-title">Extensions & Developer Data</div>
            <nav class="dd-nav">
              <a href="connections.php">Integrations</a>
              <a href="workflow_logs.php">Developer Data</a>
            </nav>
          </div>
        </aside>

        <div class="dd-main">
          <div class="dd-top">
            <div class="dd-search"><i class="fa-solid fa-magnifying-glass"></i><span>Search settings ( / )</span></div>
            <a class="dd-close" href="settings.php">Close Settings <i class="fa-solid fa-xmark" style="color:#f87171"></i></a>
          </div>

          <div class="dd-content">
            <?php if (!empty($flash['message'])) { ?><div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div><?php } ?>
            <?php if ($errors) { ?><div class="alert-err"><div class="alert-err-title">Please fix the following:</div><ul><?php foreach ($errors as $error) { ?><li><?php echo htmlspecialchars($error); ?></li><?php } ?></ul></div><?php } ?>

            <?php if ($providerCode === 'yes_bank') { ?>
              <div class="setup-layout">
                <div>
                  <div class="setup-header">
                    <div class="bank-logo" style="width:128px;height:54px">YES BANK</div>
                    <h2>Direct Deposit</h2>
                  </div>
                  <form class="setup-main" method="post">
                    <input type="hidden" name="dd_action" value="save_setup">
                    <input type="hidden" name="provider_code" value="yes_bank">
                    <div class="form-grid">
                      <div class="field form-span"><label>Customer ID <span class="req">*</span></label><input type="text" name="customer_id" value="<?php echo htmlspecialchars((string) ($selectedSetup['customer_id'] ?? '')); ?>"></div>
                      <div class="field"><label>First Half of Password <span class="req">*</span></label><input type="password" name="password_part_one" value="<?php echo htmlspecialchars((string) ($selectedSetup['password_part_one'] ?? '')); ?>"></div>
                      <div class="field"><label>Second Half of Password <span class="req">*</span></label><input type="password" name="password_part_two" value="<?php echo htmlspecialchars((string) ($selectedSetup['password_part_two'] ?? '')); ?>"></div>
                      <div class="field form-span"><label>Yes Bank Account <span class="req">*</span></label><input type="text" name="bank_account_label" value="<?php echo htmlspecialchars((string) ($selectedSetup['bank_account_label'] ?? 'B2L Mobitech - Bank Account')); ?>"><?php if (in_array('This Bank account has an invalid account number.', $errors, true)) { ?><small style="color:#ef4444">This Bank account has an invalid account number.</small><?php } ?><small><a href="#" style="color:#3b82f6;text-decoration:none">Edit Bank Account</a></small></div>
                      <div class="field"><label>Live Balance <span class="req">*</span></label><input type="text" name="live_balance" value="<?php echo htmlspecialchars((string) ($selectedSetup['live_balance'] ?? '')); ?>"></div>
                      <div class="field"><label>Registered Mobile Number <span class="req">*</span></label><input type="text" name="registered_mobile" value="<?php echo htmlspecialchars((string) ($selectedSetup['registered_mobile'] ?? '')); ?>"></div>
                      <div class="field"><label>Secret PIN <span class="req">*</span></label><input type="password" name="secret_pin" value="<?php echo htmlspecialchars((string) ($selectedSetup['secret_pin'] ?? '')); ?>"></div>
                      <div class="field"><label>Confirm Secret PIN <span class="req">*</span></label><input type="password" name="confirm_secret_pin" value="<?php echo htmlspecialchars((string) ($selectedSetup['secret_pin'] ?? '')); ?>"></div>
                    </div>
                    <p style="margin:18px 0 0;color:#475569;line-height:1.6">Note: This is a user-level integration. Other users of your organization will not be able to initiate payments on behalf of you.</p>
                    <p style="margin:14px 0 0;color:#475569">By clicking Save, you agree to our <a href="#" style="color:#3b82f6;text-decoration:none">Terms and Conditions</a></p>
                    <div class="save-row"><div></div><div style="display:flex;gap:10px"><button class="deposit-btn" type="submit">Save</button><a class="deposit-btn muted" href="direct_deposits.php">Cancel</a></div></div>
                  </form>
                </div>
                <aside class="setup-aside">
                  <h3 style="margin:0 0 10px">Transaction Charges</h3>
                  <p style="margin:0 0 16px;color:#475569;line-height:1.6">Transaction charges are applicable as per your agreement with Yes Bank. No additional fee will be charged by B2L Mobitech.</p>
                  <h3 style="margin:18px 0 10px">How to configure this integration?</h3>
                  <ul style="margin:0;padding-left:18px;line-height:1.8;color:#334155">
                    <li>Enter the unique Customer ID of your corporate account after the bank enables API Banking for your account.</li>
                    <li>Enter the password provided by the bank. The bank will share the password in two halves.</li>
                    <li>Enter your live account balance with the exact decimal numbers as provided by YES Bank.</li>
                    <li>Create a six-digit PIN to authorise all transactions initiated from B2L Mobitech.</li>
                    <li>Select the YES Bank account that you want to integrate.</li>
                    <li>Click Save to integrate your YES Bank account with B2L Mobitech.</li>
                  </ul>
                </aside>
              </div>
            <?php } ?>
            <?php if ($providerCode === 'zoho_payments' && $flow === 'onboarding') { ?>
              <?php $stepTitles = [1 => 'Business Profile', 2 => 'Business Contacts', 3 => 'Review']; ?>
              <div class="setup-layout">
                <div>
                  <div class="setup-header">
                    <div class="bank-logo" style="width:118px;height:52px;font-size:18px">B2L Payments</div>
                    <div class="wizard-steps"><?php for ($i = 1; $i <= 3; $i++) { ?><div class="wizard-step <?php echo $step === $i ? 'active' : ''; ?>"><?php echo $i; ?></div><?php } ?></div>
                  </div>
                  <form class="setup-main" method="post">
                    <input type="hidden" name="dd_action" value="zoho_onboarding_save">
                    <input type="hidden" name="provider_code" value="zoho_payments">
                    <h2 class="wizard-title"><?php echo htmlspecialchars($stepTitles[$step]); ?></h2>
                    <p class="wizard-sub">Provide basic details about your business. Ensure that the information you provide matches the legal documents of your business.</p>
                    <?php if ($step === 1) { ?>
                      <div class="form-grid">
                        <div class="field"><label>Business PAN <span class="req">*</span></label><input type="text" name="business_pan" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_pan'] ?? '')); ?>" placeholder="AAAAA0000A"><small>For individuals or sole proprietors, enter your personal PAN.</small></div>
                        <div class="field"><label>Business Type <span class="req">*</span></label><select name="business_type"><option>Select your business type</option><option <?php echo (($zohoExtra['business_type'] ?? '') === 'Private Limited') ? 'selected' : ''; ?>>Private Limited</option><option <?php echo (($zohoExtra['business_type'] ?? '') === 'Sole Proprietor') ? 'selected' : ''; ?>>Sole Proprietor</option><option <?php echo (($zohoExtra['business_type'] ?? '') === 'Partnership') ? 'selected' : ''; ?>>Partnership</option></select></div>
                        <div class="field"><label>Business Name <span class="req">*</span></label><input type="text" name="business_name" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_name'] ?? 'Zylker')); ?>"></div>
                        <div class="field"><label>Trade Name <span class="req">*</span></label><input type="text" name="trade_name" value="<?php echo htmlspecialchars((string) ($zohoExtra['trade_name'] ?? '')); ?>"></div>
                        <div class="field form-span"><label>Business Address <span class="req">*</span></label><input type="text" name="business_address_1" placeholder="Building number and name, Street, Area" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_address_1'] ?? '')); ?>"></div>
                        <div class="field form-span"><input type="text" name="business_address_2" placeholder="Address Line 2 (optional)" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_address_2'] ?? '')); ?>"></div>
                        <div class="field form-span"><input type="text" name="business_address_3" placeholder="Address Line 3 (optional)" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_address_3'] ?? '')); ?>"></div>
                        <div class="field"><input type="text" name="country" value="<?php echo htmlspecialchars((string) ($zohoExtra['country'] ?? 'India')); ?>"></div>
                        <div class="field"><select name="state"><option>State</option><option <?php echo (($zohoExtra['state'] ?? '') === 'Tamil Nadu') ? 'selected' : ''; ?>>Tamil Nadu</option><option <?php echo (($zohoExtra['state'] ?? '') === 'Karnataka') ? 'selected' : ''; ?>>Karnataka</option></select></div>
                        <div class="field"><input type="text" name="city" placeholder="Town / City" value="<?php echo htmlspecialchars((string) ($zohoExtra['city'] ?? '')); ?>"></div>
                        <div class="field"><input type="text" name="pin_code" placeholder="PIN Code" value="<?php echo htmlspecialchars((string) ($zohoExtra['pin_code'] ?? '')); ?>"></div>
                        <div class="field"><label>Business Phone Number <span class="req">*</span></label><input type="text" name="business_phone" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_phone'] ?? '')); ?>"><small><a href="#" style="color:#60a5fa;text-decoration:none">+ Verify Phone Number</a></small></div>
                        <div class="field"><label>Industry <span class="req">*</span></label><select name="industry"><option>Select your industry</option><option <?php echo (($zohoExtra['industry'] ?? '') === 'Technology') ? 'selected' : ''; ?>>Technology</option><option <?php echo (($zohoExtra['industry'] ?? '') === 'Retail') ? 'selected' : ''; ?>>Retail</option></select></div>
                        <div class="field"><label>Business Website <span class="req">*</span></label><input type="text" name="business_website" placeholder="www.example.com" value="<?php echo htmlspecialchars((string) ($zohoExtra['business_website'] ?? '')); ?>"></div>
                        <div class="field form-span"><label>Business Description <span class="req">*</span></label><textarea name="business_description"><?php echo htmlspecialchars((string) ($zohoExtra['business_description'] ?? '')); ?></textarea></div>
                        <div class="field"><label>Annual Turnover <span class="req">*</span></label><input type="text" name="annual_turnover" value="<?php echo htmlspecialchars((string) ($zohoExtra['annual_turnover'] ?? '')); ?>" placeholder="₹"></div>
                        <div class="field"><label>Average Number of Transactions Per Day <span class="req">*</span></label><input type="text" name="transactions_per_day" value="<?php echo htmlspecialchars((string) ($zohoExtra['transactions_per_day'] ?? '')); ?>"></div>
                        <div class="field"><label>Average Value Per Transaction <span class="req">*</span></label><input type="text" name="avg_transaction_value" value="<?php echo htmlspecialchars((string) ($zohoExtra['avg_transaction_value'] ?? '')); ?>" placeholder="₹"></div>
                      </div>
                    <?php } elseif ($step === 2) { ?>
                      <div class="form-grid">
                        <div class="field"><label>Primary Contact Name <span class="req">*</span></label><input type="text" name="contact_name" value="<?php echo htmlspecialchars((string) ($zohoExtra['contact_name'] ?? ($_SESSION['username'] ?? ''))); ?>"></div>
                        <div class="field"><label>Email Address <span class="req">*</span></label><input type="email" name="contact_email" value="<?php echo htmlspecialchars((string) ($zohoExtra['contact_email'] ?? ($_SESSION['user'] ?? ''))); ?>"></div>
                        <div class="field"><label>Mobile Number <span class="req">*</span></label><input type="text" name="contact_mobile" value="<?php echo htmlspecialchars((string) ($zohoExtra['contact_mobile'] ?? '')); ?>"></div>
                        <div class="field"><label>Designation <span class="req">*</span></label><input type="text" name="contact_role" value="<?php echo htmlspecialchars((string) ($zohoExtra['contact_role'] ?? 'Owner')); ?>"></div>
                      </div>
                    <?php } else { ?>
                      <div class="form-grid">
                        <div class="field form-span"><label>Review Notes</label><textarea name="review_notes"><?php echo htmlspecialchars((string) ($zohoExtra['review_notes'] ?? '')); ?></textarea></div>
                        <div class="field form-span"><small>Review your business profile before finishing the B2L Payments onboarding flow.</small></div>
                      </div>
                    <?php } ?>
                    <div class="save-row"><div class="req-note">* Indicates mandatory fields</div><button class="deposit-btn" type="submit"><?php echo $step === 3 ? 'Save and Finish' : 'Save and Next'; ?></button></div>
                  </form>
                </div>
                <aside class="setup-aside">
                  <h3 style="margin:0 0 12px">Quick Help</h3>
                  <p style="margin:0;color:#64748b;line-height:1.6">Keep your legal business details, address, phone number, website, and transaction estimates ready before you continue.</p>
                </aside>
              </div>
            <?php } ?>
            <?php if ($providerCode !== 'yes_bank' && !($providerCode === 'zoho_payments' && $flow === 'onboarding')) { ?>
              <h1>Direct Deposits</h1>
              <div class="platform-card">
                <div class="platform-top">
                  <div class="bank-logo" style="font-size:18px">B2L Payments</div>
                  <div class="deposit-copy">
                    <h3>B2L Payments - Payouts</h3>
                    <p>Pay employees directly from B2L Mobitech. Add funds to your B2L Payments Payout Account and securely disburse salaries to multiple bank accounts without leaving the app.</p>
                    <div style="margin-top:10px;color:#0f766e">Platform Fee: ₹3.00 per employee per pay run (excl. 18% GST)</div>
                  </div>
                  <a class="deposit-btn" href="direct_deposits.php?provider=zoho_payments&create=true">Set Up Now</a>
                </div>
                <div class="platform-how">
                  <h3>How it works?</h3>
                  <p>Add funds from your verified bank account into B2L Payments' Payout Account. On pay day, you can disburse salaries directly from B2L Mobitech to all employee bank accounts.</p>
                  <div class="chip-row"><span class="chip">Your verified Bank account</span><span class="chip green">Add Funds</span><span class="chip">B2L Payments Payout Account</span><span class="chip orange">Initiate Pay Run</span><span class="chip">Employee Bank Accounts</span></div>
                </div>
              </div>
              <div class="deposit-card">
                <div class="bank-logo">ICICI Bank</div>
                <div class="deposit-copy"><h3>ICICI Bank</h3><p>Transfer salaries directly to your employees' bank accounts.</p><div class="trial-note">You are currently in the Trial Plan. To configure ICICI Bank Integration, upgrade your plan. <a href="subscriptions.php" style="color:#3b82f6;text-decoration:none">Upgrade Plan</a></div></div>
                <a class="deposit-btn muted" href="subscriptions.php">Upgrade Plan</a>
              </div>
              <div class="deposit-card">
                <div class="bank-logo">YES BANK</div>
                <div class="deposit-copy"><h3>YES Bank</h3><p>Transfer salaries directly to your employees' bank accounts.</p><a class="sub-link" href="#">New to YES Bank? Request for a New Account</a></div>
                <a class="deposit-btn" href="direct_deposits.php?provider=yes_bank">Set Up Now</a>
              </div>
              <div class="deposit-card">
                <div class="bank-logo hsbc">HSBC</div>
                <div class="deposit-copy">
                  <h3>HSBC Bank <?php if ($isHsbcInitiated) { ?><span class="status-badge">INITIATED</span><?php } ?></h3>
                  <p>Transfer salaries directly to your employees' bank accounts.</p>
                  <?php if ($isHsbcInitiated) { ?><div class="setup-note"><strong>To complete the Setup:</strong><ol><li>Log in to the Portal and choose the accounts you want to connect.</li><li>Once redirected to B2L Mobitech, configure your Secret PIN, choose the accounts to make payments, and provide users access to complete the setup.</li><li>Select the accounts in B2L Mobitech to fetch live balances.</li></ol></div><?php } ?>
                </div>
                <div class="bank-actions">
                  <?php if ($isHsbcInitiated) { ?>
                    <a class="deposit-btn muted" href="direct_deposits.php">Check status</a>
                    <form method="post"><input type="hidden" name="dd_action" value="hsbc_delete"><button class="deposit-btn muted" type="submit">Delete Connection</button></form>
                  <?php } else { ?>
                    <a class="deposit-btn" href="direct_deposits.php?hsbc_modal=true">Set Up Now</a>
                  <?php } ?>
                </div>
              </div>
            <?php } ?>
          </div>
        </div>
      </div>
    </section>
  </main>

  <div class="modal <?php echo $showHsbcModal ? 'open' : ''; ?>">
    <div class="modal-backdrop"></div>
    <div class="modal-card">
      <div class="modal-head"><h2>Connect with HSBC Bank</h2><a class="modal-close" href="direct_deposits.php"><i class="fa-solid fa-xmark"></i></a></div>
      <div class="modal-body">
        <div style="font-size:17px;font-weight:700;margin-bottom:16px">Follow these steps to connect your HSBC account with B2L Mobitech:</div>
        <ol class="steps-list"><li><span class="step-index">1</span><span>Click Proceed to Connect, and you will be redirected to HSBC's portal.</span></li><li><span class="step-index">2</span><span>Sign in to HSBC and select the bank accounts you want to connect.</span></li><li><span class="step-index">3</span><span>Once redirected back to B2L Mobitech, configure your Secret PIN, select payment accounts, and provide user access to complete the setup.</span></li><li><span class="step-index">4</span><span>Select accounts in B2L Mobitech to view live balances.</span></li></ol>
        <div style="padding:16px 0;border-top:1px solid #eef2f7;border-bottom:1px solid #eef2f7;margin:18px 0"><div style="font-size:16px;font-weight:700;margin-bottom:10px">Transaction Charges</div><div style="color:#475569;line-height:1.6">Any applicable transaction charges are determined by your agreement with HSBC. B2L Mobitech does not charge any additional fees.</div></div>
        <div style="border-left:3px solid #fb923c;padding-left:14px;color:#475569;line-height:1.6">Note: The HSBC login page is valid for 5 minutes. Log in and complete the setup instantly to avoid rejections.</div>
        <div style="margin-top:18px" class="inline-check"><input type="checkbox"><span>I have read and agree to the <a href="#" style="color:#3b82f6;text-decoration:none">Terms and Conditions</a>.</span></div>
      </div>
      <div class="modal-foot"><form method="post"><input type="hidden" name="dd_action" value="hsbc_initiate"><button class="deposit-btn" type="submit">Proceed</button></form><a class="deposit-btn muted" href="direct_deposits.php">Cancel</a></div>
    </div>
  </div>

  <div class="modal <?php echo ($providerCode === 'zoho_payments' && $showCreate) ? 'open' : ''; ?>">
    <div class="modal-backdrop"></div>
    <div class="modal-card">
      <div class="modal-head"><h2>Before You Setup B2L Payments</h2><a class="modal-close" href="direct_deposits.php"><i class="fa-solid fa-xmark"></i></a></div>
      <form method="post">
        <div class="modal-body">
          <p style="margin:0 0 18px;color:#475569;line-height:1.6">Ensure you are either the business owner or an authorized person to share business details, set up and manage online payments.</p>
          <div style="border-top:1px solid #eef2f7;padding-top:18px"><div style="font-size:18px;font-weight:700;margin-bottom:14px">Account Owner</div><div style="display:flex;align-items:center;gap:14px;padding:16px;border:1px solid #eef2f7;border-radius:14px;background:#fbfdff"><div style="width:54px;height:54px;border-radius:50%;background:#dbeafe;display:flex;align-items:center;justify-content:center;color:#1d4ed8;font-weight:800"><?php echo htmlspecialchars(substr($ownerName, 0, 1)); ?></div><div><div style="font-weight:800"><?php echo htmlspecialchars($ownerName); ?></div><div style="color:#64748b"><?php echo htmlspecialchars($ownerEmail); ?></div></div></div></div>
          <div style="margin-top:18px" class="inline-check"><input type="checkbox" name="owner_confirm" value="1"><span>I confirm that I am authorised to share business details, set up and manage B2L Payments.</span></div>
          <input type="hidden" name="dd_action" value="zoho_owner_confirm"><input type="hidden" name="provider_code" value="zoho_payments">
        </div>
        <div class="modal-foot"><button class="deposit-btn" type="submit">Proceed</button><a class="deposit-btn muted" href="direct_deposits.php">Close</a></div>
      </form>
    </div>
  </div>
</body>
</html>
