<?php
// ---------------------------
// Admin Profile (PDO or MySQLi)
// ---------------------------


// Show errors while fixing (turn off later)
ini_set('display_errors', '1');
error_reporting(E_ALL);

require_once 'config.php';
require_once 'auth_guard.php'; // expected to define $loginIdentity and $isEmailLogin, but we fall back if missing

// ---- Normalize DB handle: prefer PDO; else MySQLi ----
$pdo = null;
$mysqli = null;
if (isset($conn) && $conn instanceof PDO) {
  $pdo = $conn;
} elseif (isset($dbh) && $dbh instanceof PDO) {
  $pdo = $dbh;
} elseif (isset($conn) && $conn instanceof mysqli) {
  $mysqli = $conn;
} else {
  die('DB not connected: expected PDO ($conn or $dbh) or MySQLi ($conn).');
}

// ---- CSRF token ----
if (empty($_SESSION['csrf_profile'])) {
  $_SESSION['csrf_profile'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_profile'];

// ---- Helpers ----
function e($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function fetch_admin_mysqli(mysqli $db, string $identity, bool $byEmail): ?array {
  if ($byEmail) {
    $sql = "SELECT * FROM emplist WHERE email = ? LIMIT 1";
  } else {
    $sql = "SELECT * FROM emplist WHERE empId = ? LIMIT 1";
  }
  if (!$stmt = $db->prepare($sql)) return null;
  $stmt->bind_param('s', $identity);
  $stmt->execute();
  $res = $stmt->get_result();
  $row = $res ? $res->fetch_assoc() : null;
  $stmt->close();
  return $row ?: null;
}

function fetch_admin_pdo(PDO $db, string $identity, bool $byEmail): ?array {
  $sql = $byEmail
    ? "SELECT * FROM emplist WHERE email = :v LIMIT 1"
    : "SELECT * FROM emplist WHERE empId = :v LIMIT 1";
  $st = $db->prepare($sql);
  $st->execute([':v' => $identity]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function fetch_admin_any($db, string $identity, bool $byEmail): ?array {
  if ($db instanceof PDO) return fetch_admin_pdo($db, $identity, $byEmail);
  if ($db instanceof mysqli) return fetch_admin_mysqli($db, $identity, $byEmail);
  return null;
}

// ---- Determine identity fallbacks if auth_guard didn’t set ----
if (!isset($loginIdentity) || !$loginIdentity) {
  // prefer email in session (as in your other pages)
  $loginIdentity = $_SESSION['clogin'] ?? ($_SESSION['empId'] ?? '');
}
if (!isset($isEmailLogin)) {
  $isEmailLogin = (bool) filter_var($loginIdentity, FILTER_VALIDATE_EMAIL);
}

// ---- Load admin row ----
$dbh = $pdo ?: $mysqli; // pick one
$admin = fetch_admin_any($dbh, (string)$loginIdentity, (bool)$isEmailLogin);
if (!$admin) {
  // Try the other key if first attempt failed
  $admin = fetch_admin_any($dbh, (string)$loginIdentity, !(bool)$isEmailLogin);
  if ($admin) { $isEmailLogin = !$isEmailLogin; }
}
if (!$admin) {
  die('No admin found for: '.e((string)$loginIdentity));
}

// ---- Flash holder ----
$flash = ['type'=>null,'msg'=>null];

// ---------------------------
// Handle POST (Update Profile)
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // CSRF
  if (!hash_equals($_SESSION['csrf_profile'] ?? '', $_POST['csrf'] ?? '')) {
    $flash = ['type'=>'error','msg'=>'Invalid session token. Please reload and try again.'];
  } else {
    // Inputs
    $newName  = trim($_POST['name']  ?? '');
    $newEmail = trim($_POST['email'] ?? '');
    $newPass  = $_POST['password'] ?? '';

    // Basic validation
    if ($newName === '' || $newEmail === '') {
      $flash = ['type'=>'error','msg'=>'Name and Email are required.'];
    } elseif (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
      $flash = ['type'=>'error','msg'=>'Invalid email format.'];
    } else {
      // Unique email check (except current row)
      if ($pdo instanceof PDO) {
        $chk = $pdo->prepare("SELECT id FROM emplist WHERE email = :e AND id <> :id LIMIT 1");
        $chk->execute([':e'=>$newEmail, ':id'=>$admin['id']]);
        if ($chk->fetch()) $flash = ['type'=>'error','msg'=>'That email is already in use by another user.'];
      } else { // mysqli
        $chk = $mysqli->prepare("SELECT id FROM emplist WHERE email = ? AND id <> ? LIMIT 1");
        $chk->bind_param('si', $newEmail, $admin['id']);
        $chk->execute();
        $res = $chk->get_result();
        if ($res && $res->fetch_assoc()) $flash = ['type'=>'error','msg'=>'That email is already in use by another user.'];
        $chk->close();
      }
    }

    // File upload (optional)
    $profilePath = $admin['profile_pic']; // keep old by default
    if ($flash['type'] === null && !empty($_FILES['profile_picture']['name'])) {
      $f = $_FILES['profile_picture'];
      if ($f['error'] === UPLOAD_ERR_OK) {
        if ($f['size'] > 3 * 1024 * 1024) {
          $flash = ['type'=>'error','msg'=>'Profile image must be ≤ 3 MB.'];
        } else {
          $fi = new finfo(FILEINFO_MIME_TYPE);
          $mime = $fi->file($f['tmp_name']);
          $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp'];
          if (!isset($allowed[$mime])) {
            $flash = ['type'=>'error','msg'=>'Only JPG, PNG or WebP images are allowed.'];
          } else {
            $dirAbs = __DIR__ . '/uploads/profile_pics';
            if (!is_dir($dirAbs)) { @mkdir($dirAbs, 0755, true); }
            $ext = $allowed[$mime];
            $fname = 'admin_'.$admin['id'].'_'.time().'.'.$ext;
            $destAbs = $dirAbs . '/' . $fname;
            $destRel = 'uploads/profile_pics/' . $fname;
            if (move_uploaded_file($f['tmp_name'], $destAbs)) {
              $profilePath = $destRel;
            } else {
              $flash = ['type'=>'error','msg'=>'Failed to save the uploaded file.'];
            }
          }
        }
      } else {
        $flash = ['type'=>'error','msg'=>'Upload error (code '.$f['error'].').'];
      }
    }

    // Proceed with UPDATE if no errors so far
    if ($flash['type'] === null) {
      // keep old password if empty (schema stores plain text)
      $finalPass = ($newPass === '') ? $admin['password'] : $newPass;

      if ($pdo instanceof PDO) {
        if ($profilePath !== $admin['profile_pic']) {
          $sqlUpd = "UPDATE emplist
                     SET username = :u, email = :e, password = :p, profile_pic = :pic
                     WHERE id = :id LIMIT 1";
          $params = [':u'=>$newName, ':e'=>$newEmail, ':p'=>$finalPass, ':pic'=>$profilePath, ':id'=>$admin['id']];
        } else {
          $sqlUpd = "UPDATE emplist
                     SET username = :u, email = :e, password = :p
                     WHERE id = :id LIMIT 1";
          $params = [':u'=>$newName, ':e'=>$newEmail, ':p'=>$finalPass, ':id'=>$admin['id']];
        }
        $upd = $pdo->prepare($sqlUpd);
        $ok  = $upd->execute($params);
      } else { // MySQLi
        if ($profilePath !== $admin['profile_pic']) {
          $sqlUpd = "UPDATE emplist SET username = ?, email = ?, password = ?, profile_pic = ? WHERE id = ? LIMIT 1";
          $upd = $mysqli->prepare($sqlUpd);
          $upd->bind_param('ssssi', $newName, $newEmail, $finalPass, $profilePath, $admin['id']);
        } else {
          $sqlUpd = "UPDATE emplist SET username = ?, email = ?, password = ? WHERE id = ? LIMIT 1";
          $upd = $mysqli->prepare($sqlUpd);
          $upd->bind_param('sssi', $newName, $newEmail, $finalPass, $admin['id']);
        }
        $ok = $upd->execute();
        $upd->close();
      }

      if ($ok) {
        // Keep session identities in sync
        if ($isEmailLogin && isset($_SESSION['clogin']) && $_SESSION['clogin'] !== $newEmail) {
          $_SESSION['clogin'] = $newEmail;
        }
        $_SESSION['cemail'] = $newEmail;

        // Reload row
        $admin = fetch_admin_any($dbh, $isEmailLogin ? $_SESSION['clogin'] : $loginIdentity, $isEmailLogin);
        if (!$admin) {
          $admin = fetch_admin_any($dbh, $loginIdentity, !$isEmailLogin);
        }

        $flash = ['type'=>'success','msg'=>'Profile updated successfully.'];
      } else {
        $flash = ['type'=>'error','msg'=>'Update failed. Please try again.'];
      }
    }
  }
}
?><!-- profile_modal.php -->
<style>
/* Hide scrollbar but keep scroll working */
.hide-scrollbar::-webkit-scrollbar {
  display: none;
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 10+ */
  scrollbar-width: none;     /* Firefox */
}
</style>

<div id="profileModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50" style="margin-top:40px;">
      <div class="bg-white rounded-lg shadow-lg w-full max-w-2xl p-6 relative 
            max-h-[90vh] overflow-y-auto hide-scrollbar">


    <!-- Close button -->
    <button onclick="closeProfileModal()" class="absolute top-2 right-2 text-gray-500 hover:text-gray-700">&times;</button>

    <h1 class="text-2xl font-semibold text-orange-600 mb-6">Admin Profile</h1>

    <?php if ($flash['type']): ?>
      <div class="mb-4 rounded-md p-3 text-sm <?= $flash['type']==='success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-rose-50 text-rose-700 border border-rose-200' ?>">
        <?= e($flash['msg']) ?>
      </div>
    <?php endif; ?>

<form action="" method="POST" enctype="multipart/form-data" class="space-y-4">
      <input type="hidden" name="csrf" value="<?= e($csrf) ?>">

      <!-- Profile Image -->
      <div class="flex justify-center mb-4">
        <?php $img = $admin['profile_pic'] ?: 'default.jpg'; ?>
        <img src="<?= e($img) ?>" alt="Admin Profile"
             class="w-32 h-32 rounded-full border-2 border-orange-600 object-cover">
      </div>

      <!-- Profile Picture Upload -->
      <div>
        <label for="profile_picture" class="block text-sm font-medium text-gray-700">Change Profile Picture</label>
        <input type="file" id="profile_picture" name="profile_picture"
               accept="image/jpeg,image/png,image/webp"
               class="mt-1 p-2 border border-gray-300 rounded-md w-full">
      </div>

      <!-- Name -->
      <div>
        <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
        <input type="text" id="name" name="name" value="<?= e($admin['username']) ?>"
               class="mt-1 p-2 border border-gray-300 rounded-md w-full" required>
      </div>

      <!-- Email -->
      <div>
        <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
        <input type="email" id="email" name="email" value="<?= e($admin['email']) ?>"
               class="mt-1 p-2 border border-gray-300 rounded-md w-full" required>
      </div>

      <!-- Password -->
      <div>
        <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
        <input type="text" id="password" name="password" value=""
               class="mt-1 p-2 border border-gray-300 rounded-md w-full"
               placeholder="Leave blank to keep current">
      </div>

      <div class="flex justify-end items-center pt-2">
        <button type="submit" class="bg-orange-600 text-white py-2 px-4 rounded-md hover:opacity-90">
          Update Profile
        </button>
      </div>
    </form>
  </div>
</div>
<script>
function openProfileModal() {
  document.getElementById("profileModal").classList.remove("hidden");
}
function closeProfileModal() {
  document.getElementById("profileModal").classList.add("hidden");
}
</script>
