<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

// Load config FIRST (before any includes)
$config_path = dirname(__DIR__) . '/include/config.php';
if (!file_exists($config_path)) {
    die("Configuration file not found");
}
include($config_path);

// Check admin status BEFORE any output
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id AND is_admin = 1 LIMIT 1");
$stmt->execute([':user_id' => $_SESSION['user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    header("Location: dashboard.php");
    exit();
}

// NOW include header (which handles session and outputs HTML)
include('include/header.php');
$page_title = WEB_NAME . " | Admin Profile";
?>
<title>Admin Profile - <?php echo $site_data['web_name']; ?></title>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Admin Profile Settings</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active" aria-current="page">Profile Settings</li>
    </ol>
  </div>

  <div class="row">
    <!-- Profile Card -->
    <div class="col-lg-8 mx-auto">
      <div class="card shadow mb-4 border-left-primary">
        <div class="card-header py-3 bg-gradient-primary">
          <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-user-circle mr-2"></i>Admin Profile Management
          </h6>
        </div>
        <div class="card-body p-4">
          
          <!-- Alert Messages -->
          <div id="alertContainer"></div>

          <!-- Profile Info Section -->
          <form id="adminProfileForm" autocomplete="off" novalidate>
            
            <!-- Section 1: Basic Information -->
            <div class="form-section mb-4 pb-4 border-bottom">
              <h5 class="text-primary font-weight-bold mb-3">
                <i class="fas fa-info-circle mr-2"></i>Basic Information
              </h5>

              <div class="row">
                <div class="col-md-6">
                  <div class="form-group">
                    <label for="profile_username" class="font-weight-bold">
                      <i class="fas fa-user mr-2 text-primary"></i>Username
                    </label>
                    <input type="text" class="form-control form-control-lg" id="profile_username" 
                           value="<?php echo htmlspecialchars($user['username']); ?>" required>
                    <small class="form-text text-muted">Your unique login username. 3-50 characters.</small>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="form-group">
                    <label for="profile_fullname" class="font-weight-bold">
                      <i class="fas fa-id-card mr-2 text-primary"></i>Full Name
                    </label>
                    <input type="text" class="form-control form-control-lg" id="profile_fullname" 
                           value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                    <small class="form-text text-muted">Your full name as it appears in records.</small>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label for="profile_email" class="font-weight-bold">
                  <i class="fas fa-envelope mr-2 text-primary"></i>Email Address
                </label>
                <input type="email" class="form-control form-control-lg" id="profile_email" 
                       value="<?php echo htmlspecialchars($user['email']); ?>" required>
                <small class="form-text text-muted">Your email address for login and notifications.</small>
              </div>
            </div>

            <!-- Section 2: Password Change -->
            <div class="form-section mb-4 pb-4 border-bottom">
              <h5 class="text-primary font-weight-bold mb-3">
                <i class="fas fa-lock mr-2"></i>Change Password
              </h5>
              
              <p class="text-muted small mb-3">
                <i class="fas fa-info-circle mr-1"></i>Leave password fields blank to keep your current password.
              </p>

              <div class="form-group">
                <label for="profile_password" class="font-weight-bold">
                  New Password
                </label>
                <input type="password" class="form-control form-control-lg" id="profile_password" 
                       placeholder="Enter new password (or leave blank)">
                <small class="form-text text-muted">Minimum 8 characters. Mix of uppercase, lowercase, numbers, and symbols recommended.</small>
                <div class="password-strength mt-2" id="passwordStrength" style="display: none;">
                  <div class="progress" style="height: 6px;">
                    <div id="strengthBar" class="progress-bar" style="width: 0%;"></div>
                  </div>
                  <small id="strengthText" class="text-muted"></small>
                </div>
              </div>

              <div class="form-group">
                <label for="profile_password_confirm" class="font-weight-bold">
                  Confirm Password
                </label>
                <input type="password" class="form-control form-control-lg" id="profile_password_confirm" 
                       placeholder="Re-enter new password">
              </div>

              <!-- Password Requirements -->
              <div class="alert alert-light border-left-warning" style="display: none;" id="passwordRequirements">
                <small class="font-weight-bold text-warning">
                  <i class="fas fa-check-circle mr-1"></i>Password Requirements:
                </small>
                <ul class="small mt-2 mb-0" style="list-style: none; padding-left: 0;">
                  <li><i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i><span id="req-length">At least 8 characters</span></li>
                  <li><i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i><span id="req-uppercase">One uppercase letter</span></li>
                  <li><i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i><span id="req-lowercase">One lowercase letter</span></li>
                  <li><i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i><span id="req-number">One number</span></li>
                </ul>
              </div>
            </div>

            <!-- Action Buttons -->
            <div class="form-section">
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-primary btn-lg" id="saveProfileBtn">
                  <i class="fas fa-save mr-2"></i>Save Changes
                </button>
                <button type="button" class="btn btn-secondary btn-lg" id="cancelBtn">
                  <i class="fas fa-times mr-2"></i>Cancel
                </button>
              </div>
            </div>

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

      <!-- Security Info Card -->
      <div class="card shadow border-left-info mb-4">
        <div class="card-header py-3 bg-gradient-info">
          <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-shield-alt mr-2"></i>Security Information
          </h6>
        </div>
        <div class="card-body">
          <p class="mb-2">
            <strong>Last Updated:</strong> 
            <span class="text-muted"><?php echo date('M d, Y H:i A', strtotime($user['updated_at'])); ?></span>
          </p>
          <p class="mb-2">
            <strong>Account Created:</strong> 
            <span class="text-muted"><?php echo date('M d, Y H:i A', strtotime($user['created_at'])); ?></span>
          </p>
          <p class="mb-0">
            <strong>Admin Status:</strong> 
            <span class="badge badge-success">Active Administrator</span>
          </p>
        </div>
      </div>
    </div>
  </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// ── Password Strength Checker ──────────────────────────────────────
function checkPasswordStrength(password) {
  if (!password) {
    $('#passwordStrength').hide();
    $('#passwordRequirements').hide();
    return 0;
  }

  $('#passwordStrength').show();
  $('#passwordRequirements').show();

  var strength = 0;
  var feedback = [];

  // Length check
  if (password.length >= 8) {
    strength += 25;
    $('#req-length').html('<i class="fas fa-check-circle text-success mr-1"></i>At least 8 characters').css('color', '#28a745');
  } else {
    $('#req-length').html('<i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i>At least 8 characters').css('color', '#6c757d');
  }

  // Uppercase check
  if (/[A-Z]/.test(password)) {
    strength += 25;
    $('#req-uppercase').html('<i class="fas fa-check-circle text-success mr-1"></i>One uppercase letter').css('color', '#28a745');
  } else {
    $('#req-uppercase').html('<i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i>One uppercase letter').css('color', '#6c757d');
  }

  // Lowercase check
  if (/[a-z]/.test(password)) {
    strength += 25;
    $('#req-lowercase').html('<i class="fas fa-check-circle text-success mr-1"></i>One lowercase letter').css('color', '#28a745');
  } else {
    $('#req-lowercase').html('<i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i>One lowercase letter').css('color', '#6c757d');
  }

  // Number check
  if (/[0-9]/.test(password)) {
    strength += 25;
    $('#req-number').html('<i class="fas fa-check-circle text-success mr-1"></i>One number').css('color', '#28a745');
  } else {
    $('#req-number').html('<i class="fas fa-circle text-muted mr-1" style="font-size: 0.4rem;"></i>One number').css('color', '#6c757d');
  }

  // Update progress bar
  var color = strength <= 25 ? '#e74a3b' : strength <= 50 ? '#f6c23e' : strength <= 75 ? '#51bcda' : '#1cc88a';
  var text = strength <= 25 ? 'Weak' : strength <= 50 ? 'Fair' : strength <= 75 ? 'Good' : 'Strong';
  
  $('#strengthBar').css('width', strength + '%').css('backgroundColor', color);
  $('#strengthText').html('<span style="color: ' + color + ';">' + text + ' (' + strength + '%)</span>');

  return strength;
}

// ── Password Input Events ──────────────────────────────────────────
$('#profile_password').on('input', function() {
  checkPasswordStrength($(this).val());
});

// ── Save Profile ───────────────────────────────────────────────────
$('#saveProfileBtn').on('click', function() {
  var username = $('#profile_username').val().trim();
  var email    = $('#profile_email').val().trim();
  var fullname = $('#profile_fullname').val().trim();
  var password = $('#profile_password').val();
  var confirm  = $('#profile_password_confirm').val();

  // Validation
  if (!username || !email || !fullname) {
    showAlert('All basic information fields are required.', 'error');
    return;
  }

  if (username.length < 3 || username.length > 50) {
    showAlert('Username must be between 3 and 50 characters.', 'error');
    return;
  }

  // Email validation
  if (!isValidEmail(email)) {
    showAlert('Please enter a valid email address.', 'error');
    return;
  }

  // Password validation (if provided)
  if (password) {
    if (password.length < 8) {
      showAlert('Password must be at least 8 characters.', 'error');
      return;
    }
    if (password !== confirm) {
      showAlert('Passwords do not match.', 'error');
      return;
    }
    if (!isStrongPassword(password)) {
      showAlert('Password must contain uppercase, lowercase, and numbers.', 'error');
      return;
    }
  }

  $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>Saving...');

  $.ajax({
    url: 'ajax/admin_profile.php',
    type: 'POST',
    data: { 
      action: 'save', 
      username: username, 
      email: email, 
      fullname: fullname, 
      password: password 
    },
    dataType: 'json',
    success: function(data) {
      $('#saveProfileBtn').prop('disabled', false).html('<i class="fas fa-save mr-2"></i>Save Changes');
      if (data.status == '1') {
        showAlert(data.msg, 'success');
        setTimeout(() => { location.reload(); }, 1500);
      } else {
        showAlert(data.msg, 'error');
      }
    },
    error: function() {
      $('#saveProfileBtn').prop('disabled', false).html('<i class="fas fa-save mr-2"></i>Save Changes');
      showAlert('An error occurred. Please try again.', 'error');
    }
  });
});

// ── Cancel Button ──────────────────────────────────────────────────
$('#cancelBtn').on('click', function() {
  location.reload();
});

// ── Helper Functions ───────────────────────────────────────────────
function showAlert(message, type) {
  var alertClass = type === 'error' ? 'alert-danger' : 'alert-success';
  var icon = type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle';
  var html = '<div class="alert ' + alertClass + ' alert-dismissible fade show" role="alert">' +
    '<i class="fas ' + icon + ' mr-2"></i>' + message +
    '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
    '</div>';
  $('#alertContainer').html(html);
}

function isValidEmail(email) {
  var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
}

function isStrongPassword(password) {
  return /[A-Z]/.test(password) && /[a-z]/.test(password) && /[0-9]/.test(password);
}
</script>

<style>
  .bg-gradient-primary {
    background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
  }
  .bg-gradient-info {
    background: linear-gradient(135deg, #51bcda 0%, #2680bd 100%);
  }
  .form-control-lg {
    height: calc(2.5rem + 2px);
    font-size: 1rem;
    padding: 0.75rem 1rem;
  }
  .border-left-primary {
    border-left: 4px solid #4e73df !important;
  }
  .border-left-info {
    border-left: 4px solid #51bcda !important;
  }
  .form-section {
    animation: fadeIn 0.3s ease-in;
  }
  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
  .gap-2 {
    gap: 10px !important;
  }
</style>

<?php include ('include/footer.php'); ?>