<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/User.php';

requireLogin();
$user = getCurrentUser();
$userModel = new User();
$db = Database::getInstance();

$errors = [];
$success = null;
$isAjax = isset($_POST['ajax']) && $_POST['ajax'] === '1';
$recentActivities = $db->getAll("SELECT action, description, created_at FROM activity_logs WHERE user_id = ? ORDER BY created_at DESC LIMIT 6", [$user['id']]);
$lastLogin = $user['last_login'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'update_profile') {
        $fieldErrors = [];
        $data = [
            'first_name' => trim($_POST['first_name'] ?? ''),
            'last_name' => trim($_POST['last_name'] ?? ''),
            'phone' => trim($_POST['phone'] ?? ''),
            'bio' => trim($_POST['bio'] ?? ''),
            'region' => trim($_POST['region'] ?? $user['region']),
            'currency' => trim($_POST['currency'] ?? $user['currency']),
            'timezone' => trim($_POST['timezone'] ?? $user['timezone']),
            'language' => trim($_POST['language'] ?? $user['language']),
        ];

        // Basic validation
        if ($data['first_name'] === '') {
            $fieldErrors['first_name'] = 'First name is required.';
        }
        if ($data['last_name'] === '') {
            $fieldErrors['last_name'] = 'Last name is required.';
        }

        // Avatar upload handling
        if (!empty($_FILES['avatar']['name']) && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
            $allowed = ['image/jpeg','image/png','image/gif'];
            $mime = mime_content_type($_FILES['avatar']['tmp_name']);
            if (!in_array($mime, $allowed, true)) {
                $fieldErrors['avatar'] = 'Invalid avatar image type.';
            } else {
                $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
                $destDir = __DIR__ . '/../uploads/avatars';
                if (!is_dir($destDir)) {
                    mkdir($destDir, 0755, true);
                }
                $filename = 'avatar_' . $user['id'] . '_' . time() . '.' . $ext;
                $dest = $destDir . '/' . $filename;
                if (move_uploaded_file($_FILES['avatar']['tmp_name'], $dest)) {
                    $data['avatar'] = 'uploads/avatars/' . $filename;
                } else {
                    $fieldErrors['avatar'] = 'Failed to upload avatar.';
                }
            }
        }

        if (!empty($fieldErrors)) {
            if ($isAjax) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'fieldErrors' => $fieldErrors]);
                exit;
            }
            foreach ($fieldErrors as $m) { $errors[] = $m; }
        }

        if (empty($fieldErrors)) {
            try {
                $userModel->updateProfile($user['id'], $data);
                if ($isAjax) {
                    // refresh user
                    $user = $db->get("SELECT * FROM users WHERE id = ?", [$user['id']]);
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'message' => 'Profile updated.', 'user' => ['first_name' => $user['first_name'], 'last_name' => $user['last_name'], 'avatar' => $user['avatar'], 'last_login' => $user['last_login']]]);
                    exit;
                }
                setFlashMessage('success', 'Profile updated.');
                header('Location: profile.php');
                exit;
            } catch (Exception $e) {
                if ($isAjax) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'errors' => [$e->getMessage()]]);
                    exit;
                }
                $errors[] = $e->getMessage();
            }
        }
    }

    if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
        $fieldErrors = [];
        $current = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';

        if ($new !== $confirm) {
            $fieldErrors['confirm_password'] = 'New password and confirmation do not match.';
        }
        if (strlen($new) < 8) {
            $fieldErrors['new_password'] = 'Password must be at least 8 characters long.';
        }

        if (!empty($fieldErrors)) {
            if ($isAjax) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'fieldErrors' => $fieldErrors]);
                exit;
            }
            foreach ($fieldErrors as $m) { $errors[] = $m; }
        } else {
            try {
                $userModel->changePassword($user['id'], $current, $new);
                if ($isAjax) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => true, 'message' => 'Password changed successfully.']);
                    exit;
                }
                setFlashMessage('success', 'Password changed successfully.');
                header('Location: profile.php');
                exit;
            } catch (Exception $e) {
                if ($isAjax) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'fieldErrors' => ['current_password' => $e->getMessage()]]);
                    exit;
                }
                $errors[] = $e->getMessage();
            }
        }
    }
}

$pageTitle = 'My Profile';
include __DIR__ . '/includes/header.php';
?>

<div class="row">
  <div class="col-12 mb-4">
    <h3 class="mb-1">My Profile</h3>
    <small class="text-muted">Update your personal details, avatar and account settings</small>
  </div>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger">
    <ul class="mb-0">
      <?php foreach ($errors as $err): ?>
        <li><?php echo htmlspecialchars($err); ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<?php if ($msg = getFlashMessage('success')): ?>
  <div class="alert alert-success"><?php echo htmlspecialchars($msg); ?></div>
<?php endif; ?>

<div id="ajaxMessage"></div>

<div class="row gy-4">
  <div class="col-12 col-xl-4">
    <div class="card h-100 text-center">
      <div class="card-body">
        <div class="mb-3">
          <?php if (!empty($user['avatar'])): ?>
            <div class="avatar avatar-xl mx-auto mb-2">
              <img src="/<?php echo htmlspecialchars($user['avatar']); ?>" alt="avatar" class="rounded-circle" style="width:96px;height:96px;object-fit:cover;">
            </div>
          <?php else: ?>
            <div class="avatar avatar-xl mx-auto mb-2">
              <div class="avatar-initial bg-label-primary rounded-circle" style="width:96px;height:96px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:20px;color:#fff;">
                <?php echo isset($user['first_name']) ? strtoupper(substr($user['first_name'],0,1)) : 'U'; ?>
              </div>
            </div>
          <?php endif; ?>
        </div>

        <h5 class="mb-0"><?php echo htmlspecialchars(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')); ?></h5>
        <small class="text-muted d-block mb-3"><?php echo htmlspecialchars($_SESSION['role'] ?? 'Student'); ?></small>

        <div class="d-grid gap-2">
          <a href="dashboard.php" class="btn btn-outline-secondary btn-sm"><i class="ri ri-dashboard-line me-1"></i>Dashboard</a>
          <a href="certificates.php" class="btn btn-outline-primary btn-sm"><i class="ri ri-award-line me-1"></i>My Certificates</a>
          <a href="logout.php" class="btn btn-danger btn-sm"><i class="ri ri-logout-box-r-line me-1"></i>Logout</a>
        </div>

        <?php if ($lastLogin): ?>
          <div id="lastLoginText" class="mt-3 small text-muted">Last login: <?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($lastLogin))); ?></div>
        <?php endif; ?>

        <?php if (!empty($recentActivities)): ?>
          <hr>
          <h6 class="mt-3">Recent Activity</h6>
          <ul class="list-unstyled small mb-0">
            <?php foreach ($recentActivities as $act): ?>
              <li class="mb-2"><?php echo htmlspecialchars($act['action']); ?> <br><small class="text-muted"><?php echo htmlspecialchars(substr($act['description'] ?? '', 0, 70)); ?> • <?php echo date('Y-m-d H:i', strtotime($act['created_at'])); ?></small></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-8">
    <div class="card mb-4">
      <div class="card-body">
        <h5 class="card-title">Profile Details</h5>
        <form id="profileForm" method="post" enctype="multipart/form-data" novalidate>
          <input type="hidden" name="action" value="update_profile">

          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">First name</label>
              <input id="first_name" name="first_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['first_name'] ?? ($user['first_name'] ?? '')); ?>">
              <div class="invalid-feedback" data-field="first_name"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Last name</label>
              <input id="last_name" name="last_name" class="form-control" required value="<?php echo htmlspecialchars($_POST['last_name'] ?? ($user['last_name'] ?? '')); ?>">
              <div class="invalid-feedback" data-field="last_name"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Phone</label>
              <input id="phone" name="phone" class="form-control" value="<?php echo htmlspecialchars($_POST['phone'] ?? ($user['phone'] ?? '')); ?>">
              <div class="invalid-feedback" data-field="phone"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Region</label>
              <select name="region" class="form-select">
                <?php foreach (['usa','europe','africa'] as $r): ?>
                  <option value="<?php echo $r; ?>" <?php echo ($user['region'] ?? '') === $r ? 'selected' : ''; ?>><?php echo ucfirst($r); ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12">
              <label class="form-label">Bio</label>
              <textarea id="bio" name="bio" class="form-control" rows="4"><?php echo htmlspecialchars($_POST['bio'] ?? ($user['bio'] ?? '')); ?></textarea>
              <div class="invalid-feedback" data-field="bio"></div>
            </div>

            <div class="col-md-6">
              <label class="form-label">Timezone</label>
              <input id="timezone" name="timezone" class="form-control" value="<?php echo htmlspecialchars($_POST['timezone'] ?? ($user['timezone'] ?? '')); ?>">
              <div class="invalid-feedback" data-field="timezone"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Avatar</label>
              <input id="avatar" type="file" name="avatar" accept="image/*" class="form-control">
              <div class="invalid-feedback" data-field="avatar"></div>
            </div>

            <div class="col-12 text-end">
              <button class="btn btn-primary"><i class="ri ri-save-line me-1"></i>Save Changes</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <div class="card">
      <div class="card-body">
        <h5 class="card-title">Security</h5>
        <form id="passwordForm" method="post" novalidate>
          <input type="hidden" name="action" value="change_password">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Current password</label>
              <input id="current_password" type="password" name="current_password" class="form-control" required>
              <div class="invalid-feedback" data-field="current_password"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">New password</label>
              <input id="new_password" type="password" name="new_password" class="form-control" required>
              <div class="invalid-feedback" data-field="new_password"></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Confirm password</label>
              <input id="confirm_password" type="password" name="confirm_password" class="form-control" required>
              <div class="invalid-feedback" data-field="confirm_password"></div>
            </div>
            <div class="col-12 text-end">
              <button class="btn btn-primary"><i class="ri ri-lock-password-line me-1"></i>Change Password</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Avatar preview
  var avatarInput = document.querySelector('input[name="avatar"]');
  if (avatarInput) {
    avatarInput.addEventListener('change', function(e) {
      var file = e.target.files[0];
      if (!file) return;
      var img = document.querySelector('img[alt="avatar"]');
      if (!img) return;
      var reader = new FileReader();
      reader.onload = function(ev) { img.src = ev.target.result; };
      reader.readAsDataURL(file);
    });
  }

  // Helpers
  function clearFieldErrors(form) {
    form.querySelectorAll('.is-invalid').forEach(function(el){ el.classList.remove('is-invalid'); });
    form.querySelectorAll('.invalid-feedback').forEach(function(el){ el.textContent = ''; });
    var ajax = document.getElementById('ajaxMessage'); if (ajax) ajax.innerHTML = '';
  }

  function applyFieldErrors(form, fieldErrors) {
    Object.keys(fieldErrors || {}).forEach(function(field){
      var el = form.querySelector('[name="' + field + '"]');
      var fb = form.querySelector('.invalid-feedback[data-field="' + field + '"]');
      if (el) el.classList.add('is-invalid');
      if (fb) fb.textContent = fieldErrors[field];
    });
  }

  function showAlert(type, message) {
    var ajax = document.getElementById('ajaxMessage');
    if (!ajax) return;
    ajax.innerHTML = '<div class="alert alert-' + type + '">' + message + '</div>';
  }

  // Profile form submit via AJAX
  var profileForm = document.getElementById('profileForm');
  if (profileForm) {
    profileForm.addEventListener('submit', function(e) {
      e.preventDefault();
      clearFieldErrors(profileForm);

      // client-side simple validation
      var first = profileForm.querySelector('[name="first_name"]').value.trim();
      var last = profileForm.querySelector('[name="last_name"]').value.trim();
      var avatarFile = profileForm.querySelector('[name="avatar"]').files[0];
      var fieldErrors = {};
      if (!first) fieldErrors['first_name'] = 'First name is required.';
      if (!last) fieldErrors['last_name'] = 'Last name is required.';
      if (avatarFile && avatarFile.size > 2 * 1024 * 1024) fieldErrors['avatar'] = 'Avatar must be under 2MB.';
      if (Object.keys(fieldErrors).length) {
        applyFieldErrors(profileForm, fieldErrors);
        showAlert('danger', 'Please fix the highlighted fields.');
        return;
      }

      var btn = profileForm.querySelector('button[type="submit"], button.btn');
      if (btn) btn.disabled = true;

      var fd = new FormData(profileForm);
      fd.append('ajax', '1');

      fetch('profile.php', { method: 'POST', body: fd, credentials: 'same-origin' })
        .then(function(r){ return r.json(); })
        .then(function(data){
          if (data.success) {
            showAlert('success', data.message || 'Saved.');
            // update name and avatar
            if (data.user) {
              var nameEl = document.querySelector('.card h5.mb-0');
              if (nameEl) nameEl.textContent = (data.user.first_name || '') + ' ' + (data.user.last_name || '');
              if (data.user.avatar) {
                var img = document.querySelector('img[alt="avatar"]');
                if (img) img.src = '/' + data.user.avatar;
              }
              if (data.user.last_login) {
                var ll = document.getElementById('lastLoginText');
                if (ll) ll.textContent = 'Last login: ' + data.user.last_login;
              }
            }
          } else {
            if (data.fieldErrors) {
              applyFieldErrors(profileForm, data.fieldErrors);
              showAlert('danger', 'Please fix the highlighted fields.');
            } else if (data.errors && data.errors.length) {
              showAlert('danger', data.errors.join('<br>'));
            } else {
              showAlert('danger', 'Failed to save profile.');
            }
          }
        })
        .catch(function(){ showAlert('danger','Network error.'); })
        .finally(function(){ if (btn) btn.disabled = false; });
    });
  }

  // Password form submit via AJAX
  var passwordForm = document.getElementById('passwordForm');
  if (passwordForm) {
    passwordForm.addEventListener('submit', function(e) {
      e.preventDefault();
      clearFieldErrors(passwordForm);

      var cur = passwordForm.querySelector('[name="current_password"]').value || '';
      var nw = passwordForm.querySelector('[name="new_password"]').value || '';
      var conf = passwordForm.querySelector('[name="confirm_password"]').value || '';
      var fieldErrors = {};
      if (nw.length < 8) fieldErrors['new_password'] = 'Password must be at least 8 characters.';
      if (nw !== conf) fieldErrors['confirm_password'] = 'Passwords do not match.';
      if (Object.keys(fieldErrors).length) {
        applyFieldErrors(passwordForm, fieldErrors);
        showAlert('danger', 'Please fix the highlighted fields.');
        return;
      }

      var btn = passwordForm.querySelector('button[type="submit"], button.btn');
      if (btn) btn.disabled = true;

      var fd = new FormData(passwordForm);
      fd.append('ajax','1');

      fetch('profile.php', { method: 'POST', body: fd, credentials: 'same-origin' })
        .then(function(r){ return r.json(); })
        .then(function(data){
          if (data.success) {
            clearFieldErrors(passwordForm);
            passwordForm.reset();
            showAlert('success', data.message || 'Password changed.');
          } else {
            if (data.fieldErrors) {
              applyFieldErrors(passwordForm, data.fieldErrors);
              showAlert('danger', 'Please fix the highlighted fields.');
            } else if (data.errors && data.errors.length) {
              showAlert('danger', data.errors.join('<br>'));
            } else {
              showAlert('danger', 'Failed to change password.');
            }
          }
        })
        .catch(function(){ showAlert('danger','Network error.'); })
        .finally(function(){ if (btn) btn.disabled = false; });
    });
  }
});
</script>

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