<?php
/* =============================================================================
 * File   : profile_mobile.php
 * Goal   : Fully responsive Mobile Profile with neat Name/Email/Mobile rows
 * Stack  : Core PHP + MySQLi (NO PDO)
 * DB     : config.php (fallback to reports-config.php), utf8mb4_general_ci
 * Notes  : - Session resolution mirrors dst.php (id/email/empid)
 *          - Works even if header_mobile.php/footer_mobile.php are missing
 *          - Tight mobile-first CSS with truncation & wrap fixes
 * ============================================================================= */

@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; }

/* ---------- Pick mysqli ---------- */
$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 in config.php"; exit; }

/* ---------- Charset / Collation ---------- */
@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; }

/* ---------- Session (same as dst.php) ---------- */
$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'] ?? ''));

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;
}

/* ----- Ensure empid present by looking up superadmin.users if needed ----- */
if ($ME_EMPID==='') {
    $cond = $ME_ID ? "id=".(int)$ME_ID : ($ME_MAIL!=='' ? "email='".mysqli_real_escape_string($DB,$ME_MAIL)."'" : "");
    if ($cond) {
        $u = row($DB,"SELECT empid FROM broriserin_superadmin.users WHERE {$cond} LIMIT 1");
        if (!empty($u['empid'])) { $ME_EMPID = trim($u['empid']); $_SESSION['auth']['empid']=$ME_EMPID; }
    }
}

/* ---------- Fetch user (superadmin.users → users → session) ---------- */
$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 id,first_name,last_name,email,phone,empid,role_id,status,created_at,
                        IFNULL(username,'') AS username,
                        IFNULL(about,'') AS about,
                        IFNULL(avatar_url,'') AS avatar_url
                 FROM broriserin_superadmin.users {$WHERE} LIMIT 1");
if(!$USER && table_exists($DB,'users')){
    $USER = row($DB,"SELECT id,first_name,last_name,email,phone,empid,role_id,status,created_at,
                            IFNULL(username,'') AS username,
                            IFNULL(about,'') AS about,
                            IFNULL(avatar_url,'') AS avatar_url
                     FROM users {$WHERE} LIMIT 1");
}
$FROM_SESSION=false;
if(!$USER){
    $FROM_SESSION=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,'role_id'=>$ROLE_ID,'status'=>'Active','created_at'=>'',
      'username'=>($ME_MAIL?strtok($ME_MAIL,'@'):($ME_EMPID?:'user')),'about'=>'','avatar_url'=>'assets/images/stories/pic1.png'
    ];
}

/* ---------- Role text ---------- */
$ROLE_TEXT='User';
$rr=row($DB,"SELECT name FROM broriserin_superadmin.roles WHERE id=".(int)$USER['role_id']." LIMIT 1");
if(!$rr && table_exists($DB,'roles')) $rr=row($DB,"SELECT name FROM roles WHERE id=".(int)$USER['role_id']." LIMIT 1");
if($rr && !empty($rr['name'])) $ROLE_TEXT=(string)$rr['name'];

/* ---------- Derived UI ---------- */
$FULL_NAME = trim(($USER['first_name']??'').' '.($USER['last_name']??'')); if($FULL_NAME==='') $FULL_NAME='User';
$USERNAME  = ($USER['username']!=='') ? $USER['username'] : (($USER['email']!=='') ? strtok($USER['email'],'@') : 'user'.$USER['id']);
$ABOUT     = ($USER['about']!=='') ? $USER['about'] : '—';
$AVATAR    = ($USER['avatar_url']!=='') ? $USER['avatar_url'] : 'assets/images/stories/pic1.png';

/* ---------- 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';

/* ---------- Render ---------- */
if (file_exists($HEADER)) { require $HEADER; } else {
?>
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,viewport-fit=cover">
<link rel="shortcut icon" href="<?php echo h($ASSET.'assets/images/favicon.png'); ?>">
<link href="<?php echo h($ASSET.'assets/css/style.css'); ?>" rel="stylesheet">
<link href="<?php echo h($ASSET.'assets/vendor/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">
<link href="<?php echo h($ASSET.'assets/vendor/fontawesome/css/all.min.css'); ?>" rel="stylesheet">
<title>Profile</title>
</head><body class="theme-light"><div class="page-wraper header-fixed">
<?php } if (file_exists($SIDEBAR)) { require $SIDEBAR; } ?>

<style>
/* ===== Mobile-first responsive fixes ===== */
:root{
  --card-pad:16px;
  --avatar-size:88px;
  --radius-xl:18px;
  --accent:#ff7a59;
  --muted:#6b7280;
  --ink:#0f172a;
}
.page-content{padding:12px 12px 84px 12px;} /* bottom space for menubar */
.container{max-width:720px;margin:0 auto;padding:0;}

/* Card */
.profile-card{
  background:#fff;border-radius:var(--radius-xl);
  padding:var(--card-pad);border:1px solid rgba(0,0,0,.06);
  box-shadow:0 4px 14px rgba(0,0,0,.04);
}

/* Grid: stacks on very small screens, 2-col above 380px */
.profile-grid{
  display:grid;gap:14px;align-items:center;
  grid-template-columns:1fr;
}
@media (min-width:380px){
  .profile-grid{grid-template-columns:1fr auto;}
}

/* Info rows */
.info-list{display:grid;gap:10px;}
.info-row{
  display:grid;grid-template-columns:auto 84px 1fr;gap:10px;align-items:center;
}
@media (max-width:360px){
  .info-row{grid-template-columns:auto 68px 1fr;gap:8px;}
}
.info-ico{
  width:28px;height:28px;border-radius:9px;background:#ffe9e0;
  display:flex;align-items:center;justify-content:center;flex:0 0 28px;
}
.info-ico i{font-size:13px;line-height:1;}
.info-lbl{
  color:var(--muted);font-weight:700;font-size:12px;letter-spacing:.2px;
  text-transform:uppercase;
}
.info-val{
  font-weight:800;color:var(--ink);min-width:0;
  overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
  line-height:1.2;
}

/* Avatar block */
.avatar-wrap{position:relative;justify-self:end}
@media (max-width:379.98px){
  .avatar-wrap{justify-self:start;order:-1;}
}
.avatar{
  width:var(--avatar-size);height:var(--avatar-size);border-radius:16px;
  border:3px solid var(--accent);object-fit:cover;display:block;background:#f6f7f9;
}
.pencil{
  position:absolute;right:-8px;bottom:-8px;background:var(--accent);color:#fff;border:none;
  width:34px;height:34px;border-radius:12px;display:flex;align-items:center;justify-content:center;
  box-shadow:0 10px 20px rgba(255,122,89,.35);text-decoration:none;
}

/* About */
.about-head{display:flex;align-items:center;gap:10px;}
.about-head h6{font-weight:800;margin:0;}
.about-pencil{
  background:var(--accent);color:#fff;border:none;width:28px;height:28px;border-radius:10px;
  display:inline-flex;align-items:center;justify-content:center;box-shadow:0 8px 16px rgba(255,122,89,.25);
  text-decoration:none;
}
.about-text{color:#111827;font-size:14px;line-height:1.55;word-break:break-word;}

/* Stats strip (auto wraps on tiny screens) */
.stats{
  background:linear-gradient(90deg,#6633ff,#a238ff);border-radius:16px;color:#fff;
  display:grid;grid-template-columns:repeat(3,1fr);overflow:hidden;
}
.stats div{padding:12px 6px;text-align:center}
.stats b{display:block;font-size:18px;line-height:1}
.stats span{opacity:.9;font-size:12px}

/* Gallery */
.gallery .col-4{padding:6px;}
.gallery img{width:100%;height:auto;border-radius:10px;display:block;}

/* Safe area for notched devices */
@supports (padding: max(0px)){
  .page-content{padding-bottom:max(84px, env(safe-area-inset-bottom));}
}

/* Dark theme friendly (if body has .theme-dark) */
.theme-dark .profile-card{background:#0f1420;border-color:rgba(255,255,255,.06);}
.theme-dark .info-lbl{color:#9aa4b2;}
.theme-dark .info-val{color:#e6e9ef;}
.theme-dark .about-text{color:#dfe3ea;}
</style>

<script src="<?php echo h($ASSET.'assets/js/jquery.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/vendor/swiper/swiper-bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/vendor/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/dz.carousel.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/settings.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/custom.js'); ?>"></script>

<div class="page-content">
  <div class="container">
    <!-- Top profile card -->
    <div class="profile-card mb-3">
      <div class="profile-grid">
        <div class="info-list">
          <div class="info-row">
            <div class="info-ico" aria-hidden="true"><i class="fa-regular fa-user"></i></div>
            <div class="info-lbl">Name</div>
            <div class="info-val" title="<?php echo h($FULL_NAME); ?>"><?php echo h($FULL_NAME); ?></div>
          </div>
          <div class="info-row">
            <div class="info-ico" aria-hidden="true"><i class="fa-regular fa-envelope"></i></div>
            <div class="info-lbl">Email</div>
            <div class="info-val" title="<?php echo h($USER['email']); ?>"><?php echo h($USER['email']); ?></div>
          </div>
          <div class="info-row">
            <div class="info-ico" aria-hidden="true"><i class="fa-regular fa-phone"></i></div>
            <div class="info-lbl">Mobile</div>
            <div class="info-val" title="<?php echo h($USER['phone'] ?: '—'); ?>"><?php echo h($USER['phone'] ?: '—'); ?></div>
          </div>
        </div>
        <div class="avatar-wrap">
          <img class="avatar" src="<?php echo h($ASSET.$AVATAR); ?>"
               onerror="this.src='<?php echo h($ASSET.'assets/images/stories/pic1.png'); ?>';"
               alt="avatar">
          <a class="pencil" href="edit-profile.php#photo" title="Change photo"><i class="fa-solid fa-pencil"></i></a>
        </div>
      </div>
    </div>

    <!-- About me -->
    <div class="mb-2 about-head">
      <h6 class="mb-0">About me</h6>
      <a class="about-pencil" href="edit-profile.php#about" title="Edit about"><i class="fa-solid fa-pencil"></i></a>
    </div>
    <p class="mb-3 about-text"><?php echo nl2br(h($ABOUT)); ?></p>

    <!-- Stats strip -->
    <div class="stats mb-3">
      <div><b>52</b><span>Post</span></div>
      <div><b>250</b><span>Following</span></div>
      <div><b>4.5k</b><span>Followers</span></div>
    </div>

    <!-- Gallery sample -->
    <div class="row g-0 gallery">
      <?php for($i=1;$i<=9;$i++): ?>
        <div class="col-4"><img src="<?php echo h($ASSET.'assets/images/post/pic'.(($i%12)+1).'.png'); ?>" alt=""></div>
      <?php endfor; ?>
    </div>
  </div>
</div>

<?php
if (file_exists($FOOTER)) {
  require $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>';
}
