<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

$user = auth_user();
$uid  = (int)$user['id'];
$errors = [];
$success = '';

if (isset($_GET['saved'])) $success = 'Οι αλλαγές αποθηκεύτηκαν επιτυχώς.';

$uploadDir = __DIR__ . '/../uploads/avatars/';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    gp_require_csrf();
    $action = $_POST['action'] ?? 'info';

    // ── Avatar upload ──
    if ($action === 'avatar') {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] !== UPLOAD_ERR_NO_FILE) {
            $file = $_FILES['avatar'];
            if ($file['error'] !== UPLOAD_ERR_OK) {
                $errors[] = 'Upload error: ' . $file['error'];
            } else {
                $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime  = finfo_file($finfo, $file['tmp_name']);
                finfo_close($finfo);
                if (!in_array($mime, $allowedTypes, true)) {
                    $errors[] = 'Μη έγκυρος τύπος αρχείου. JPG, PNG ή WEBP μόνο.';
                } else {
                    $ext      = $mime === 'image/png' ? 'png' : ($mime === 'image/webp' ? 'webp' : 'jpg');
                    $filename = 'user_' . $uid . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
                    $dest     = $uploadDir . $filename;
                    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                    if (move_uploaded_file($file['tmp_name'], $dest)) {
                        $pdo->prepare("UPDATE users SET avatar_path = ? WHERE id = ?")->execute(['/gopools/public/uploads/avatars/' . $filename, $uid]);
                        $_SESSION['gp_user']['avatar_path'] = '/gopools/public/uploads/avatars/' . $filename;
                        gp_log_action($pdo, 'PROFILE_UPDATE', 'user', $uid, 'Updated avatar');
                        header('Location: profile.php?saved=1'); exit;
                    } else { $errors[] = 'Αποτυχία αποθήκευσης αρχείου.'; }
                }
            }
        }
    }

    // ── Personal info ──
    if ($action === 'info') {
        $email    = trim((string)($_POST['email']     ?? ''));
        $phone    = trim((string)($_POST['phone']     ?? ''));
        $fullName = trim((string)($_POST['full_name'] ?? ''));
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Μη έγκυρο email.';
        }
        if (!$errors) {
            $pdo->prepare("UPDATE users SET email = ?, phone = ?, full_name = ? WHERE id = ?")
                ->execute([$email ?: null, $phone ?: null, $fullName ?: null, $uid]);
            gp_log_action($pdo, 'PROFILE_UPDATE', 'user', $uid, 'Updated contact info');
            header('Location: profile.php?saved=1'); exit;
        }
    }

    // ── Password change ──
    if ($action === 'password') {
        $pass1 = (string)($_POST['new_pass']  ?? '');
        $pass2 = (string)($_POST['new_pass2'] ?? '');
        $current = (string)($_POST['current_pass'] ?? '');

        $dbRow = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?")->execute([$uid]) ? null : null;
        $st = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
        $st->execute([$uid]);
        $dbRow = $st->fetch();

        if ($current === '' || !password_verify($current, $dbRow['password_hash'] ?? '')) {
            $errors[] = 'Ο τρέχων κωδικός δεν είναι σωστός.';
        } elseif ($pass1 === '') {
            $errors[] = 'Εισάγετε νέο κωδικό.';
        } elseif ($pass1 !== $pass2) {
            $errors[] = 'Οι κωδικοί δεν ταιριάζουν.';
        } elseif (strlen($pass1) < 6) {
            $errors[] = 'Ο κωδικός πρέπει να έχει τουλάχιστον 6 χαρακτήρες.';
        } else {
            $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?")->execute([password_hash($pass1, PASSWORD_DEFAULT), $uid]);
            gp_log_action($pdo, 'PROFILE_UPDATE', 'user', $uid, 'Changed password');
            header('Location: profile.php?saved=1'); exit;
        }
    }
}

// Update last_login on profile visit? No — track at login. Just read current user.
$st = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$st->execute([$uid]);
$dbUser = $st->fetch();

// Recent project activity for this user
$recentProjects = [];
try {
    $stRP = $pdo->prepare("
        SELECT p.id, p.title, p.code, p.status, p.created_at, p.updated_at,
               CASE WHEN p.created_by_user_id = :uid THEN 'created' ELSE 'updated' END AS action_type
        FROM projects p
        WHERE p.created_by_user_id = :uid OR p.updated_by_user_id = :uid
        ORDER BY GREATEST(COALESCE(p.updated_at, '1970-01-01'), COALESCE(p.created_at, '1970-01-01')) DESC
        LIMIT 5
    ");
    $stRP->execute([':uid' => $uid]);
    $recentProjects = $stRP->fetchAll();
} catch (Throwable $e) {}

// Stats
$projectsCreated = 0;
try {
    $stPC = $pdo->prepare("SELECT COUNT(*) FROM projects WHERE created_by_user_id = ?");
    $stPC->execute([$uid]);
    $projectsCreated = (int)$stPC->fetchColumn();
} catch (Throwable $e) {}

$page_title = 'Προφίλ';
include __DIR__ . '/../includes/header.php';
?>

<style>
.profile-hero {
  background: linear-gradient(135deg, var(--gp-primary) 0%, #6366f1 100%);
  border-radius: 20px; padding: 28px 32px; margin-bottom: 20px;
  color: #fff; display: flex; align-items: center; gap: 24px;
  position: relative; overflow: hidden;
}
.profile-hero::before {
  content: ''; position: absolute; top: -60px; right: -60px;
  width: 240px; height: 240px; border-radius: 50%;
  background: rgba(255,255,255,0.05);
}
.profile-avatar-wrap { position: relative; flex-shrink: 0; }
.profile-avatar {
  width: 80px; height: 80px; border-radius: 50%; object-fit: cover;
  border: 3px solid rgba(255,255,255,0.4);
}
.profile-avatar-placeholder {
  width: 80px; height: 80px; border-radius: 50%;
  background: rgba(255,255,255,0.15); border: 3px solid rgba(255,255,255,0.4);
  display: flex; align-items: center; justify-content: center;
  font-size: 2rem; font-weight: 800; color: #fff;
}
.profile-name { font-size: 1.4rem; font-weight: 800; }
.profile-role-badge {
  display: inline-flex; align-items: center; padding: 3px 10px;
  background: rgba(255,255,255,0.2); border-radius: 999px;
  font-size: .75rem; font-weight: 700; margin-top: 6px;
}
.profile-stat { text-align: center; }
.profile-stat-value { font-size: 1.6rem; font-weight: 800; }
.profile-stat-label { font-size: .72rem; opacity: .8; margin-top: 2px; }

.profile-tabs { display: flex; gap: 4px; border-bottom: 2px solid var(--gp-card-border); margin-bottom: 20px; }
.profile-tab {
  padding: 10px 18px; font-size: .85rem; font-weight: 700; border: none;
  background: transparent; color: var(--gp-muted); cursor: pointer;
  border-bottom: 2px solid transparent; margin-bottom: -2px;
  text-decoration: none; display: inline-block; transition: all .18s;
}
.profile-tab.active { color: var(--gp-primary); border-bottom-color: var(--gp-primary); }

.upload-drop-zone {
  border: 2px dashed var(--gp-card-border); border-radius: 14px;
  padding: 24px; text-align: center; cursor: pointer; transition: all .2s;
}
.upload-drop-zone:hover { border-color: var(--gp-primary); background: rgba(37,99,235,.02); }

@media(max-width:640px) {
  .profile-hero { flex-direction: column; align-items: flex-start; padding: 20px; }
  .profile-hero-stats { display: none; }
}
</style>

<!-- Hero -->
<div class="profile-hero">
  <div class="profile-avatar-wrap">
    <?php if (!empty($dbUser['avatar_path'])): ?>
      <img class="profile-avatar" src="<?php echo h($dbUser['avatar_path']); ?>" alt="">
    <?php else: ?>
      <div class="profile-avatar-placeholder"><?php echo strtoupper(substr($dbUser['username'],0,1)); ?></div>
    <?php endif; ?>
  </div>
  <div style="flex:1;min-width:0;">
    <div class="profile-name"><?php echo h($dbUser['full_name'] ?: $dbUser['username']); ?></div>
    <?php if ($dbUser['full_name'] && $dbUser['full_name'] !== $dbUser['username']): ?>
    <div style="font-size:.9rem;opacity:.8;margin-top:2px;">@<?php echo h($dbUser['username']); ?></div>
    <?php endif; ?>
    <span class="profile-role-badge">
      <?php $roleLabels = ['admin'=>'Admin','manager'=>'Manager','employee'=>'Εργαζόμενος','partner'=>'Συνεργάτης','secretary'=>'Γραμματεία','customer'=>'Πελάτης']; ?>
      <?php echo $roleLabels[$dbUser['role'] ?? ''] ?? h($dbUser['role'] ?? ''); ?>
    </span>
    <?php if ($dbUser['email']): ?>
    <div style="font-size:.85rem;opacity:.8;margin-top:6px;">✉️ <?php echo h($dbUser['email']); ?></div>
    <?php endif; ?>
    <?php if ($dbUser['phone']): ?>
    <div style="font-size:.85rem;opacity:.8;">📞 <?php echo h($dbUser['phone']); ?></div>
    <?php endif; ?>
  </div>
  <div class="profile-hero-stats" style="display:flex;gap:28px;flex-shrink:0;">
    <div class="profile-stat">
      <div class="profile-stat-value"><?php echo $projectsCreated; ?></div>
      <div class="profile-stat-label">Έργα που<br>δημιούργησε</div>
    </div>
  </div>
</div>

<?php if ($success): ?>
<div class="alert-success" style="margin-bottom:16px;"><?php echo h($success); ?></div>
<?php endif; ?>
<?php foreach ($errors as $err): ?>
<div class="alert-danger" style="margin-bottom:10px;"><?php echo h($err); ?></div>
<?php endforeach; ?>

<!-- Tabs -->
<?php $activeTab = $_GET['tab'] ?? 'info'; ?>
<div class="profile-tabs">
  <a class="profile-tab <?php echo $activeTab === 'info' ? 'active' : ''; ?>" href="?tab=info">👤 Στοιχεία</a>
  <a class="profile-tab <?php echo $activeTab === 'avatar' ? 'active' : ''; ?>" href="?tab=avatar">📷 Φωτογραφία</a>
  <a class="profile-tab <?php echo $activeTab === 'security' ? 'active' : ''; ?>" href="?tab=security">🔐 Ασφάλεια</a>
  <?php if ($recentProjects): ?>
  <a class="profile-tab <?php echo $activeTab === 'activity' ? 'active' : ''; ?>" href="?tab=activity">📋 Δραστηριότητα</a>
  <?php endif; ?>
</div>

<?php if ($activeTab === 'info'): ?>
<!-- Personal Info -->
<div class="card">
  <div style="font-weight:800;font-size:1rem;margin-bottom:18px;">👤 Προσωπικά Στοιχεία</div>
  <form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="action" value="info">
    <div class="form-grid">
      <div class="form-group">
        <label>Πλήρες Ονοματεπώνυμο</label>
        <input type="text" name="full_name" value="<?php echo h($dbUser['full_name'] ?? ''); ?>" placeholder="Ονοματεπώνυμο">
      </div>
      <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" value="<?php echo h($dbUser['email'] ?? ''); ?>" placeholder="email@example.com">
      </div>
      <div class="form-group">
        <label>Τηλέφωνο</label>
        <input type="tel" name="phone" value="<?php echo h($dbUser['phone'] ?? ''); ?>" placeholder="+30 6900000000">
      </div>
      <div class="form-group">
        <label>Username</label>
        <input type="text" value="<?php echo h($dbUser['username']); ?>" disabled style="opacity:.6;">
        <small style="color:var(--gp-muted);font-size:.72rem;">Δεν μπορεί να αλλαχτεί</small>
      </div>
    </div>
    <div class="form-actions">
      <button type="submit" class="btn btn-primary">💾 Αποθήκευση</button>
    </div>
  </form>
</div>

<?php elseif ($activeTab === 'avatar'): ?>
<!-- Avatar -->
<div class="card" style="max-width:500px;">
  <div style="font-weight:800;font-size:1rem;margin-bottom:18px;">📷 Φωτογραφία Προφίλ</div>
  <div style="display:flex;align-items:center;gap:20px;margin-bottom:20px;">
    <?php if (!empty($dbUser['avatar_path'])): ?>
      <img src="<?php echo h($dbUser['avatar_path']); ?>" style="width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--gp-primary);">
    <?php else: ?>
      <div style="width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,var(--gp-primary),#6366f1);color:#fff;display:flex;align-items:center;justify-content:center;font-size:2rem;font-weight:800;"><?php echo strtoupper(substr($dbUser['username'],0,1)); ?></div>
    <?php endif; ?>
    <div>
      <div style="font-weight:700;"><?php echo h($dbUser['username']); ?></div>
      <div style="font-size:.8rem;color:var(--gp-muted);">JPG, PNG ή WEBP · Μέγ. 2MB</div>
    </div>
  </div>
  <form method="post" enctype="multipart/form-data">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="action" value="avatar">
    <div class="upload-drop-zone">
      <div style="font-size:2rem;margin-bottom:8px;">📸</div>
      <input type="file" name="avatar" accept="image/jpeg,image/png,image/webp" style="margin:0 auto;display:block;">
      <div style="font-size:.78rem;color:var(--gp-muted);margin-top:8px;">Επιλέξτε φωτογραφία</div>
    </div>
    <div class="form-actions">
      <button type="submit" class="btn btn-primary">📤 Ανέβασμα</button>
    </div>
  </form>
</div>

<?php elseif ($activeTab === 'security'): ?>
<!-- Password -->
<div class="card" style="max-width:500px;">
  <div style="font-weight:800;font-size:1rem;margin-bottom:18px;">🔐 Αλλαγή Κωδικού</div>
  <form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="action" value="password">
    <div class="form-group">
      <label>Τρέχων Κωδικός</label>
      <input type="password" name="current_pass" autocomplete="current-password" placeholder="••••••">
    </div>
    <div class="form-group">
      <label>Νέος Κωδικός</label>
      <input type="password" name="new_pass" autocomplete="new-password" placeholder="Τουλάχιστον 6 χαρακτήρες">
    </div>
    <div class="form-group">
      <label>Επιβεβαίωση Νέου Κωδικού</label>
      <input type="password" name="new_pass2" autocomplete="new-password" placeholder="••••••">
    </div>
    <div class="form-actions">
      <button type="submit" class="btn btn-primary">🔐 Αλλαγή Κωδικού</button>
    </div>
  </form>
</div>

<?php elseif ($activeTab === 'activity' && $recentProjects): ?>
<!-- Recent activity -->
<div class="card">
  <div style="font-weight:800;font-size:1rem;margin-bottom:18px;">📋 Πρόσφατη Δραστηριότητα</div>
  <div style="display:flex;flex-direction:column;gap:10px;">
    <?php foreach ($recentProjects as $rp): ?>
    <a href="/gopools/public/projects/edit.php?id=<?php echo (int)$rp['id']; ?>"
       style="display:flex;align-items:center;gap:14px;padding:12px 16px;background:var(--gp-nav-bg-2);border-radius:12px;text-decoration:none;color:var(--gp-text);border:1px solid var(--gp-card-border);transition:all .18s;"
       onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform=''">
      <span style="font-size:1.4rem;"><?php echo $rp['action_type'] === 'created' ? '➕' : '✏️'; ?></span>
      <div style="flex:1;min-width:0;">
        <div style="font-weight:700;font-size:.88rem;"><?php echo h($rp['title']); ?></div>
        <div style="font-size:.72rem;color:var(--gp-muted);"><?php echo h($rp['code']); ?> · <?php echo $rp['action_type'] === 'created' ? 'Δημιουργήθηκε' : 'Τελευταία επεξεργασία'; ?></div>
      </div>
      <div style="font-size:.72rem;color:var(--gp-muted);white-space:nowrap;"><?php echo gp_date(substr($rp['updated_at'] ?: $rp['created_at'],0,10)); ?></div>
      <span style="font-size:.7rem;font-weight:700;padding:2px 8px;border-radius:999px;background:rgba(37,99,235,.1);color:var(--gp-primary);"><?php echo h($rp['status']); ?></span>
    </a>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

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