<?php
/* =============================================================================
 * File   : edit-profile.php
 * Goal   : Edit/Create profile safely across mismatched users schemas
 * Stack  : Core PHP + MySQLi (NO PDO) | Collation utf8mb4_general_ci
 * Fixes  : - Detects available columns and builds INSERT/UPDATE accordingly
 *          - Works even if no DB row yet (INSERT mode)
 *          - FIX: remove by-reference warnings when calling bind_param
 * ============================================================================= */

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

/* ---------- Config ---------- */
$cfg_main = __DIR__ . '/config.php';
$cfg_fall = __DIR__ . '/reports-config.php';
if (file_exists($cfg_main)) { require_once $cfg_main; }
elseif (file_exists($cfg_fall)) { require_once $cfg_fall; }
else { http_response_code(500); echo "config.php not found"; exit; }

/* ---------- DB ---------- */
$DB = null;
if (isset($conn) && $conn instanceof mysqli)                    { $DB = $conn; }
elseif (isset($conn_crm) && $conn_crm instanceof mysqli)         { $DB = $conn_crm; }
elseif (isset($conn_crmplus) && $conn_crmplus instanceof mysqli) { $DB = $conn_crmplus; }
elseif (isset($conn_sa) && $conn_sa instanceof mysqli)           { $DB = $conn_sa; }
if (!($DB instanceof mysqli)) { http_response_code(500); echo "No mysqli connection"; exit; }
@mysqli_set_charset($DB,'utf8mb4');
@mysqli_query($DB,"SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_query($DB,"SET collation_connection='utf8mb4_general_ci'");

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

/* ---------- Who am I (like dst.php) ---------- */
$ME       = $_SESSION['auth'] ?? [];
$ME_ID    = (int)($ME['id'] ?? 0);
$ME_MAIL  = trim((string)($ME['email'] ?? ''));
$ME_EMPID = trim((string)($ME['empid'] ?? ''));
$ROLE_ID  = (int)($ME['role_id'] ?? 0);

if ($ME_ID<=0 && $ME_MAIL==='' && $ME_EMPID==='') {
  $base = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https://' : 'http://').($_SERVER['HTTP_HOST'] ?? 'localhost');
  header("Location: {$base}/mobile/welcome/login/"); exit;
}

/* ---------- Find row & target table ---------- */
$conds=[]; if($ME_ID)$conds[]="id=".$ME_ID; if($ME_MAIL!=='')$conds[]="email='".mysqli_real_escape_string($DB,$ME_MAIL)."'"; if($ME_EMPID!=='')$conds[]="empid='".mysqli_real_escape_string($DB,$ME_EMPID)."'";
$WHERE = $conds ? 'WHERE '.implode(' OR ',$conds) : 'WHERE 1=0';
$USER  = row($DB,"SELECT * FROM broriserin_superadmin.users {$WHERE} LIMIT 1");
$TBL   = 'broriserin_superadmin.users';
if(!$USER && table_exists($DB,'users')) { $USER=row($DB,"SELECT * FROM users {$WHERE} LIMIT 1"); $TBL='users'; }

$INSERT_MODE=false;
if(!$USER){
  $INSERT_MODE=true;
  $USER = [
    'id'=>$ME_ID,'first_name'=>trim((string)($ME['first_name']??'')),'last_name'=>trim((string)($ME['last_name']??'')),
    'email'=>$ME_MAIL,'phone'=>trim((string)($ME['phone']??'')),'empid'=>$ME_EMPID,'about'=>'','avatar_url'=>'assets/images/stories/pic1.png'
  ];
  if (table_exists($DB,'users')) $TBL='users';
}

/* ---------- Which columns exist in target ---------- */
list($dbName,$tableOnly) = strpos($TBL,'.')!==false ? explode('.',$TBL,2) : [null,$TBL];
$cols = [
  'first_name' => col_exists($DB,$tableOnly,'first_name'),
  'last_name'  => col_exists($DB,$tableOnly,'last_name'),
  'email'      => col_exists($DB,$tableOnly,'email'),
  'phone'      => col_exists($DB,$tableOnly,'phone'),
  'empid'      => col_exists($DB,$tableOnly,'empid'),
  'about'      => col_exists($DB,$tableOnly,'about'),
  'avatar_url' => col_exists($DB,$tableOnly,'avatar_url'),
  'password'   => col_exists($DB,$tableOnly,'password'),
  'status'     => col_exists($DB,$tableOnly,'status'),
  'role_id'    => col_exists($DB,$tableOnly,'role_id'),
  'created_at' => col_exists($DB,$tableOnly,'created_at'),
  'updated_at' => col_exists($DB,$tableOnly,'updated_at'),
];

/* ---------- POST: build query dynamically (no by-ref warnings) ---------- */
$success=''; $error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
  $first_name=post('first_name'); $last_name=post('last_name'); $email=post('email');
  $phone=post('phone'); $empid=post('empid'); $about=post('about'); $avatar_url=post('avatar_url');
  $new_pass=post('new_password'); $confirm=post('confirm_password');

  if(($cols['first_name'] && $first_name==='') || ($cols['email'] && $email==='')) {
    $error='First name and Email are required.';
  } elseif($new_pass!=='' && $new_pass!==$confirm) {
    $error='Passwords do not match.';
  } else {
    $tbl = $TBL; // already qualified if needed

    // uniqueness check (only if email column exists and row exists)
    $existingId = (int)($USER['id'] ?? 0);
    if(!$INSERT_MODE && $cols['email'] && $existingId>0){
      $stmtC=$DB->prepare("SELECT `id` FROM {$tbl} WHERE `email`=? AND `id`<>? LIMIT 1");
      if($stmtC){
        $stmtC->bind_param('si',$email,$existingId);
        $stmtC->execute(); $stmtC->store_result();
        if($stmtC->num_rows>0){ $error='This email is already in use.'; }
        $stmtC->close();
      }
    }

    if($error===''){
      if($INSERT_MODE){
        // ---- INSERT ----
        $insCols = []; $place = []; $bindVals = []; $types = '';

        $push = function($name,$val) use (&$insCols,&$place,&$bindVals,&$types,$cols){
          if(!empty($cols[$name])){ $insCols[]="`{$name}`"; $place[]='?'; $types.='s'; $bindVals[]=$val; }
        };
        $push('first_name',$first_name);
        $push('last_name',$last_name);
        $push('email',$email);
        $push('phone',$phone);
        $push('empid',$empid);
        $push('about',$about);
        $push('avatar_url',$avatar_url);
        if($new_pass!=='' && $cols['password']){ $push('password', password_hash($new_pass,PASSWORD_BCRYPT)); }
        if($cols['status'])  { $push('status','Active'); }
        if($cols['role_id']) { $push('role_id',(string)$ROLE_ID); }
        if($cols['created_at']) { $insCols[]='`created_at`'; $place[]='NOW()'; }
        if($cols['updated_at']) { $insCols[]='`updated_at`'; $place[]='NOW()'; }

        $sql = "INSERT INTO {$tbl} (".implode(',',$insCols).") VALUES (".implode(',',$place).")";
        if (strpos($sql,'?')!==false) {
          $stmt = $DB->prepare($sql);
          if($stmt){
            // Build reference array for bind_param without array_map (prevents warnings)
            $params = array_merge([$types], $bindVals);
            $refs = [];
            foreach ($params as $k => $v) { $refs[$k] = &$params[$k]; }
            call_user_func_array([$stmt,'bind_param'], $refs);
            $ok = $stmt->execute();
            $stmt->close();
            $success = $ok ? 'Profile created.' : ('Insert failed: '.$DB->error);
          } else { $error='Prepare failed: '.$DB->error; }
        } else {
          $ok = @mysqli_query($DB,$sql);
          $success = $ok ? 'Profile created.' : ('Insert failed: '.$DB->error);
        }

      } else {
        // ---- UPDATE ----
        $setParts = []; $bindVals = []; $types='';

        $add = function($name,$val) use (&$setParts,&$bindVals,&$types,$cols){
          if(!empty($cols[$name])){ $setParts[]="`{$name}`=?"; $bindVals[]=$val; $types.='s'; }
        };

        $add('first_name',$first_name);
        $add('last_name',$last_name);
        $add('email',$email);
        $add('phone',$phone);
        $add('empid',$empid);
        $add('about',$about);
        $add('avatar_url',$avatar_url);
        if($new_pass!=='' && $cols['password']){ $setParts[]='`password`=?'; $bindVals[] = password_hash($new_pass,PASSWORD_BCRYPT); $types.='s'; }
        if($cols['updated_at']){ $setParts[]='`updated_at`=NOW()'; }

        $sql = "UPDATE {$tbl} SET ".implode(',', $setParts)." WHERE `id`=?";
        $types .= 'i';
        $bindVals[] = (int)$USER['id'];

        $stmt = $DB->prepare($sql);
        if($stmt){
          $params = array_merge([$types], $bindVals);
          $refs = [];
          foreach ($params as $k => $v) { $refs[$k] = &$params[$k]; }
          call_user_func_array([$stmt,'bind_param'], $refs);
          $ok = $stmt->execute();
          $stmt->close();
          $success = $ok ? 'Profile updated.' : ('Update failed: '.$DB->error);
        } else { $error='Prepare failed: '.$DB->error; }
      }

      // Refresh and session sync
      if($success!==''){
        $selector = $INSERT_MODE && $cols['email'] ? "`email`='".mysqli_real_escape_string($DB,$email)."'" : "`id`=".(int)$USER['id'];
        $USER = row($DB,"SELECT * FROM {$tbl} WHERE {$selector} ORDER BY id DESC LIMIT 1");
        if($USER){
          if(isset($USER['email'])) $_SESSION['auth']['email']=$USER['email'];
          if(isset($USER['empid'])) $_SESSION['auth']['empid']=$USER['empid'];
          if(isset($USER['first_name'])) $_SESSION['auth']['first_name']=$USER['first_name'];
          if(isset($USER['last_name']))  $_SESSION['auth']['last_name']=$USER['last_name'];
        }
        $INSERT_MODE=false;
      }
    }
  }
}

/* ---------- Paths & includes ---------- */
$BASE = (defined('BASE_URL') && BASE_URL) ? rtrim(BASE_URL,'/').'/' :
        ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https://' : 'http://')
        . ($_SERVER['HTTP_HOST'] ?? 'localhost') . rtrim(dirname($_SERVER['SCRIPT_NAME']),'/\\').'/';
$ASSET = $BASE.'mobile/';

$HEADER  = __DIR__ . 'header_mobile.php';
$SIDEBAR = __DIR__ . '/sidebar_mobile.php';
$FOOTER  = __DIR__ . '/footer_mobile.php';

if (is_file($HEADER)) { require_once $HEADER; } else {
  ?><!doctype html><html lang="en"><head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="<?php echo h($ASSET.'assets/css/style.css'); ?>" rel="stylesheet">
  <title><?php echo $INSERT_MODE?'Create Profile':'Edit Profile'; ?></title></head>
  <body class="bg-gradient-2"><div class="page-wraper header-fixed"><?php
}
if (is_file($SIDEBAR)) { require_once $SIDEBAR; }
?>
<div class="page-content">
  <div class="container">
    <div class="card" style="border-radius:14px;">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><?php echo $INSERT_MODE ? 'Create Profile' : 'Edit Profile'; ?></h6>
        <a class="btn btn-sm btn-outline-primary" href="profile_mobile.php">Back to Profile</a>
      </div>
      <div class="card-body">
        <?php if($error!==''): ?><div class="alert alert-danger"><?php echo h($error); ?></div><?php endif; ?>
        <?php if($success!==''): ?><div class="alert alert-success"><?php echo h($success); ?></div><?php endif; ?>

        <form method="post" autocomplete="off" class="row g-3">
          <div class="col-6">
            <label class="form-label">First Name <?php echo $cols['first_name']?'*':''; ?></label>
            <input type="text" name="first_name" class="form-control" value="<?php echo h($USER['first_name'] ?? ''); ?>" <?php echo $cols['first_name']?'required':''; ?>>
          </div>
          <div class="col-6">
            <label class="form-label">Last Name</label>
            <input type="text" name="last_name" class="form-control" value="<?php echo h($USER['last_name'] ?? ''); ?>">
          </div>
          <div class="col-12">
            <label class="form-label">Email <?php echo $cols['email']?'*':''; ?></label>
            <input type="email" name="email" class="form-control" value="<?php echo h($USER['email'] ?? ''); ?>" <?php echo $cols['email']?'required':''; ?>>
          </div>
          <div class="col-6">
            <label class="form-label">Phone</label>
            <input type="text" name="phone" class="form-control" value="<?php echo h($USER['phone'] ?? ''); ?>">
          </div>
          <div class="col-6">
            <label class="form-label">Emp ID</label>
            <input type="text" name="empid" class="form-control" value="<?php echo h($USER['empid'] ?? ''); ?>">
          </div>

          <div class="col-12" id="photo">
            <label class="form-label">Avatar URL</label>
            <input type="text" name="avatar_url" class="form-control" placeholder="assets/images/stories/pic1.png" value="<?php echo h($USER['avatar_url'] ?? ''); ?>">
          </div>

          <div class="col-12" id="about">
            <label class="form-label">About</label>
            <textarea name="about" rows="3" class="form-control"><?php echo h($USER['about'] ?? ''); ?></textarea>
          </div>

          <div class="col-12 mt-2"><div class="alert alert-info py-2 px-3 mb-2">Change password (optional)</div></div>
          <div class="col-6">
            <label class="form-label">New Password</label>
            <input type="password" name="new_password" class="form-control" autocomplete="new-password">
          </div>
          <div class="col-6">
            <label class="form-label">Confirm Password</label>
            <input type="password" name="confirm_password" class="form-control" autocomplete="new-password">
          </div>

          <div class="col-12 mt-3">
            <button type="submit" class="btn btn-primary w-100"><?php echo $INSERT_MODE ? 'Create' : 'Save Changes'; ?></button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const id = location.hash.replace('#','');
  if(!id) return; const el=document.getElementById(id);
  if(!el) return; setTimeout(()=>{ el.scrollIntoView({behavior:'smooth',block:'center'}); const i=el.querySelector('input,textarea'); i&&i.focus(); },120);
})();
</script>
<?php
if (is_file($FOOTER)) { require_once $FOOTER; } else {
  echo '<script src="'.$ASSET.'assets/js/jquery.js"></script><script src="'.$ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script><script src="'.$ASSET.'assets/js/settings.js"></script><script src="'.$ASSET.'assets/js/custom.js"></script></div></body></html>';
}
