<?php
// kasir/profil.php — Halaman Profil & Logout (Kasir & Admin)
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireKasir();

$user = currentUser();
$role = $user['role'];

// Statistik personal
$trxTotal = $pdo->prepare("SELECT COUNT(*) FROM transaksi WHERE kasir_id=?");
$trxTotal->execute([$user['id']]);
$trxTotal = (int)$trxTotal->fetchColumn();

$omzetTotal = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM transaksi WHERE kasir_id=?");
$omzetTotal->execute([$user['id']]);
$omzetTotal = (float)$omzetTotal->fetchColumn();

$trxHariIni = $pdo->prepare("SELECT COUNT(*) FROM transaksi WHERE kasir_id=? AND DATE(tanggal)=CURDATE()");
$trxHariIni->execute([$user['id']]);
$trxHariIni = (int)$trxHariIni->fetchColumn();

$omzetHariIni = $pdo->prepare("SELECT COALESCE(SUM(total),0) FROM transaksi WHERE kasir_id=? AND DATE(tanggal)=CURDATE()");
$omzetHariIni->execute([$user['id']]);
$omzetHariIni = (float)$omzetHariIni->fetchColumn();

// Ganti password
$msg   = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ganti_password'])) {
    $passBaru   = $_POST['password_baru']   ?? '';
    $passUlang  = $_POST['password_ulang']  ?? '';
    $passLama   = $_POST['password_lama']   ?? '';

    $stmt = $pdo->prepare("SELECT password FROM akun WHERE id=?");
    $stmt->execute([$user['id']]);
    $hash = $stmt->fetchColumn();

    if (!password_verify($passLama, $hash)) {
        $error = 'Password lama salah.';
    } elseif (strlen($passBaru) < 6) {
        $error = 'Password baru minimal 6 karakter.';
    } elseif ($passBaru !== $passUlang) {
        $error = 'Konfirmasi password tidak cocok.';
    } else {
        $pdo->prepare("UPDATE akun SET password=? WHERE id=?")->execute([password_hash($passBaru, PASSWORD_BCRYPT), $user['id']]);
        $msg = 'Password berhasil diubah.';
    }
}

// Inisial nama untuk avatar
$initials = '';
foreach (explode(' ', $user['nama']) as $kata) {
    $initials .= strtoupper(substr($kata, 0, 1));
    if (strlen($initials) >= 2) break;
}
$roleLabel = $role === 'admin' ? 'Administrator' : 'Kasir';
$roleColor = $role === 'admin' ? '#4f46e5' : '#10b981';
$roleBg    = $role === 'admin' ? '#eef2ff'  : '#d1fae5';
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Profil — <?= NAMA_TOKO ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= BASE_URL ?>css/style.css?v=<?= time() ?>">
  <style>
    /* ── Profil Hero ── */
    .profil-hero {
      background: linear-gradient(135deg, #0a0e17, #111827);
      padding: 40px 20px 28px;
      text-align: center;
      color: #fff;
      position: relative;
    }
    .profil-avatar {
      width: 90px; height: 90px;
      border-radius: 50%;
      background: rgba(255,255,255,.25);
      border: 4px solid rgba(255,255,255,.5);
      margin: 0 auto 14px;
      display: flex; align-items: center; justify-content: center;
      font-size: 36px; font-weight: 700; letter-spacing: -1px;
    }
    .profil-nama  { font-size: 22px; font-weight: 700; margin-bottom: 6px; }
    .profil-role  {
      display: inline-block;
      background: rgba(255,255,255,.2);
      border-radius: 20px;
      padding: 4px 16px;
      font-size: 13px; font-weight: 600;
    }

    /* ── Stat strip ── */
    .profil-stats {
      background: var(--white);
      border-radius: 20px;
      margin: 16px 16px 20px;
      padding: 20px;
      box-shadow: 0 4px 24px rgba(0,0,0,.1);
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 0;
    }
    .ps-item {
      text-align: center;
      padding: 8px 0;
    }
    .ps-item + .ps-item { border-left: 1px solid var(--border); }
    .ps-val   { font-size: 20px; font-weight: 700; color: var(--primary); }
    .ps-label { font-size: 11px; color: var(--muted); margin-top: 2px; }

    /* ── Info rows ── */
    .info-section { padding: 0 16px; margin-bottom: 16px; }
    .info-card    { background: var(--white); border-radius: 16px; border: 1px solid var(--border); overflow: hidden; }
    .info-row {
      display: flex; align-items: center; gap: 14px;
      padding: 14px 16px; border-bottom: 1px solid var(--border);
    }
    .info-row:last-child { border-bottom: none; }
    .info-icon {
      width: 38px; height: 38px; border-radius: 10px;
      display: flex; align-items: center; justify-content: center;
      font-size: 18px; flex-shrink: 0;
    }
    .info-label { font-size: 11px; color: var(--muted); font-weight: 600; margin-bottom: 2px; }
    .info-value { font-size: 14px; font-weight: 600; }

    /* ── Action buttons ── */
    .action-section { padding: 0 16px 100px; display: flex; flex-direction: column; gap: 10px; }
    .action-btn {
      display: flex; align-items: center; gap: 14px;
      padding: 16px; background: var(--white);
      border: 1px solid var(--border); border-radius: 14px;
      cursor: pointer; text-decoration: none;
      color: var(--text); font-family: inherit;
      width: 100%; font-size: 14px; font-weight: 600;
      transition: background .15s;
    }
    .action-btn:hover, .action-btn:active { background: var(--bg); }
    .action-btn .ab-icon {
      width: 42px; height: 42px; border-radius: 12px;
      display: flex; align-items: center; justify-content: center;
      font-size: 20px; flex-shrink: 0;
    }
    .action-btn .ab-text { flex: 1; text-align: left; }
    .action-btn .ab-text small { display: block; font-size: 11px; color: var(--muted); font-weight: 400; margin-top: 1px; }
    .action-btn .ab-arrow { color: var(--muted); font-size: 18px; }
    .action-btn.danger { border-color: #fecaca; }
    .action-btn.danger .ab-text { color: #dc2626; }

    /* ── Modal ganti password ── */
    .modal-ganti { max-width: 420px; }

    /* ── Section title ── */
    .section-title-sm {
      font-size: 11px; font-weight: 700; color: var(--muted);
      letter-spacing: .6px; text-transform: uppercase;
      padding: 0 16px 8px; margin-top: 4px;
    }
  </style>
</head>
<body>
<div class="layout">
  <?php include '../includes/sidebar.php'; ?>

  <div class="main-content">
    <div class="topbar">
      <button class="hamburger" id="hamburgerBtn" aria-label="Menu">☰</button>
      <div class="topbar-title">👤 Profil Saya</div>
    </div>

    <div class="page-body" style="padding:0">

      <?php if ($msg):   ?>
      <div class="alert alert-success" style="margin:12px 16px 0">
        ✅ <?= htmlspecialchars($msg) ?>
      </div>
      <?php endif; ?>
      <?php if ($error): ?>
      <div class="alert alert-error" style="margin:12px 16px 0">
        ❌ <?= htmlspecialchars($error) ?>
      </div>
      <?php endif; ?>

      <!-- Hero -->
      <div class="profil-hero">
        <div class="profil-avatar"><?= $initials ?></div>
        <div class="profil-nama"><?= htmlspecialchars($user['nama']) ?></div>
        <div class="profil-role"><?= $roleLabel ?></div>
      </div>

      <!-- Statistik -->
      <div class="profil-stats">
        <div class="ps-item">
          <div class="ps-val"><?= $trxHariIni ?></div>
          <div class="ps-label">Transaksi Hari Ini</div>
        </div>
        <div class="ps-item">
          <div class="ps-val"><?= formatRp($omzetHariIni) ?></div>
          <div class="ps-label">Omzet Hari Ini</div>
        </div>
      </div>

      <!-- Info Akun -->
      <div class="section-title-sm">Informasi Akun</div>
      <div class="info-section">
        <div class="info-card">
          <div class="info-row">
            <div class="info-icon" style="background:#eef2ff">👤</div>
            <div>
              <div class="info-label">NAMA LENGKAP</div>
              <div class="info-value"><?= htmlspecialchars($user['nama']) ?></div>
            </div>
          </div>
          <div class="info-row">
            <div class="info-icon" style="background:<?= $roleBg ?>">
              <?= $role === 'admin' ? '🛡️' : '🧾' ?>
            </div>
            <div>
              <div class="info-label">ROLE / JABATAN</div>
              <div class="info-value" style="color:<?= $roleColor ?>"><?= $roleLabel ?></div>
            </div>
          </div>
          <div class="info-row">
            <div class="info-icon" style="background:#fef3c7">🏪</div>
            <div>
              <div class="info-label">TOKO</div>
              <div class="info-value"><?= NAMA_TOKO ?></div>
            </div>
          </div>
          <div class="info-row">
            <div class="info-icon" style="background:#d1fae5">📊</div>
            <div>
              <div class="info-label">TOTAL TRANSAKSI</div>
              <div class="info-value"><?= $trxTotal ?> transaksi &nbsp;·&nbsp; <?= formatRp($omzetTotal) ?></div>
            </div>
          </div>
          <div class="info-row">
            <div class="info-icon" style="background:#f3f4f6">🕐</div>
            <div>
              <div class="info-label">SESI SEKARANG</div>
              <div class="info-value"><?= date('d F Y, H:i') ?></div>
            </div>
          </div>
        </div>
      </div>

      <!-- Aksi -->
      <div class="section-title-sm">Pengaturan</div>
      <div class="action-section">

        <!-- Ganti Password -->
        <button class="action-btn" onclick="document.getElementById('modalPassword').classList.add('open')">
          <div class="ab-icon" style="background:#eef2ff">🔒</div>
          <div class="ab-text">
            Ganti Password
            <small>Ubah password akun Anda</small>
          </div>
          <div class="ab-arrow">›</div>
        </button>

        <?php if ($role === 'admin'): ?>
        <!-- Ke halaman manajemen akun (admin) -->
        <a href="<?= BASE_URL ?>admin/akun.php" class="action-btn">
          <div class="ab-icon" style="background:#d1fae5">👥</div>
          <div class="ab-text">
            Manajemen Akun
            <small>Kelola semua akun pengguna</small>
          </div>
          <div class="ab-arrow">›</div>
        </a>
        <?php endif; ?>

        <!-- Tentang -->
        <button class="action-btn" onclick="alert('<?= NAMA_TOKO ?>\nSistem POS v1.0\n© 2026')">
          <div class="ab-icon" style="background:#f3f4f6">ℹ️</div>
          <div class="ab-text">
            Tentang Aplikasi
            <small>Versi 1.0 — <?= NAMA_TOKO ?></small>
          </div>
          <div class="ab-arrow">›</div>
        </button>

        <!-- Logout -->
        <a href="<?= BASE_URL ?>logout.php"
           class="action-btn danger"
           onclick="return confirm('Yakin ingin keluar dari akun?')">
          <div class="ab-icon" style="background:#fee2e2">🚪</div>
          <div class="ab-text">
            Keluar
            <small>Logout dari sesi ini</small>
          </div>
          <div class="ab-arrow" style="color:#dc2626">›</div>
        </a>

      </div>
    </div>
  </div>
</div>

<!-- Modal Ganti Password -->
<div class="modal-overlay" id="modalPassword">
  <div class="modal modal-ganti">
    <div class="modal-header">
      <h4>🔒 Ganti Password</h4>
      <button class="modal-close" onclick="document.getElementById('modalPassword').classList.remove('open')">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="ganti_password" value="1">
      <div class="modal-body">
        <div class="form-group">
          <label>Password Lama</label>
          <input type="password" name="password_lama" class="form-control" required placeholder="Masukkan password lama...">
        </div>
        <div class="form-group">
          <label>Password Baru</label>
          <input type="password" name="password_baru" class="form-control" required placeholder="Minimal 6 karakter...">
        </div>
        <div class="form-group">
          <label>Konfirmasi Password Baru</label>
          <input type="password" name="password_ulang" class="form-control" required placeholder="Ulangi password baru...">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('modalPassword').classList.remove('open')">Batal</button>
        <button type="submit" class="btn btn-primary">Simpan</button>
      </div>
    </form>
  </div>
</div>

<script src="<?= BASE_URL ?>js/app.js"></script>
<?php if ($msg || $error): ?>
<script>
  // Buka modal lagi jika ada error ganti password
  <?php if ($error): ?>
  document.getElementById('modalPassword').classList.add('open');
  <?php endif; ?>
</script>
<?php endif; ?>
</body>
</html>