<?php
require_once 'config.php';
require_once 'auth-helpers.php';

// Initialize variables
$error = '';

// Check if user already logged in
if ($is_logged_in) {
    header("Location: dashboard.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['firstname'] ?? '');
    $last_name = trim($_POST['lastname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $terms = isset($_POST['terms']) ? 1 : 0;
    
    // Validation
    if (empty($first_name) || empty($last_name) || empty($email) || empty($phone) || empty($password) || empty($confirm_password)) {
        $error = "All fields are required!";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address!";
    } elseif (!$terms) {
        $error = "You must agree to the terms and conditions!";
    } else {
        // Validate password strength
        $validation = validatePassword($password);
        if (!$validation['valid']) {
            $error = $validation['message'];
        } elseif ($password !== $confirm_password) {
            $error = "Passwords do not match!";
        } else {
            // Check if email already exists
            $query = "SELECT id FROM customers WHERE email = ? LIMIT 1";
            $stmt = $conn->prepare($query);
            
            if ($stmt) {
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows > 0) {
                    $error = "Email already registered! Please use another email or log in.";
                } else {
                    // Store registration data in session temporarily
                    $_SESSION['reg_firstname'] = $first_name;
                    $_SESSION['reg_lastname'] = $last_name;
                    $_SESSION['reg_email'] = $email;
                    $_SESSION['reg_phone'] = $phone;
                    $_SESSION['reg_password'] = password_hash($password, PASSWORD_BCRYPT);
                    
                    // Generate and send OTP
                    $otp = generateOTP();
                    $storeResult = storeOTP($conn, $email, $otp);
                    
                    if ($storeResult['success']) {
                        $userName = trim($first_name . ' ' . $last_name);
                        $sendResult = sendOTPEmail($email, $otp, $userName);
                        
                        if ($sendResult['success']) {
                            // Redirect to OTP verification page
                            header('Location: verify-registration-otp.php?email=' . urlencode($email));
                            exit;
                        } else {
                            $error = 'Unable to send OTP. Please try again later.';
                        }
                    } else {
                        $error = 'An error occurred. Please try again later.';
                    }
                }
                
                $stmt->close();
            } else {
                $error = "Database error. Please try again later.";
            }
        }
    }
}
?>
<!doctype html>
<html class="no-js" lang="zxx">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Register - Real Estate</title>
  <meta name="author" content="vecuro">
  <meta name="description" content="Zemaraim HTML Template">
  <meta name="keywords" content="Zemaraim HTML Template">
  <meta name="robots" content="INDEX,FOLLOW">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="icon" type="image/png" href="assets/img/favicons/favicon.png">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="theme-color" content="#ffffff">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
  <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/css/fontawesome.min.css">
  <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
  <link rel="stylesheet" href="assets/css/slick.min.css">
  <link rel="stylesheet" href="assets/css/style.css">
  <style>
    .register-section {
      min-height: 100vh;
      display: flex;
      align-items: center;
      background: #f8f9fa;
      padding: 40px 20px;
    }

    .register-container {
      width: 100%;
      max-width: 1000px;
      margin: 0 auto;
    }

    .register-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 40px;
      align-items: center;
      background: white;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
    }

    .register-image {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      padding: 60px 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      min-height: 841px;
      color: white;
      text-align: center;
    }

    .register-image-content h2 {
      font-size: 32px;
      font-weight: 700;
      margin-bottom: 20px;
      font-family: 'Playfair Display', serif;
    }

    .register-image-content p {
      font-size: 16px;
      line-height: 1.6;
      margin-bottom: 30px;
      opacity: 0.9;
    }

    .benefit-list {
      list-style: none;
      padding: 0;
      text-align: left;
      display: inline-block;
    }

    .benefit-list li {
      margin-bottom: 15px;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .benefit-list i {
      font-size: 16px;
    }

    .register-form {
      padding: 50px 40px;
      max-height: auto;
      overflow-y: auto;
    }

    .register-form::-webkit-scrollbar {
      width: 6px;
    }

    .register-form::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    .register-form::-webkit-scrollbar-thumb {
      background: #667eea;
      border-radius: 3px;
    }

    .register-form::-webkit-scrollbar-thumb:hover {
      background: #764ba2;
    }

    .register-header {
      margin-bottom: 30px;
    }

    .register-header h1 {
      font-size: 28px;
      font-weight: 700;
      color: #1a1a1a;
      margin-bottom: 8px;
      font-family: 'Playfair Display', serif;
    }

    .register-header p {
      color: #999;
      font-size: 14px;
    }

    .back-link {
      display: inline-block;
      margin-bottom: 20px;
      color: #667eea;
      text-decoration: none;
      font-size: 13px;
      transition: color 0.3s ease;
    }

    .back-link:hover {
      color: #764ba2;
    }

    .back-link i {
      margin-right: 5px;
    }

    .form-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
    }

    .form-row.full {
      grid-template-columns: 1fr;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      color: #1a1a1a;
      font-weight: 600;
      font-size: 14px;
    }

    .form-group input {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid #e0e0e0;
      border-radius: 5px;
      font-size: 14px;
      transition: all 0.3s ease;
      font-family: 'Poppins', sans-serif;
    }

    .form-group input:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .password-strength {
      margin-top: 5px;
      height: 4px;
      border-radius: 2px;
      background: #e0e0e0;
      overflow: hidden;
      display: none;
    }

    .password-strength-bar {
      height: 100%;
      width: 0;
      background: #ff4757;
      transition: all 0.3s ease;
    }

    .password-strength.show {
      display: block;
    }

    .strength-text {
      font-size: 12px;
      margin-top: 5px;
      display: none;
    }

    .strength-text.show {
      display: block;
    }

    .strength-text.weak {
      color: #ff4757;
    }

    .strength-text.medium {
      color: #ffa502;
    }

    .strength-text.strong {
      color: #2ed573;
    }

    .password-requirements {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 5px;
      margin-top: 10px;
      border: 1px solid #e0e0e0;
    }

    .requirement {
      font-size: 12px;
      color: #999;
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 6px;
    }

    .requirement:last-child {
      margin-bottom: 0;
    }

    .requirement.met {
      color: #2ed573;
    }

    .requirement i {
      font-size: 12px;
      width: 14px;
      text-align: center;
    }

    .terms-checkbox {
      display: flex;
      align-items: flex-start;
      gap: 10px;
      margin-bottom: 25px;
      font-size: 13px;
    }

    .terms-checkbox input[type="checkbox"] {
      margin-top: 3px;
      cursor: pointer;
      width: auto;
    }

    .terms-checkbox label {
      margin: 0;
      cursor: pointer;
      color: #666;
    }

    .terms-checkbox a {
      color: #667eea;
      text-decoration: none;
      transition: color 0.3s ease;
    }

    .terms-checkbox a:hover {
      color: #764ba2;
    }

    .register-btn {
      width: 100%;
      padding: 12px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 5px;
      font-weight: 600;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s ease;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      font-family: 'Poppins', sans-serif;
    }

    .register-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
    }

    .register-btn:active {
      transform: translateY(0);
    }

    .register-btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }

    .auth-footer {
      text-align: center;
      color: #666;
      font-size: 14px;
      margin-top: 20px;
    }

    .auth-footer a {
      color: #667eea;
      text-decoration: none;
      font-weight: 600;
      transition: color 0.3s ease;
    }

    .auth-footer a:hover {
      color: #764ba2;
    }

    .alert {
      padding: 12px 15px;
      border-radius: 5px;
      margin-bottom: 20px;
      font-size: 14px;
    }

    .alert-danger {
      background: rgba(255, 71, 87, 0.1);
      color: #ff4757;
      border: 1px solid rgba(255, 71, 87, 0.2);
    }

    .alert-success {
      background: rgba(46, 213, 115, 0.1);
      color: #2ed573;
      border: 1px solid rgba(46, 213, 115, 0.2);
    }

    @media (max-width: 992px) {
      .register-grid {
        grid-template-columns: 1fr;
        gap: 0;
      }

      .register-image {
        min-height: auto;
        padding: 40px 30px;
      }

      .register-image-content h2 {
        font-size: 24px;
      }

      .register-form {
        padding: 40px 30px;
      }

      .register-header h1 {
        font-size: 24px;
      }
    }

    @media (max-width: 768px) {
      .register-section {
        padding: 20px 15px;
      }

      .register-grid {
        border-radius: 8px;
      }

      .register-image {
        padding: 30px 25px;
      }

      .register-image-content h2 {
        font-size: 22px;
      }

      .register-image-content p {
        font-size: 14px;
      }

      .register-form {
        padding: 30px 25px;
      }

      .register-header h1 {
        font-size: 22px;
      }

      .form-group input {
        padding: 10px 12px;
        font-size: 13px;
      }

      .form-row {
        grid-template-columns: 1fr;
        gap: 0;
      }
    }

    @media (max-width: 480px) {
      .register-section {
        padding: 15px;
      }

      .register-image {
        display: none;
      }

      .register-form {
        padding: 20px 15px;
      }

      .register-header h1 {
        font-size: 20px;
      }

      .form-group input {
        padding: 10px;
        font-size: 12px;
      }

      .register-btn {
        padding: 10px;
        font-size: 12px;
      }

      .form-row {
        gap: 0;
      }

      .terms-checkbox {
        font-size: 12px;
        gap: 8px;
      }
    }
  </style>
</head>

<body>
    <?php include 'header.php'; ?>

  <section class="register-section">
    <div class="register-container">
      <div class="register-grid">
        
        <div class="register-image">
          <div class="register-image-content">
            <h2>Join Zemaraim Today</h2>
            <p>Start Your Real Estate Journey</p>
            <ul class="benefit-list">
              <li><i class="fas fa-star"></i> Exclusive property listings</li>
              <li><i class="fas fa-star"></i> Direct broker connections</li>
              <li><i class="fas fa-star"></i> Expert market insights</li>
              <li><i class="fas fa-star"></i> Personalized recommendations</li>
            </ul>
          </div>
        </div>

        <div class="register-form">
          <a href="index.php" class="back-link">
            <i class="fas fa-arrow-left"></i> Back to Home
          </a>

          <div class="register-header">
            <h1>Create Account</h1>
            <p>Register as a customer</p>
          </div>

          <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
          <?php endif; ?>

          <form method="POST" action="" id="registerForm">
            <div class="form-row">
              <div class="form-group">
                <label for="firstname">First Name</label>
                <input type="text" id="firstname" name="firstname" placeholder="Enter first name" required>
              </div>

              <div class="form-group">
                <label for="lastname">Last Name</label>
                <input type="text" id="lastname" name="lastname" placeholder="Enter last name" required>
              </div>
            </div>

            <div class="form-group">
              <label for="email">Email Address</label>
              <input type="email" id="email" name="email" placeholder="Enter your email" required>
            </div>

            <div class="form-group">
              <label for="phone">Phone Number</label>
              <input type="tel" id="phone" name="phone" placeholder="Enter phone number" required>
            </div>

            <div class="form-group">
              <label for="password">Password</label>
              <input type="password" id="password" name="password" placeholder="Enter password" required onkeyup="checkPasswordStrength(this.value)">
              <div class="password-strength" id="passwordStrength">
                <div class="password-strength-bar" id="strengthBar"></div>
              </div>
              <div class="password-requirements" id="passwordRequirements" style="display: none;">
                <div class="requirement" id="req-length">
                  <i class="fas fa-times-circle" style="color: #ff4757;"></i> At least 8 characters
                </div>
                <div class="requirement" id="req-uppercase">
                  <i class="fas fa-times-circle" style="color: #ff4757;"></i> Uppercase letter
                </div>
                <div class="requirement" id="req-lowercase">
                  <i class="fas fa-times-circle" style="color: #ff4757;"></i> Lowercase letter
                </div>
                <div class="requirement" id="req-number">
                  <i class="fas fa-times-circle" style="color: #ff4757;"></i> Number
                </div>
              </div>
              <div class="strength-text" id="strengthText"></div>
            </div>

            <div class="form-group">
              <label for="confirm_password">Confirm Password</label>
              <input type="password" id="confirm_password" name="confirm_password" placeholder="Re-enter password" required>
            </div>

            <div class="terms-checkbox">
              <input type="checkbox" id="terms" name="terms" required>
              <label for="terms">
                I agree to the <a href="#">Terms and Conditions</a> and <a href="#">Privacy Policy</a>
              </label>
            </div>

            <button type="submit" class="register-btn">Create Account</button>
          </form>

          <div class="auth-footer">
            Already have an account? <a href="login.php">Sign in here</a>
          </div>
        </div>

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

  <script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>
  <script src="assets/js/slick.min.js"></script>
  <script src="assets/js/jquery.magnific-popup.min.js"></script>
  <script src="assets/js/imagesloaded.pkgd.min.js"></script>
  <script src="assets/js/isotope.pkgd.min.js"></script>
  <script src="assets/js/main.js"></script>

  <script>
    function checkPasswordStrength(password) {
      const strengthDiv = document.getElementById('passwordStrength');
      const strengthBar = document.getElementById('strengthBar');
      const strengthText = document.getElementById('strengthText');
      const requirementsDiv = document.getElementById('passwordRequirements');
      
      if (password.length === 0) {
        strengthDiv.classList.remove('show');
        strengthText.classList.remove('show');
        requirementsDiv.style.display = 'none';
        document.getElementById('registerForm').querySelector('button').disabled = true;
        return;
      }

      strengthDiv.classList.add('show');
      strengthText.classList.add('show');
      requirementsDiv.style.display = 'block';

      let strength = 0;
      let allMet = true;

      // Check length
      const lengthReq = document.getElementById('req-length');
      if (password.length >= 8) {
        strength += 25;
        lengthReq.classList.add('met');
        lengthReq.querySelector('i').className = 'fas fa-check-circle';
      } else {
        lengthReq.classList.remove('met');
        lengthReq.querySelector('i').className = 'fas fa-times-circle';
        allMet = false;
      }

      // Check uppercase
      const uppercaseReq = document.getElementById('req-uppercase');
      if (/[A-Z]/.test(password)) {
        strength += 25;
        uppercaseReq.classList.add('met');
        uppercaseReq.querySelector('i').className = 'fas fa-check-circle';
      } else {
        uppercaseReq.classList.remove('met');
        uppercaseReq.querySelector('i').className = 'fas fa-times-circle';
        allMet = false;
      }

      // Check lowercase
      const lowercaseReq = document.getElementById('req-lowercase');
      if (/[a-z]/.test(password)) {
        strength += 25;
        lowercaseReq.classList.add('met');
        lowercaseReq.querySelector('i').className = 'fas fa-check-circle';
      } else {
        lowercaseReq.classList.remove('met');
        lowercaseReq.querySelector('i').className = 'fas fa-times-circle';
        allMet = false;
      }

      // Check number
      const numberReq = document.getElementById('req-number');
      if (/[0-9]/.test(password)) {
        strength += 25;
        numberReq.classList.add('met');
        numberReq.querySelector('i').className = 'fas fa-check-circle';
      } else {
        numberReq.classList.remove('met');
        numberReq.querySelector('i').className = 'fas fa-times-circle';
        allMet = false;
      }

      strengthBar.style.width = strength + '%';
      
      if (strength < 50) {
        strengthBar.style.background = '#ff4757';
        strengthText.className = 'strength-text show weak';
        strengthText.textContent = '✗ Password too weak';
      } else if (strength < 75) {
        strengthBar.style.background = '#ffa502';
        strengthText.className = 'strength-text show medium';
        strengthText.textContent = '○ Medium strength';
      } else {
        strengthBar.style.background = '#2ed573';
        strengthText.className = 'strength-text show strong';
        strengthText.textContent = '✓ Strong password';
      }

      // Update button state
      const confirmPassword = document.getElementById('confirm_password').value;
      const terms = document.getElementById('terms').checked;
      const registerBtn = document.getElementById('registerForm').querySelector('button');
      registerBtn.disabled = !(allMet && password === confirmPassword && terms);
    }

    // Update validation on confirm password change
    document.getElementById('confirm_password').addEventListener('input', function() {
      const password = document.getElementById('password').value;
      const registerBtn = document.getElementById('registerForm').querySelector('button');
      const terms = document.getElementById('terms').checked;
      
      // Check if all requirements met
      let allMet = true;
      if (password.length < 8) allMet = false;
      if (!/[A-Z]/.test(password)) allMet = false;
      if (!/[a-z]/.test(password)) allMet = false;
      if (!/[0-9]/.test(password)) allMet = false;
      
      registerBtn.disabled = !(allMet && password === this.value && terms);
    });

    // Update validation on terms change
    document.getElementById('terms').addEventListener('change', function() {
      const password = document.getElementById('password').value;
      const confirmPassword = document.getElementById('confirm_password').value;
      const registerBtn = document.getElementById('registerForm').querySelector('button');
      
      // Check if all requirements met
      let allMet = true;
      if (password.length < 8) allMet = false;
      if (!/[A-Z]/.test(password)) allMet = false;
      if (!/[a-z]/.test(password)) allMet = false;
      if (!/[0-9]/.test(password)) allMet = false;
      
      registerBtn.disabled = !(allMet && password === confirmPassword && this.checked);
    });

    // Form submission
    document.getElementById('registerForm').addEventListener('submit', function(e) {
      const password = document.getElementById('password').value;
      const confirmPassword = document.getElementById('confirm_password').value;
      
      if (password !== confirmPassword) {
        e.preventDefault();
        alert('Passwords do not match');
        return false;
      }
    });
  </script>
</body>

</html>
<?php include 'footer.php'; ?>