<?php
/* =============================================================================
 * File   : /brocrm/mobile/broker_onboarding_new.php
 * Goal   : Broker Onboarding (same mobile theme as dst.php pages)
 * Stack  : Core PHP + MySQLi (NO PDO). DB from config.php
 * DB     : utf8mb4 / COLLATE=utf8mb4_general_ci
 * Notes  : - Inserts the logged-in user's numeric id into brokers.user_id
 *            (robust mapping: session -> superadmin.users by empid/email)
 *          - Shows exact MySQL error when a prepare/execute fails
 *          - Uses the same session pattern as dst.php/footer_mobile.php
 * ============================================================================= */

if (session_status() === PHP_SESSION_NONE) { session_start(); }
date_default_timezone_set('Asia/Kolkata');

/* ------------------------- Centralized config (like dst.php) ------------------------- */
$cfgs = [
  __DIR__ . '/config.php',
  __DIR__ . '/../config.php',
  __DIR__ . '/../../config.php'
];
$cfgFound = false;
foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; $cfgFound = true; break; } }
if (!$cfgFound) { http_response_code(500); exit('config.php not found'); }

/* --------------------------------- DB + charset ------------------------------------- */
if (!isset($conn) || !($conn instanceof mysqli)) { http_response_code(500); exit("DB connection (\$conn) missing."); }
@mysqli_set_charset($conn, 'utf8mb4');
@mysqli_query($conn, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_query($conn, "SET collation_connection='utf8mb4_general_ci'");

/* --------------------------------- Helpers ------------------------------------------ */
if (!function_exists('h')){ function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
if (!function_exists('post')){ function post($k,$d=''){ return isset($_POST[$k])?trim((string)$_POST[$k]):$d; } }
if (!function_exists('upper')){ function upper($s){ return strtoupper(trim((string)$s)); } }
if (!function_exists('col_exists')){
  function col_exists(mysqli $db, $t, $c){
    $t = mysqli_real_escape_string($db,$t); $c = mysqli_real_escape_string($db,$c);
    $rs = @mysqli_query($db, "SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
    $ok = $rs && mysqli_num_rows($rs)>0; if ($rs) @mysqli_free_result($rs); return $ok;
  }
}
if (!function_exists('table_exists')){
  function table_exists(mysqli $db, $t){
    $t = mysqli_real_escape_string($db,$t);
    $rs = @mysqli_query($db, "SHOW TABLES LIKE '{$t}'");
    $ok = $rs && mysqli_num_rows($rs)>0; if ($rs) @mysqli_free_result($rs); return $ok;
  }
}
if (!function_exists('asset')){ function asset($p){ return '/brocrm/mobile/'.ltrim($p,'/'); } }
if (!function_exists('q_one')){
  function q_one(mysqli $db, $sql){
    $r=null; if($res=@mysqli_query($db,$sql)){ $r=mysqli_fetch_assoc($res); mysqli_free_result($res); } return $r;
  }
}

/* --------------------------- Current user/session (EXACT pattern) -------------------- */
$ME        = $_SESSION['auth'] ?? [];
$ROLE_ID   = isset($ME['role_id']) ? (int)$ME['role_id'] : 0;
$ROLE_NAME = strtolower($ME['role_name'] ?? 'user');
$ME_ID     = (int)($ME['id'] ?? 0);
$ME_MAIL   = trim((string)($ME['email'] ?? ''));
$ME_EMPID  = trim((string)($ME['empid'] ?? ''));

/* -------- Map a reliable numeric user_id for save (avoid 0 when possible) ---------- */
$USER_ID_FOR_SAVE = $ME_ID;
if ($USER_ID_FOR_SAVE <= 0) {
  $cond = '';
  if ($ME_EMPID !== '')      { $cond = "empid='".mysqli_real_escape_string($conn,$ME_EMPID)."'"; }
  elseif ($ME_MAIL !== '')   { $cond = "email='".mysqli_real_escape_string($conn,$ME_MAIL)."'"; }
  if ($cond !== '') {
    $u = q_one($conn, "SELECT id FROM broriserin_superadmin.users WHERE {$cond} LIMIT 1");
    if ($u && !empty($u['id'])) { $USER_ID_FOR_SAVE = (int)$u['id']; }
  }
}
/* If still 0, leave as 0 (table allows it) — but mapping above should fill it for brokers and most employees */

/* --------------------------------- CSRF --------------------------------------------- */
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$csrf = $_SESSION['csrf_token'];

/* --------------------------- Prefill / last application ------------------------------ */
$first_name = post('first_name','');
$last_name  = post('last_name','');
$email      = post('email','');
$phone      = post('phone','');

$last_app = null;
if ($email !== '') {
  if ($st = mysqli_prepare($conn, "SELECT * FROM brokers WHERE email=? ORDER BY id DESC LIMIT 1")) {
    mysqli_stmt_bind_param($st, "s", $email);
    mysqli_stmt_execute($st);
    $res = mysqli_stmt_get_result($st);
    if ($res && mysqli_num_rows($res)>0) { $last_app = mysqli_fetch_assoc($res); }
    mysqli_stmt_close($st);
  }
}
$already_pending = ($last_app && strtolower((string)$last_app['status']) === 'pending');

/* ----------------------- Ensure table/column availability ---------------------------- */
if (!table_exists($conn,'brokers')) {
  @mysqli_query($conn, "CREATE TABLE IF NOT EXISTS `brokers`(
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_id` INT NULL,
    `broker_code` VARCHAR(50) NOT NULL,
    `first_name` VARCHAR(100) NOT NULL,
    `last_name` VARCHAR(100) NULL,
    `email` VARCHAR(180) NOT NULL,
    `phone` VARCHAR(30) NOT NULL,
    `alt_phone` VARCHAR(30) NULL,
    `whatsapp` VARCHAR(30) NULL,
    `dob` DATE NULL,
    `firm_name` VARCHAR(200) NOT NULL,
    `business_type` VARCHAR(50) NOT NULL,
    `rera_id` VARCHAR(100) NOT NULL,
    `license_valid_till` DATE NULL,
    `gstin` VARCHAR(20) NULL,
    `pan` VARCHAR(20) NULL,
    `addr_line` VARCHAR(255) NOT NULL,
    `city` VARCHAR(120) NOT NULL,
    `state` VARCHAR(120) NOT NULL,
    `pincode` VARCHAR(20) NOT NULL,
    `bank_account_name` VARCHAR(200) NULL,
    `bank_account_number` VARCHAR(64) NULL,
    `bank_ifsc` VARCHAR(20) NULL,
    `bank_name` VARCHAR(200) NULL,
    `bank_branch` VARCHAR(200) NULL,
    `doc_rera_cert` VARCHAR(255) NULL,
    `doc_pan_card` VARCHAR(255) NULL,
    `doc_gst_cert` VARCHAR(255) NULL,
    `doc_cancelled_cheque` VARCHAR(255) NULL,
    `doc_address_proof` VARCHAR(255) NULL,
    `referral_source` VARCHAR(100) NULL,
    `notes` TEXT NULL,
    `status` VARCHAR(30) NOT NULL DEFAULT 'Pending',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_email` (`email`)
  ) ENGINE=InnoDB COLLATE=utf8mb4_general_ci");
}
if (!col_exists($conn,'brokers','user_id')) {
  @mysqli_query($conn, "ALTER TABLE `brokers` ADD COLUMN `user_id` INT NULL AFTER `id`");
}

/* --------------------------------- Submit ------------------------------------------- */
$error=''; $success='';
if ($_SERVER['REQUEST_METHOD']==='POST' && post('action')==='final_submit' && !$already_pending) {
  if (!hash_equals($csrf, post('csrf_token',''))) {
    $error = 'Invalid session. Please reload the page.';
  } else {
    $first_name = post('first_name','');   $last_name  = post('last_name','');
    $email      = post('email','');        $phone      = post('phone','');
    $alt_phone  = post('alt_phone','');    $whatsapp   = post('whatsapp','');
    $dob        = post('dob','');
    $firm_name  = post('firm_name','');    $business_type = post('business_type','');
    $rera_id    = post('rera_id','');      $license_valid_till = post('license_valid_till','');
    $gstin      = upper(post('gstin','')); $pan        = upper(post('pan',''));
    $addr_line  = post('addr_line','');    $city       = post('city','');
    $state      = post('state','');        $pincode    = post('pincode','');
    $bank_account_name = post('bank_account_name','');
    $bank_account_number = post('bank_account_number','');
    $bank_ifsc  = upper(post('bank_ifsc',''));
    $bank_name  = post('bank_name','');    $bank_branch = post('bank_branch','');
    $referral_source = post('referral_source','');   $notes = post('notes','');
    $agreement_accept = post('agreement_accept','');

    /* Validations */
    if($first_name==='') $error='First Name is required.';
    if(!$error && !filter_var($email,FILTER_VALIDATE_EMAIL))              $error='Valid Email is required.';
    if(!$error && !preg_match('/^\d{10}$/',$phone))                       $error='Phone must be 10 digits.';
    if(!$error && $firm_name==='')                                        $error='Firm/Company Name is required.';
    if(!$error && $business_type==='')                                    $error='Business Type is required.';
    if(!$error && $rera_id==='')                                          $error='RERA ID is required.';
    if(!$error && $agreement_accept==='')                                 $error='You must accept the onboarding terms.';
    if(!$error && $addr_line==='')                                        $error='Address Line is required.';
    if(!$error && $city==='')                                             $error='City is required.';
    if(!$error && $state==='')                                            $error='State is required.';
    if(!$error && $pincode==='')                                          $error='Pincode is required.';
    if(!$error && $gstin!=='' && !preg_match('/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][1-9A-Z]Z[0-9A-Z]$/',$gstin)) $error='Invalid GSTIN format.';
    if(!$error && $pan!==''  && !preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]$/',$pan))                            $error='Invalid PAN format.';

    /* Uploads */
    $saved = [
      'doc_rera_cert'=>null,'doc_pan_card'=>null,'doc_gst_cert'=>null,
      'doc_cancelled_cheque'=>null,'doc_address_proof'=>null
    ];
    if(!$error){
      $root = dirname(__DIR__).'/uploads/broker_docs'; if(!is_dir($root)) @mkdir($root,0775,true);
      $folder_rel = 'uploads/broker_docs/'.date('Ymd_His').'_'.bin2hex(random_bytes(3));
      $folder_abs = dirname(__DIR__).'/'.$folder_rel; if(!is_dir($folder_abs)) @mkdir($folder_abs,0775,true);
      $allowed = ['jpg','jpeg','png','webp','gif','pdf'];
      foreach($saved as $field=>$_){
        $name=$_FILES[$field]['name'] ?? ''; $tmp=$_FILES[$field]['tmp_name'] ?? '';
        if($name===''||$tmp==='') continue;
        $ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));
        if(!in_array($ext,$allowed,true)){ $error='Invalid file type for '.$field; break; }
        $safe=preg_replace('/[^a-zA-Z0-9_\-.]/','_',basename($name));
        $dest=$folder_abs.'/'.$field.'__'.$safe;
        if(!move_uploaded_file($tmp,$dest)){ $error='Failed to upload '.$field; break; }
        $saved[$field]=$folder_rel.'/'.basename($dest);
      }
    }

    /* Insert with a CORRECT placeholder count (31) */
    if(!$error){
      $broker_code='BR-'.date('Ymd').'-'.substr(bin2hex(random_bytes(3)),0,6);

      $sql="INSERT INTO brokers(
              user_id,
              broker_code,
              first_name,last_name,email,phone,alt_phone,whatsapp,dob,
              firm_name,business_type,rera_id,license_valid_till,gstin,pan,
              addr_line,city,state,pincode,
              bank_account_name,bank_account_number,bank_ifsc,bank_name,bank_branch,
              doc_rera_cert,doc_pan_card,doc_gst_cert,doc_cancelled_cheque,doc_address_proof,
              referral_source,notes,status,created_at
            ) VALUES (
              ?,                                   /* user_id */
              ?,                                   /* broker_code */
              ?,?,?,?,?,?,NULLIF(?, ''),           /* 1st pack: 7 values (dob nullable) */
              ?,?,?,NULLIF(?, ''),?,?,             /* 2nd pack: 6 values (license nullable) */
              ?,?,?,?,                             /* 3rd pack: 4 values (address) */
              ?,?,?,?,?,                           /* 4th pack: 5 values (bank) */
              ?,?,?,?,?,                           /* 5th pack: 5 values (docs) */
              ?,?,                                 /* 6th pack: 2 values (other) */
              'Pending',NOW()
            )";

      $st = mysqli_prepare($conn, $sql);
      if(!$st){
        $error = 'Failed to prepare database statement: '.h(mysqli_error($conn));
      }else{
        $dr=$saved['doc_rera_cert']; $dp=$saved['doc_pan_card']; $dg=$saved['doc_gst_cert'];
        $dc=$saved['doc_cancelled_cheque']; $da=$saved['doc_address_proof'];

        $params = [
          (int)$USER_ID_FOR_SAVE,                 // user_id (mapped)
          $broker_code,                           // broker_code
          $first_name,$last_name,$email,$phone,$alt_phone,$whatsapp,$dob,
          $firm_name,$business_type,$rera_id,$license_valid_till,$gstin,$pan,
          $addr_line,$city,$state,$pincode,
          $bank_account_name,$bank_account_number,$bank_ifsc,$bank_name,$bank_branch,
          $dr,$dp,$dg,$dc,$da,
          $referral_source,$notes
        ];

        $types = '';
        foreach ($params as $p) { $types .= (is_int($p) ? 'i' : 's'); }
        $bind = []; $bind[] = &$types; foreach ($params as $k=>$v){ $bind[] = &$params[$k]; }
        call_user_func_array([$st,'bind_param'], $bind);

        if(!mysqli_stmt_execute($st)){
          $error = 'Database error while saving application: '.h(mysqli_stmt_error($st));
        }else{
          $last_app = [
            'broker_code'=>$broker_code,
            'first_name'=>$first_name,'last_name'=>$last_name,
            'email'=>$email,'phone'=>$phone,'firm_name'=>$firm_name,'status'=>'Pending'
          ];
          $already_pending = true;

          $ok1 = send_submission_mail_to_applicant($email,$first_name,$firm_name,$broker_code);
          $ok2 = send_admin_notification($first_name,$last_name,$email,$phone,$broker_code);
          $success = 'Your application has been submitted successfully.'
                    .($ok1?' Confirmation email sent.':'')
                    .($ok2?' Admin notified.':'');
        }
        mysqli_stmt_close($st);
      }
    }
  }
}

/* --------------------- SendGrid: applicant + admin ------------------------- */
function send_submission_mail_to_applicant($toEmail,$toName,$firm,$broker_code){
  $apiKey    = defined('SENDGRID_API_KEY')    ? SENDGRID_API_KEY    : '';
  $fromEmail = defined('SENDGRID_FROM_EMAIL') ? SENDGRID_FROM_EMAIL : '';
  $fromName  = defined('SENDGRID_FROM_NAME')  ? SENDGRID_FROM_NAME  : 'BroRiser';
  if($apiKey===''||$fromEmail===''){ return false; }

  $subject = "We received your Broker Onboarding Application (Code: ".$broker_code.")";
  $logo = asset("assets/images/logos/favicon.jpg");
  $html =
    '<div style="font-family:Inter,Segoe UI,Arial,sans-serif;max-width:640px;margin:auto;border:1px solid #eee;border-radius:12px;overflow:hidden">'.
      '<div style="background:#111827;padding:20px 24px;color:#fff;display:flex;gap:12px;align-items:center">'.
        '<img src="'.h($logo).'" alt="BroRiser" style="width:36px;height:36px;border-radius:8px;object-fit:cover" />'.
        '<div style="font-size:18px;font-weight:600">BroRiser Onboarding</div>'.
      '</div>'.
      '<div style="padding:24px">'.
        '<h2 style="margin:0 0 8px 0;color:#111827">Thanks, '.h($toName?:'Partner').'!</h2>'.
        '<p style="color:#374151">We’ve received your broker onboarding application'.($firm?' for <strong>'.h($firm).'</strong>':'').'.</p>'.
        '<ul style="color:#111827"><li><strong>Application Code:</strong> '.h($broker_code).'</li><li><strong>Status:</strong> Pending Review</li></ul>'.
        '<p style="color:#6B7280">We’ll review your details and get back to you shortly.</p>'.
      '</div>'.
    '</div>';

  $payload = [
    "personalizations" => [[ "to" => [[ "email"=>$toEmail, "name"=>$toName?:'' ]], "subject"=>$subject ]],
    "from"     => [ "email"=>$fromEmail, "name"=>$fromName ],
    "reply_to" => [ "email"=>$fromEmail, "name"=>$fromName ],
    "content"  => [[ "type"=>"text/html", "value"=>$html ]]
  ];

  $ch = curl_init("https://api.sendgrid.com/v3/mail/send");
  curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [ "Authorization: Bearer ".$apiKey, "Content-Type: application/json" ],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
    CURLOPT_TIMEOUT        => 30
  ]);
  curl_exec($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  return ($code>=200 && $code<300);
}

function send_admin_notification($first,$last,$email,$phone,$broker_code){
  $apiKey    = defined('SENDGRID_API_KEY')    ? SENDGRID_API_KEY    : '';
  $fromEmail = defined('SENDGRID_FROM_EMAIL') ? SENDGRID_FROM_EMAIL : '';
  $fromName  = defined('SENDGRID_FROM_NAME')  ? SENDGRID_FROM_NAME  : 'BroRiser';
  if($apiKey===''||$fromEmail===''){ return false; }

  $adminEmail = 'info@browser.in'; // change if required
  $applicant  = trim($first.' '.$last);
  $subject    = "New Broker Applicant: {$applicant}, {$email}, {$phone}";
  $html =
    '<div style="font-family:Inter,Segoe UI,Arial,sans-serif;max-width:640px;margin:auto;border:1px solid #eee;border-radius:12px;overflow:hidden">'.
      '<div style="background:#111827;padding:16px 20px;color:#fff"><strong>New Broker Application Submitted</strong></div>'.
      '<div style="padding:18px">'.
        '<p><strong>Applicant:</strong> '.h($applicant).'</p>'.
        '<p><strong>Email:</strong> '.h($email).'</p>'.
        '<p><strong>Phone:</strong> '.h($phone).'</p>'.
        '<p><strong>Application Code:</strong> '.h($broker_code).'</p>'.
        '<p style="color:#6B7280">This is an automated notification.</p>'.
      '</div>'.
    '</div>';

  $payload = [
    "personalizations" => [[ "to" => [[ "email"=>$adminEmail, "name"=>"Admin" ]], "subject"=>$subject ]],
    "from"    => [ "email"=>$fromEmail, "name"=>$fromName ],
    "content" => [[ "type"=>"text/html", "value"=>$html ]]
  ];

  $ch = curl_init("https://api.sendgrid.com/v3/mail/send");
  curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [ "Authorization: Bearer ".$apiKey, "Content-Type: application/json" ],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
    CURLOPT_TIMEOUT        => 30
  ]);
  curl_exec($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  return ($code>=200 && $code<300);
}

/* ------------------------------ THEME / LAYOUT ----------------------------- */
$base_dir   = __DIR__ . '/Base';
$static_url = '/brocrm/mobile/assets';

/* Navbar */
ob_start();
if (file_exists($base_dir.'/navbar.php')) { include $base_dir.'/navbar.php'; }
$navlink_content = ob_get_clean();
$page='nav'; $fpage='foot';

/* Page (hero) */
ob_start();
$PAGE_TITLE = 'Broker Onboarding';
?>
<style>
:root{
  --bg:#fff9f5; --card:#ffffff; --muted:#667084; --text:#0f172a; --line:#e9edf5;
  --btn:#4f7cff; --btn-t:#fff; --accent:#0ea5e9;
}
body.theme-dark{
  --bg:#0d1117; --card:#141a1f; --muted:#aab2c0; --text:#e9eef7; --line:#242c3b;
  --btn:#5b8dff; --btn-t:#0b1220; --accent:#60a5fa;
}
html,body{background:var(--bg); color:var(--text);}
.card{background:var(--card); border:1px solid var(--line); border-radius:16px;}
.small{color:var(--muted)!important}
.btn-big{background:var(--btn); color:var(--btn-t); border:0; height:50px; border-radius:12px; font-weight:800}
.form-select,.form-control{border-radius:12px;}
.page-title .ipt-title{margin-bottom:4px}
.badge-soft{background:rgba(79,124,255,.12); color:#3552b4; border-radius:999px; padding:.28rem .6rem; font-weight:800}
</style>

<div class="page-title">
  <div class="container">
    <div class="row"><div class="col-12">
      <h2 class="ipt-title"><?=h($PAGE_TITLE)?></h2>
      <span class="ipn-subtitle">Apply to partner with us</span>
    </div></div>
  </div>
</div>

<section>
  <div class="container py-3">

    <div class="card mb-3">
      <div class="card-body d-flex justify-content-between align-items-center">
        <div class="small">Fill the details below to submit your application.</div>
        <?php if($ROLE_NAME!=='user' && $ME_MAIL!==''): ?>
        <span class="badge-soft">Logged in as <?=h($ME_MAIL)?></span>
        <?php endif; ?>
      </div>
    </div>

    <?php if($error): ?><div class="alert alert-danger"><?=h($error)?></div><?php endif; ?>
    <?php if($success): ?><div class="alert alert-success"><?=h($success)?></div><?php endif; ?>

    <?php if($already_pending && $last_app): ?>
      <div class="card"><div class="card-body">
        <div class="row g-3">
          <div class="col-12 col-md-6"><div class="small">Application Code</div><div class="fw-extrabold"><?=h($last_app['broker_code'] ?? '')?></div></div>
          <div class="col-6 col-md-3"><div class="small">Email</div><div class="fw-bold"><?=h($last_app['email'])?></div></div>
          <div class="col-6 col-md-3"><div class="small">Phone</div><div class="fw-bold"><?=h($last_app['phone'])?></div></div>
          <div class="col-12 col-md-6"><div class="small">Firm</div><div class="fw-bold"><?=h($last_app['firm_name'] ?? '')?></div></div>
          <div class="col-12 col-md-6"><div class="small">Status</div><div class="fw-bold"><?=h($last_app['status'])?></div></div>
        </div>
        <?php if(!empty($last_app['doc_rera_cert']) || !empty($last_app['doc_pan_card']) || !empty($last_app['doc_gst_cert']) || !empty($last_app['doc_cancelled_cheque']) || !empty($last_app['doc_address_proof'])): ?>
          <hr class="my-3"><h6 class="fw-bold">Uploaded Documents</h6><ul class="mb-0">
          <?php
            $docs = [
              'doc_rera_cert' => 'RERA Certificate',
              'doc_pan_card'  => 'PAN Card',
              'doc_gst_cert'  => 'GST Certificate',
              'doc_cancelled_cheque' => 'Cancelled Cheque',
              'doc_address_proof'    => 'Address Proof'
            ];
            foreach($docs as $k=>$label):
              if(!empty($last_app[$k])): ?><li><a class="text-decoration-none" target="_blank" href="<?=h('/brocrm/mobile/'.ltrim($last_app[$k],'/'))?>"><?=h($label)?></a></li><?php
              endif;
            endforeach; ?>
          </ul>
        <?php endif; ?>
      </div></div>
      <p class="small mt-3">If you need to submit a new request, please contact support.</p>

    <?php else: ?>

    <form method="post" enctype="multipart/form-data" novalidate>
      <input type="hidden" name="csrf_token" value="<?=h($csrf)?>">
      <input type="hidden" name="action" value="final_submit">

      <div class="card"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Contact Details</h5>
        <div class="row g-3">
          <div class="col-md-4"><label class="small">First Name *</label><input name="first_name" class="form-control" value="<?=h($first_name)?>" required></div>
          <div class="col-md-4"><label class="small">Last Name</label><input name="last_name" class="form-control" value="<?=h($last_name)?>"></div>
          <div class="col-md-4"><label class="small">Email *</label><input type="email" name="email" class="form-control" value="<?=h($email)?>" required></div>
          <div class="col-md-4"><label class="small">Phone *</label><input name="phone" class="form-control" value="<?=h($phone)?>" placeholder="10 digits" required></div>
          <div class="col-md-4"><label class="small">Alternate Phone</label><input name="alt_phone" class="form-control" value="<?=h(post('alt_phone',''))?>"></div>
          <div class="col-md-4"><label class="small">WhatsApp</label><input name="whatsapp" class="form-control" value="<?=h(post('whatsapp',''))?>"></div>
          <div class="col-md-4"><label class="small">Date of Birth</label><input type="date" name="dob" class="form-control" value="<?=h(post('dob',''))?>"></div>
        </div>
      </div></div>

      <div class="card mt-3"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Business Details</h5>
        <div class="row g-3">
          <div class="col-md-4"><label class="small">Firm / Company Name *</label><input name="firm_name" class="form-control" value="<?=h(post('firm_name',''))?>" required></div>
          <div class="col-md-4">
            <label class="small">Business Type *</label>
            <?php $bt=post('business_type',''); ?>
            <select name="business_type" class="form-select" required>
              <option value="">Select</option>
              <option <?=($bt==='Individual')?'selected':''?>>Individual</option>
              <option <?=($bt==='Partnership')?'selected':''?>>Partnership</option>
              <option <?=($bt==='LLP')?'selected':''?>>LLP</option>
              <option <?=($bt==='Pvt Ltd')?'selected':''?>>Pvt Ltd</option>
              <option <?=($bt==='Public Ltd')?'selected':''?>>Public Ltd</option>
              <option <?=($bt==='Other')?'selected':''?>>Other</option>
            </select>
          </div>
          <div class="col-md-4"><label class="small">RERA ID *</label><input name="rera_id" class="form-control" value="<?=h(post('rera_id',''))?>" required></div>
          <div class="col-md-4"><label class="small">License Valid Till</label><input type="date" name="license_valid_till" class="form-control" value="<?=h(post('license_valid_till',''))?>"></div>
          <div class="col-md-4"><label class="small">GSTIN</label><input name="gstin" class="form-control" value="<?=h(post('gstin',''))?>" placeholder="22ABCDE1234A1Z5"></div>
          <div class="col-md-4"><label class="small">PAN</label><input name="pan" class="form-control" value="<?=h(post('pan',''))?>" placeholder="ABCDE1234F"></div>
        </div>
      </div></div>

      <div class="card mt-3"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Address</h5>
        <div class="row g-3">
          <div class="col-md-6"><label class="small">Address Line *</label><input name="addr_line" class="form-control" value="<?=h(post('addr_line',''))?>" required></div>
          <div class="col-md-3"><label class="small">City *</label><input name="city" class="form-control" value="<?=h(post('city',''))?>" required></div>
          <div class="col-md-3"><label class="small">State *</label><input name="state" class="form-control" value="<?=h(post('state',''))?>" required></div>
          <div class="col-md-3"><label class="small">Pincode *</label><input name="pincode" class="form-control" value="<?=h(post('pincode',''))?>" required></div>
        </div>
      </div></div>

      <div class="card mt-3"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Bank Details</h5>
        <div class="row g-3">
          <div class="col-md-4"><label class="small">Account Holder Name</label><input name="bank_account_name" class="form-control" value="<?=h(post('bank_account_name',''))?>"></div>
          <div class="col-md-4"><label class="small">Account Number</label><input name="bank_account_number" class="form-control" value="<?=h(post('bank_account_number',''))?>"></div>
          <div class="col-md-4"><label class="small">IFSC</label><input name="bank_ifsc" class="form-control" value="<?=h(post('bank_ifsc',''))?>"></div>
          <div class="col-md-4"><label class="small">Bank Name</label><input name="bank_name" class="form-control" value="<?=h(post('bank_name',''))?>"></div>
          <div class="col-md-4"><label class="small">Branch</label><input name="bank_branch" class="form-control" value="<?=h(post('bank_branch',''))?>"></div>
        </div>
      </div></div>

      <div class="card mt-3"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Upload Documents</h5>
        <div class="row g-3">
          <?php
            $docs=[
              'doc_rera_cert'=>'RERA Certificate',
              'doc_pan_card'=>'PAN Card',
              'doc_gst_cert'=>'GST Certificate',
              'doc_cancelled_cheque'=>'Cancelled Cheque',
              'doc_address_proof'=>'Address Proof'
            ];
            foreach($docs as $name=>$label): ?>
              <div class="col-md-4">
                <label class="small"><?=h($label)?></label>
                <input type="file" name="<?=h($name)?>" class="form-control" accept=".jpg,.jpeg,.png,.webp,.gif,.pdf">
              </div>
          <?php endforeach; ?>
        </div>
      </div></div>

      <div class="card mt-3"><div class="card-body">
        <h5 class="fw-extrabold mb-2">Other</h5>
        <div class="mb-3">
          <?php $rs=post('referral_source',''); ?>
          <label class="small">Referral Source</label>
          <select name="referral_source" class="form-select">
            <option value="">Select</option>
            <option <?=($rs==='Website')?'selected':''?>>Website</option>
            <option <?=($rs==='Walk-in')?'selected':''?>>Walk-in</option>
            <option <?=($rs==='Referral')?'selected':''?>>Referral</option>
            <option <?=($rs==='Campaign')?'selected':''?>>Campaign</option>
            <option <?=($rs==='Other')?'selected':''?>>Other</option>
          </select>
        </div>
        <div class="mb-3"><label class="small">Notes</label><textarea name="notes" rows="4" class="form-control"><?=h(post('notes',''))?></textarea></div>
        <div class="form-check mb-3">
          <input type="checkbox" class="form-check-input" id="agreement_accept" name="agreement_accept" value="1" <?=post('agreement_accept')?'checked':''?> required>
          <label class="form-check-label" for="agreement_accept">I accept the onboarding terms</label>
        </div>
        <button class="btn-big w-100" type="submit">Submit Application</button>
        <div class="small mt-2">You will receive a confirmation email after submission.</div>
      </div></div>

    </form>
    <?php endif; ?>

  </div>
</section>

<script src="<?=h($static_url.'/js/jquery.js')?>"></script>
<script src="<?=h($static_url.'/vendor/bootstrap/js/bootstrap.bundle.min.js')?>"></script>
<script src="<?=h($static_url.'/js/custom.js')?>"></script>
<?php
$hero_content = ob_get_clean();

/* ------------------------------ Render via base ----------------------------- */
if (file_exists($base_dir.'/style/base.php')) {
  include $base_dir.'/style/base.php';
} else {
  // Fallback render if Base template not present
  ?><!doctype html><html lang="en"><head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?=h($PAGE_TITLE)?></title>
    <link rel="stylesheet" href="<?=h($static_url.'/css/style.css')?>">
  </head><body><?= $hero_content ?></body></html><?php
}
