<?php
/* =============================================================================
 * File   : crm_add.php  (Simple auth guard, Soziety mobile, LIGHT MODE)
 * Goal   : Add New Enquiry — requires login; if not, redirects to /mobile/welcome/login?return=<this>
 * Uses   : ./config.php (DB links), header_mobile.php, footer_mobile.php
 * Theme  : Uses ASSET_URL or theme_asset() from config.php; falls back to mobile/assets/
 * ============================================================================= */

@session_start();
date_default_timezone_set('Asia/Kolkata');

require_once __DIR__ . '/config.php';

/* ---------- helpers: current URL + absolute redirect ---------- */
function current_url(): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $uri    = $_SERVER['REQUEST_URI'] ?? '/';
    return $scheme . '://' . $host . $uri;
}
function abs_redirect(string $pathOrUrl){
    if (!preg_match('~^https?://~i', $pathOrUrl)) {
        $base = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        if ($pathOrUrl === '' || $pathOrUrl[0] !== '/') $pathOrUrl = '/'.$pathOrUrl;
        $pathOrUrl = $base.'://'.$host.$pathOrUrl;
    }
    header('Location: '.$pathOrUrl, true, 302);
    exit;
}

/* ---------- SIMPLE AUTH GUARD ---------- */
if (empty($_SESSION['auth']['logged_in'])) {
    $loginUrl = '/mobile/welcome/login?return='.rawurlencode(current_url());
    abs_redirect($loginUrl);
}

/* ---------- h() + theme_asset() shims ---------- */
if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}
if (!function_exists('theme_asset')) {
    if (defined('ASSET_URL')) {
        function theme_asset(string $path): string { return ASSET_URL . ltrim($path, '/'); }
    } else {
        function theme_asset(string $path): string { return 'mobile/assets/' . ltrim($path, '/'); }
    }
}

/* ---------- Pick a DB link ---------- */
$DB = null;
if (isset($conn_crm) && $conn_crm instanceof mysqli)            { $DB = $conn_crm; }
elseif (isset($conn_crmplus) && $conn_crmplus instanceof mysqli){ $DB = $conn_crmplus; }
elseif (isset($conn) && $conn instanceof mysqli)                { $DB = $conn; }
if (!($DB instanceof mysqli)) { http_response_code(500); exit('DB connection missing.'); }

@mysqli_set_charset($DB,'utf8mb4');
@mysqli_query($DB,"SET NAMES 'utf8mb4'");
@mysqli_query($DB,"SET collation_connection='utf8mb4_general_ci'");

/* ---------- tiny helpers ---------- */
function fetch_all($db,$sql){ $out=[]; if($res=@mysqli_query($db,$sql)){ while($r=mysqli_fetch_assoc($res)){ $out[]=$r; } @mysqli_free_result($res);} return $out; }
function table_exists($db,$name){ $name = mysqli_real_escape_string($db,$name); $res=@mysqli_query($db,"SHOW TABLES LIKE '{$name}'"); $ok=($res && mysqli_num_rows($res)>0); if($res) @mysqli_free_result($res); return $ok; }
function col_exists($db,$table,$col){ $table = mysqli_real_escape_string($db,$table); $col = mysqli_real_escape_string($db,$col); $res=@mysqli_query($db,"SHOW COLUMNS FROM `{$table}` LIKE '{$col}'"); $ok=($res && mysqli_num_rows($res)>0); if($res) @mysqli_free_result($res); return $ok; }
function refValues($arr){ if (strnatcmp(phpversion(),'5.3')>=0){ $refs=[]; foreach($arr as $k=>$v){ $refs[$k]=&$arr[$k]; } return $refs; } return $arr; }

/* ---------- Locate CRM Table ---------- */
$CRM_TABLE = null;
foreach (['crm_enquiries','crm_leads','crm','leads','enquiries'] as $try){
    if (table_exists($DB,$try)) { $CRM_TABLE = $try; break; }
}

/* ---------- PROJECTS: auto-detect ---------- */
$PDB = $DB;
$PROJECTS_TABLE = null;
foreach (['projects','project','pp_projects','tbl_projects','crm_enquiries'] as $t) {
    if (table_exists($PDB,$t)) { $PROJECTS_TABLE = $t; break; }
}
$PC = ['id'=>null,'name'=>null,'city'=>null,'region'=>null,'locality'=>null];
if ($PROJECTS_TABLE) {
  $PC['id']      = col_exists($PDB,$PROJECTS_TABLE,'id') ? 'id'
                 : (col_exists($PDB,$PROJECTS_TABLE,'project_id') ? 'project_id' : null);
  $PC['name']    = col_exists($PDB,$PROJECTS_TABLE,'title') ? 'title'
                 : (col_exists($PDB,$PROJECTS_TABLE,'name') ? 'name'
                 : (col_exists($PDB,$PROJECTS_TABLE,'project_name') ? 'project_name'
                 : (col_exists($PDB,$PROJECTS_TABLE,'project') ? 'project' : null)));
  $PC['city']    = col_exists($PDB,$PROJECTS_TABLE,'city') ? 'city' : null;
  $PC['region']  = col_exists($PDB,$PROJECTS_TABLE,'region') ? 'region' : null;
  $PC['locality']= col_exists($PDB,$PROJECTS_TABLE,'locality') ? 'locality'
                 : (col_exists($PDB,$PROJECTS_TABLE,'location') ? 'location' : null);
}
$opt_projects = [];
if ($PROJECTS_TABLE && $PC['name']) {
  $cols = [];
  $cols[] = "`{$PC['name']}` AS pname";
  $cols[] = $PC['id'] ? "`{$PC['id']}` AS pid" : "NULL AS pid";
  $cols[] = $PC['city'] ? "`{$PC['city']}` AS city" : "NULL AS city";
  $cols[] = $PC['region'] ? "`{$PC['region']}` AS region" : "NULL AS region";
  $cols[] = $PC['locality'] ? "`{$PC['locality']}` AS locality" : "NULL AS locality";
  $rows = fetch_all($PDB, "SELECT ".implode(',', $cols)." FROM `{$PROJECTS_TABLE}` ORDER BY 1");
  $seen = [];
  foreach ($rows as $r) {
    $name = trim((string)$r['pname']); if ($name==='') continue;
    $val  = ($r['pid']!=='') ? (string)$r['pid'] : $name;
    $key  = strtolower($val).'|'.strtolower($name);
    if (isset($seen[$key])) continue;
    $seen[$key]=1;
    $label = $name;
    $tag = trim(implode(' · ', array_filter([trim((string)$r['locality']), trim((string)$r['city'])])));
    if ($tag!=='') { $label .= ' — '.$tag; }
    $opt_projects[] = ['value'=>$val,'label'=>$label];
  }
}
if (!$opt_projects) $opt_projects = [['value'=>'','label'=>'(Type project in comments)']];

/* ---------- Lead Sources ---------- */
$opt_sources = [];
if (table_exists($DB,'ui_crm')) {
  $ui = fetch_all($DB,"SELECT * FROM ui_crm WHERE is_active=1 ORDER BY section, sort_order, id");
  foreach ($ui as $r) {
    if (strtolower(trim($r['section']))==='lead_source') {
      $label = trim($r['label'] ?? ''); $value = trim($r['value'] ?? '');
      if ($label!=='' || $value!=='') $opt_sources[] = ['value'=>$value!==''?$value:$label, 'label'=>$label!==''?$label:($value!==''?$value:'')];
    }
  }
}
if (!$opt_sources) foreach (['Walk-in','Referral','Broker','Website','WhatsApp','Facebook','Instagram','Google Ads'] as $s) $opt_sources[] = ['value'=>$s,'label'=>$s];

/* ---------- SEO ---------- */
$scheme    = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
$host      = $_SERVER['HTTP_HOST'] ?? 'localhost';
$path      = strtok($_SERVER['REQUEST_URI'] ?? '/mobile/crm_add.php', '?');
$canonical = $scheme . '://' . $host . $path;
$seo_title = 'Add New Enquiry';
$seo_desc  = 'Create a new CRM enquiry from your mobile-friendly screen.';

/* ---------- Submit ---------- */
$errors=[]; $created=false;
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    if (!$CRM_TABLE) { $errors[] = 'CRM table not found in CRM database.'; }
    else {
        $project = trim($_POST['project'] ?? '');
        $name    = trim($_POST['name'] ?? '');
        $phone   = trim($_POST['phone'] ?? '');
        $email   = trim($_POST['email'] ?? '');
        $source  = trim($_POST['source'] ?? '');
        $comment = trim($_POST['comment'] ?? '');
        $accept  = isset($_POST['accept']) ? 1 : 0;

        if ($project==='') $errors[]='Please select a project.';
        if ($name==='')    $errors[]='Please enter client name.';
        if ($phone==='')   $errors[]='Please enter client phone.';
        if (!$accept)      $errors[]='You must accept the Terms and Conditions.';

        $phone = preg_replace('/[^0-9+]/','',$phone);

        $col_project = col_exists($DB,$CRM_TABLE,'project') ? 'project' : (col_exists($DB,$CRM_TABLE,'project_name') ? 'project_name' : null);
        $col_name    = col_exists($DB,$CRM_TABLE,'name') ? 'name' : (col_exists($DB,$CRM_TABLE,'customer_name') ? 'customer_name' : null);
        $col_phone   = col_exists($DB,$CRM_TABLE,'mobile') ? 'mobile' : (col_exists($DB,$CRM_TABLE,'phone') ? 'phone' : null);
        $col_email   = col_exists($DB,$CRM_TABLE,'email') ? 'email' : (col_exists($DB,$CRM_TABLE,'email_address') ? 'email_address' : null);
        $col_source  = col_exists($DB,$CRM_TABLE,'lead_source') ? 'lead_source' : (col_exists($DB,$CRM_TABLE,'source') ? 'source' : null);
        $col_remark  = col_exists($DB,$CRM_TABLE,'remarks') ? 'remarks' : (col_exists($DB,$CRM_TABLE,'note') ? 'note' : (col_exists($DB,$CRM_TABLE,'comment') ? 'comment' : null));
        $col_created = col_exists($DB,$CRM_TABLE,'created_at') ? 'created_at' : (col_exists($DB,$CRM_TABLE,'created_on') ? 'created_on' : null);

        if (!$col_project || !$col_name || !$col_phone) { $errors[]='Required columns missing in the CRM table.'; }

        if (!$errors) {
            $cols=[]; $ph=[]; $vals=[]; $types='';

            $cols[]=$col_project; $ph[]='?'; $vals[]=$project; $types.='s';
            $cols[]=$col_name;    $ph[]='?'; $vals[]=$name;    $types.='s';
            $cols[]=$col_phone;   $ph[]='?'; $vals[]=$phone;   $types.='s';
            if ($col_email)  { $cols[]=$col_email;  $ph[]='?'; $vals[]=$email;   $types.='s'; }
            if ($col_source) { $cols[]=$col_source; $ph[]='?'; $vals[]=$source;  $types.='s'; }
            if ($col_remark) { $cols[]=$col_remark; $ph[]='?'; $vals[]=$comment; $types.='s'; }
            if ($col_created){ $cols[]=$col_created; $ph[]='?'; $vals[]=date('Y-m-d H:i:s'); $types.='s'; }

            $sql = "INSERT INTO `{$CRM_TABLE}` (`".implode('`,`',$cols)."`) VALUES (".implode(',',$ph).")";
            if ($stmt = mysqli_prepare($DB,$sql)) {
                $bind = array_merge([$stmt, $types], array_map(function(&$v){ return $v; }, $vals));
                @call_user_func_array('mysqli_stmt_bind_param', refValues($bind));
                if (@mysqli_stmt_execute($stmt)) { $created=true; } else { $errors[]='Database error while saving.'; }
                @mysqli_stmt_close($stmt);
            } else {
                $errors[]='Failed to prepare insert statement.';
            }
        }
    }
    if ($created) { header('Location: crm_mobile.php?created=1'); exit; }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title><?php echo h($seo_title); ?></title>
<meta name="description" content="<?php echo h($seo_desc); ?>">
<link rel="canonical" href="<?php echo h($canonical); ?>">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="<?php echo h(theme_asset('css/style.css')); ?>">
<style>
:root{ --bg:#fff; --text:#0d0f14; --muted:#6b7280; --line:#e5e7eb; --card:#fff; --card2:#fafafa; --primary:#5f35f5; }
html,body{background:#fff;color:#0d0f14}
.page-wrap{max-width:680px;margin:0 auto;padding:12px 12px 80px}
.card{background:var(--card);border-radius:16px;box-shadow:0 8px 20px rgba(0,0,0,.06);padding:14px;margin:12px 0;border:1px solid var(--line)}
.label{font-size:13px;color:var(--muted);margin-bottom:6px}
.inp, select, textarea{width:100%;background:var(--card2);border:1px solid var(--line);border-radius:12px;color:var(--text);padding:12px 12px;font-size:15px;outline:none}
select{appearance:none;background-image:linear-gradient(45deg,transparent 50%,var(--text) 50%),linear-gradient(135deg,var(--text) 50%,transparent 50%);background-position:calc(100% - 24px) calc(50% - 3px), calc(100% - 16px) calc(50% - 3px);background-size:8px 8px, 8px 8px;background-repeat:no-repeat}
textarea{min-height:110px;resize:vertical}
.topbar{display:flex;align-items:center;justify-content:space-between;height:56px;padding:0 12px;border-bottom:1px solid var(--line);background:#fff;position:sticky;top:0;z-index:50}
.topbtn{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;border:1px solid var(--line);background:var(--card2)}
.topbtn svg{width:20px;height:20px;stroke:var(--text)}
.topttl{font-weight:800;font-size:16px}
.terms{display:flex;align-items:center;gap:10px;margin:10px 0}
.terms input{appearance:none;width:20px;height:20px;border:2px solid #d1d5db;border-radius:6px;background:#fff;position:relative;outline:0;min-width:20px}
.terms input:checked{border-color:var(--primary);background:var(--primary)}
.terms input:checked::after{content:'';position:absolute;inset:4px;background:#fff;border-radius:4px}
.terms a{color:var(--primary);text-decoration:underline}
.btn-primary{width:100%;height:52px;border-radius:14px;background:var(--primary);border:1px solid var(--primary);color:#fff;font-weight:800;font-size:16px;box-shadow:0 12px 30px rgba(95,53,245,.35)}
.toast{margin:12px;background:#fef2f2;color:#991b1b;border:1px solid #fecaca;padding:12px;border-radius:12px}
@media (min-width:992px){ .layout{display:grid;grid-template-columns:280px 1fr;gap:0} .page-wrap{max-width:900px;padding:16px 24px 100px} }
</style>
</head>
<body>

<?php if (file_exists(__DIR__.'header_mobile.php')) include __DIR__.'header_mobile.php'; ?>

<main class="page-wrap" role="main" aria-label="Add New Enquiry">
  <div class="topbar">
    <a class="topbtn" href="crm_mobile.php" aria-label="Back">
      <svg viewBox="0 0 24 24" fill="none" stroke-width="2"><path d="M15 18l-6-6 6-6" stroke="currentColor"/></svg>
    </a>
    <div class="topttl">Add New Enquiry</div>
    <a class="topbtn" href="crm_mobile.php" aria-label="Close">
      <svg viewBox="0 0 24 24" fill="none" stroke-width="2"><path d="M18 6L6 18M6 6l12 12" stroke="currentColor"/></svg>
    </a>
  </div>

  <?php if($errors){ ?>
    <div class="section">
      <div class="toast" role="alert" aria-live="assertive">
        <?php echo '<ul style="margin:0 0 0 18px;padding:0">'; foreach($errors as $e){ echo '<li>'.h($e).'</li>'; } echo '</ul>'; ?>
      </div>
    </div>
  <?php } ?>

  <form class="card" method="post" action="" novalidate>
    <div class="field" style="margin-bottom:14px">
      <div class="label">Select a Project</div>
      <select name="project" required>
        <option value="">Project</option>
        <?php foreach($opt_projects as $o){ $val = ($o['value']??'')!=='' ? $o['value'] : ($o['label']??''); ?>
          <option value="<?php echo h($val); ?>" <?php echo (isset($_POST['project']) && $_POST['project']===$val)?'selected':''; ?>>
            <?php echo h($o['label'] ?: $val); ?>
          </option>
        <?php } ?>
      </select>
    </div>

    <div class="field" style="margin-bottom:14px">
      <div class="label">Client Name</div>
      <input class="inp" type="text" name="name" placeholder="Enter Name" value="<?php echo h($_POST['name'] ?? ''); ?>" required>
    </div>

    <div class="field" style="margin-bottom:14px">
      <div class="label">Client Phone</div>
      <input class="inp" type="tel" name="phone" placeholder="Enter Phone" inputmode="tel" value="<?php echo h($_POST['phone'] ?? ''); ?>" required>
    </div>

    <div class="field" style="margin-bottom:14px">
      <div class="label">Email Address</div>
      <input class="inp" type="email" name="email" placeholder="Enter Email Address" value="<?php echo h($_POST['email'] ?? ''); ?>">
    </div>

    <div class="field" style="margin-bottom:14px">
      <div class="label">Source</div>
      <select name="source">
        <option value="">Source</option>
        <?php foreach($opt_sources as $o){ $val = ($o['value']??'')!=='' ? $o['value'] : ($o['label']??''); ?>
          <option value="<?php echo h($val); ?>" <?php echo (isset($_POST['source']) && $_POST['source']===$val)?'selected':''; ?>>
            <?php echo h($o['label'] ?: $val); ?>
          </option>
        <?php } ?>
      </select>
    </div>

    <div class="field" style="margin-bottom:10px">
      <div class="label">Comment</div>
      <textarea name="comment" placeholder="Enter Comments"><?php echo h($_POST['comment'] ?? ''); ?></textarea>
    </div>

    <label class="terms">
      <input type="checkbox" name="accept" value="1" <?php echo isset($_POST['accept'])?'checked':''; ?> required>
      <span>I accept the <a href="terms.php" target="_blank" rel="noopener">Terms and Conditions</a></span>
    </label>

    <div class="submit" style="position:sticky;bottom:0;background:#fff;padding:12px;border-top:1px solid var(--line)">
      <button class="btn-primary" type="submit">Create</button>
    </div>
  </form>
</main>

<?php if (file_exists(__DIR__.'footer_mobile.php')) include __DIR__.'footer_mobile.php'; ?>

<script>
document.querySelector('form').addEventListener('submit', function(e){
  const project = this.querySelector('select[name="project"]');
  const name    = this.querySelector('input[name="name"]');
  const phone   = this.querySelector('input[name="phone"]');
  const accept  = this.querySelector('input[name="accept"]');
  if(!project.value || !name.value.trim() || !phone.value.trim() || !accept.checked){
    e.preventDefault(); alert('Please fill required fields and accept Terms.');
  }
});
</script>
</body>
</html>
