<?php
$page_title = 'ملفي الشخصي';
require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/admin_user_profile_lib.php';

require_login();
if (function_exists('ensure_auth_tables') && ($conn instanceof mysqli)) ensure_auth_tables($conn);
if (function_exists('ua_ensure_admin_profile_columns') && ($conn instanceof mysqli)) ua_ensure_admin_profile_columns($conn);

$uid = (int)($_SESSION['admin_id'] ?? ($_SESSION['admin_user_id'] ?? 0));
if ($uid <= 0) { header('Location: index.php?login=1'); exit; }

$msg = '';
$err = '';
$user = ua_admin_fetch_user($conn, $uid);
if (!$user) { die('تعذر العثور على بيانات المستخدم الحالي.'); }

function ua_profile_col(mysqli $conn, string $col): bool {
  return function_exists('col_exists') ? col_exists($conn, 'admin_users', $col) : false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_profile'])) {
  $full_name = trim((string)($_POST['full_name'] ?? ''));
  $email = trim((string)($_POST['email'] ?? ''));
  $phone = trim((string)($_POST['phone'] ?? ''));
  $phone2 = trim((string)($_POST['phone2'] ?? ''));
  $address = trim((string)($_POST['address'] ?? ''));
  $job_title = trim((string)($_POST['job_title'] ?? ''));
  $identity_no = trim((string)($_POST['identity_no'] ?? ''));
  $profile_notes = trim((string)($_POST['profile_notes'] ?? ''));

  if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $err = 'صيغة البريد الإلكتروني غير صحيحة.';
  }

  $avatar_new = '';
  $id_front_new = '';
  $id_back_new = '';
  if (!$err) {
    $avatar_new = ua_admin_upload_image('avatar_image', $uid, 'avatar', $err);
  }
  if (!$err) {
    $id_front_new = ua_admin_upload_image('identity_front_image', $uid, 'identity_front', $err);
  }
  if (!$err) {
    $id_back_new = ua_admin_upload_image('identity_back_image', $uid, 'identity_back', $err);
  }

  if (!$err) {
    $sets = [];
    $add = function(string $col, string $val) use (&$sets, $conn) {
      if (ua_profile_col($conn, $col)) $sets[] = "`$col`='".$conn->real_escape_string($val)."'";
    };
    $add('full_name', $full_name);
    $add('email', $email);
    $add('phone', $phone);
    $add('phone2', $phone2);
    $add('address', $address);
    $add('job_title', $job_title);
    $add('identity_no', $identity_no);
    $add('profile_notes', $profile_notes);
    if ($avatar_new !== '') $add('avatar_path', $avatar_new);
    if ($id_front_new !== '') {
      $add('identity_front_image_path', $id_front_new);
      $add('identity_image_path', $id_front_new); // توافق قديم: الوجه الأمامي هو صورة الهوية الافتراضية
    }
    if ($id_back_new !== '') $add('identity_back_image_path', $id_back_new);
    if (!empty($_POST['remove_avatar']) && ua_profile_col($conn, 'avatar_path')) $sets[] = "avatar_path=NULL";
    if (!empty($_POST['remove_identity_front_image'])) {
      if (ua_profile_col($conn, 'identity_front_image_path')) $sets[] = "identity_front_image_path=NULL";
      if (ua_profile_col($conn, 'identity_image_path')) $sets[] = "identity_image_path=NULL";
    }
    if (!empty($_POST['remove_identity_back_image']) && ua_profile_col($conn, 'identity_back_image_path')) $sets[] = "identity_back_image_path=NULL";
    if (ua_profile_col($conn, 'updated_at')) $sets[] = "updated_at=NOW()";

    if (!empty($sets)) {
      $ok = $conn->query("UPDATE admin_users SET ".implode(',', $sets)." WHERE id=$uid LIMIT 1");
      if (!$ok) $err = 'DB Error: '.$conn->error;
    }
  }

  // تغيير كلمة المرور اختياري، لكنه يتطلب كلمة المرور الحالية.
  $current_password = (string)($_POST['current_password'] ?? '');
  $new_password = (string)($_POST['new_password'] ?? '');
  $new_password2 = (string)($_POST['new_password2'] ?? '');
  if (!$err && trim($new_password) !== '') {
    if ($new_password !== $new_password2) {
      $err = 'كلمة المرور الجديدة غير متطابقة.';
    } elseif (mb_strlen($new_password, 'UTF-8') < 6) {
      $err = 'كلمة المرور الجديدة قصيرة جداً. الحد الأدنى 6 أحرف.';
    } else {
      $stored_hash = (string)($user['password_hash'] ?? '');
      $stored_pass = (string)($user['password'] ?? '');
      $ok_old = false;
      if ($stored_hash !== '') $ok_old = verify_any_password($current_password, $stored_hash);
      if (!$ok_old && $stored_pass !== '') $ok_old = verify_any_password($current_password, $stored_pass);
      if (!$ok_old) {
        $err = 'كلمة المرور الحالية غير صحيحة.';
      } else {
        $hash = password_hash($new_password, PASSWORD_DEFAULT);
        $hash_esc = $conn->real_escape_string($hash);
        $pass_sets = [];
        if (ua_profile_col($conn, 'password_hash')) $pass_sets[] = "password_hash='$hash_esc'";
        if (ua_profile_col($conn, 'password')) $pass_sets[] = "password='$hash_esc'";
        if ($pass_sets) {
          $ok = $conn->query("UPDATE admin_users SET ".implode(',', $pass_sets)." WHERE id=$uid LIMIT 1");
          if (!$ok) $err = 'DB Error: '.$conn->error;
        }
      }
    }
  }

  if (!$err) {
    $fresh = ua_admin_fetch_user($conn, $uid);
    if ($fresh) {
      ua_admin_profile_set_session($fresh);
      if ($avatar_new !== '') ua_admin_delete_old_image($user['avatar_path'] ?? '', $avatar_new);
      if ($id_front_new !== '') {
        ua_admin_delete_old_image($user['identity_front_image_path'] ?? '', $id_front_new);
        ua_admin_delete_old_image($user['identity_image_path'] ?? '', $id_front_new);
      }
      if ($id_back_new !== '') ua_admin_delete_old_image($user['identity_back_image_path'] ?? '', $id_back_new);
      if (!empty($_POST['remove_avatar'])) ua_admin_delete_old_image($user['avatar_path'] ?? '', '');
      if (!empty($_POST['remove_identity_front_image'])) {
        ua_admin_delete_old_image($user['identity_front_image_path'] ?? '', '');
        ua_admin_delete_old_image($user['identity_image_path'] ?? '', '');
      }
      if (!empty($_POST['remove_identity_back_image'])) ua_admin_delete_old_image($user['identity_back_image_path'] ?? '', '');
      $user = $fresh;
    }
    $msg = 'تم حفظ الملف الشخصي بنجاح.';
  }
}

$avatar = ua_admin_public_image_url($user['avatar_path'] ?? '');
$idfront = ua_admin_public_image_url($user['identity_front_image_path'] ?? '');
if ($idfront === '') $idfront = ua_admin_public_image_url($user['identity_image_path'] ?? '');
$idback = ua_admin_public_image_url($user['identity_back_image_path'] ?? '');
$perms = $_SESSION['perms'] ?? [];
$perm_count = (isset($perms['all']) && $perms['all']) ? 'كل الصلاحيات' : (string)count(array_filter((array)$perms));

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidUserProfile = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidUserProfile) $UA_PAGE_CSS = ['assets/css/android_user_profile.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
if ($uaAndroidUserProfile) { require __DIR__ . '/android_user_profile.php'; include __DIR__ . '/footer.php'; return; }
?>

<div class="content-wrapper ua-manual-page">
  <section class="content">
    <div class="container-fluid">
<div class="ua-profile-shell">
  <?php if($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
  <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

  <form method="post" enctype="multipart/form-data">
    <div class="ua-profile-hero">
      <aside class="ua-profile-card ua-profile-side">
        <div class="ua-profile-avatar">
          <?php if($avatar): ?><img src="<?= h($avatar) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$avatar) ?>" alt=""><?php else: ?><span><?= h(mb_substr((string)($user['full_name'] ?: $user['username']),0,1,'UTF-8')) ?></span><?php endif; ?>
        </div>
        <h2><?= h($user['full_name'] ?: $user['username']) ?></h2>
        <p>@<?= h($user['username'] ?? '') ?></p>
        <div class="ua-profile-badge"><i class="fa fa-key"></i><span><?= h($perm_count) ?></span></div>
        <div class="ua-profile-current" aria-label="البيانات الحالية">
          <div><span>الاسم الحالي</span><strong><?= h(($user['full_name'] ?? '') ?: ($user['username'] ?? '—')) ?></strong></div>
          <div><span>اسم الدخول</span><strong><?= h(($user['username'] ?? '') ?: '—') ?></strong></div>
          <div><span>البريد</span><strong><?= h(($user['email'] ?? '') ?: '—') ?></strong></div>
          <div><span>الاتصال</span><strong><?= h(($user['phone'] ?? '') ?: '—') ?></strong></div>
          <div><span>الوظيفة</span><strong><?= h(($user['job_title'] ?? '') ?: '—') ?></strong></div>
        </div>
      </aside>

      <section class="ua-profile-card ua-profile-main">
        <div class="ua-profile-title">
          <h1><i class="fa fa-id-card-o"></i> الملف الشخصي</h1>
          <?php if(function_exists('has_perm') && has_perm('can_manage_admins')): ?>
            <a class="btn btn-outline-info btn-sm" href="users_permissions.php"><i class="fa fa-users"></i> المستخدمون والصلاحيات</a>
          <?php endif; ?>
        </div>

        <div class="ua-profile-grid">
          <div class="ua-profile-field"><label>الاسم الكامل</label><input class="form-control" name="full_name" value="<?= h($user['full_name'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>اسم المستخدم</label><input class="form-control" value="<?= h($user['username'] ?? '') ?>" readonly></div>
          <div class="ua-profile-field"><label>البريد الإلكتروني</label><input class="form-control" name="email" value="<?= h($user['email'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>المسمى الوظيفي</label><input class="form-control" name="job_title" value="<?= h($user['job_title'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>رقم الاتصال الأساسي</label><input class="form-control" name="phone" value="<?= h($user['phone'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>رقم اتصال إضافي</label><input class="form-control" name="phone2" value="<?= h($user['phone2'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>رقم الهوية</label><input class="form-control" name="identity_no" value="<?= h($user['identity_no'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>العنوان</label><input class="form-control" name="address" value="<?= h($user['address'] ?? '') ?>"></div>
          <div class="ua-profile-field"><label>الصورة الشخصية</label><input type="file" class="form-control" name="avatar_image" accept="image/png,image/jpeg,image/webp"><?php if($avatar): ?><label class="mt-2"><input type="checkbox" name="remove_avatar" value="1"> حذف الصورة الحالية</label><?php endif; ?></div>
          <div class="ua-profile-field"><label>هوية - الوجه الأمامي</label><input type="file" class="form-control" name="identity_front_image" accept="image/png,image/jpeg,image/webp"><?php if($idfront): ?><label class="mt-2"><input type="checkbox" name="remove_identity_front_image" value="1"> حذف الأمامي</label><?php endif; ?></div>
          <div class="ua-profile-field"><label>هوية - الوجه الخلفي</label><input type="file" class="form-control" name="identity_back_image" accept="image/png,image/jpeg,image/webp"><?php if($idback): ?><label class="mt-2"><input type="checkbox" name="remove_identity_back_image" value="1"> حذف الخلفي</label><?php endif; ?></div>
          
          <?php if($idfront || $idback): ?>
            <div class="ua-profile-field ua-u-grid-full">
              <label>معاينة صور الهوية</label>
              <div class="ua-profile-preview-grid">
                <?php if($idfront): ?><div class="ua-profile-preview-card"><strong>الوجه الأمامي</strong><img class="ua-profile-preview" src="<?= h($idfront) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$idfront) ?>" alt=""></div><?php endif; ?>
                <?php if($idback): ?><div class="ua-profile-preview-card"><strong>الوجه الخلفي</strong><img class="ua-profile-preview" src="<?= h($idback) ?>?v=<?= (int)@filemtime(__DIR__.'/'.$idback) ?>" alt=""></div><?php endif; ?>
              </div>
            </div>
          <?php endif; ?>
        </div>

        <section class="ua-profile-pass" aria-label="تغيير كلمة المرور والملاحظات">
          <div class="ua-profile-pass__title"><i class="fa fa-lock" aria-hidden="true"></i><span>تغيير كلمة المرور</span></div>
          <div class="ua-profile-pass__body">
            <div class="ua-profile-grid ua-profile-pass-grid">
              <div class="ua-profile-field"><label>كلمة المرور الحالية</label><input type="password" class="form-control" name="current_password" autocomplete="current-password"></div>
              <div class="ua-profile-field"><label>كلمة المرور الجديدة</label><input type="password" class="form-control" name="new_password" autocomplete="new-password"></div>
              <div class="ua-profile-field"><label>تأكيد كلمة المرور الجديدة</label><input type="password" class="form-control" name="new_password2" autocomplete="new-password"></div>
            </div>
            <div class="ua-profile-field ua-profile-notes-field">
              <label>ملاحظات</label>
              <input class="form-control" name="profile_notes" value="<?= h($user['profile_notes'] ?? '') ?>">
            </div>
          </div>
        </section>

        <div class="ua-profile-actions">
          <button class="btn btn-warning" name="save_profile"><i class="fa fa-save"></i> حفظ الملف الشخصي</button>
          <a class="btn btn-outline-light" href="dashboard.php"><i class="fa fa-home"></i> الرئيسية</a>
        </div>
      </section>
    </div>

  </form>
</div>
    </div>
  </section>
</div>

<?php include __DIR__ . '/footer.php'; ?>
