<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>تسجيل الدخول - نظام التقييم</title>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" href="unified-style.css">
  <style>
    .login-card {
      max-width: 450px;
      width: 100%;
    }
    .remember-me {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 15px 0;
    }
    .remember-me input[type="checkbox"] {
      width: 18px;
      height: 18px;
      cursor: pointer;
      accent-color: var(--primary);
    }
    .remember-me label {
      font-weight: 500;
      color: var(--text-dark);
      cursor: pointer;
    }
    .login-message {
      padding: 12px 15px;
      border-radius: var(--radius-sm);
      margin-bottom: 15px;
      display: none;
      align-items: center;
      gap: 10px;
      font-weight: 500;
    }
    .login-message.show {
      display: flex;
    }
    .login-message.error {
      background: #f8d7da;
      border: 2px solid #dc3545;
      color: #721c24;
    }
    .login-message.success {
      background: #d4edda;
      border: 2px solid #28a745;
      color: #155724;
    }
    .login-message i {
      font-size: 1.2rem;
    }
    .btn {
      width: 100%;
    }
    .btn:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }
    .form-control.error {
      border-color: #dc3545;
    }
    .form-control.success {
      border-color: #28a745;
    }
  </style>
</head>
<body>
  <header class="program-header">
    <div class="header-content">
      <img src="wezara.png" alt="شعار الوزارة" class="logo-right">
      <div class="title-container">
        <h1 class="program-title">البرنامج القومي لتنمية مهارات اللغة العربية بالحلقة الابتدائية</h1>
      </div>
      <img src="week.png" alt="شعار البرنامج" class="logo-left">
    </div>
  </header>

  <main style="flex:1; display: flex; justify-content: center; align-items: center; padding: 2rem;">
    <div class="login-card">
      <div class="login-header">
        <h2>تسجيل الدخول</h2>
      </div>
      <div class="login-body">
        
        <!-- Messages -->
        <div id="message" class="login-message">
          <i id="messageIcon"></i>
          <span id="messageText"></span>
        </div>

        <form id="loginForm">
          <div class="form-group">
            <label for="national_id">الرقم القومي</label>
            <input type="text" id="national_id" name="national_id" class="form-control" 
                   maxlength="14" pattern="\d{14}" required 
                   placeholder="أدخل 14 رقمًا" 
                   value="<?php echo isset($_COOKIE['remembered_national_id']) ? htmlspecialchars($_COOKIE['remembered_national_id']) : ''; ?>">
          </div>
          
          <div class="remember-me">
            <input type="checkbox" id="remember_me" name="remember_me" 
                   <?php echo isset($_COOKIE['remembered_national_id']) ? 'checked' : ''; ?>>
            <label for="remember_me">تذكرني</label>
          </div>
          
          <button type="submit" class="btn" id="loginBtn">دخول</button>
          
          <div style="text-align: center; margin-top: 1.5rem;">
            <a href="new_register.php" style="color: var(--primary);">إنشاء حساب جديد</a>
          </div>
        </form>
      </div>
    </div>
  </main>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const form = document.getElementById('loginForm');
      const nationalIdInput = document.getElementById('national_id');
      const submitBtn = document.getElementById('loginBtn');
      const messageDiv = document.getElementById('message');
      const messageIcon = document.getElementById('messageIcon');
      const messageText = document.getElementById('messageText');
      
      // Show message function
      function showMessage(message, type) {
        messageDiv.className = 'login-message show ' + type;
        messageIcon.className = type === 'error' ? 'fas fa-exclamation-circle' : 
                                type === 'success' ? 'fas fa-check-circle' : 'fas fa-info-circle';
        messageText.textContent = message;
      }
      
      // Hide message
      function hideMessage() {
        messageDiv.classList.remove('show');
      }
      
      // Validate national ID
      function validateNationalId(value) {
        return /^\d{14}$/.test(value);
      }
      
      // Handle form submission
      form.addEventListener('submit', function(e) {
        e.preventDefault();
        hideMessage();
        
        const nationalId = nationalIdInput.value.trim();
        const rememberMe = document.getElementById('remember_me').checked;
        
        // Validate
        if (!nationalId) {
          showMessage('الرجاء إدخال الرقم القومي', 'error');
          nationalIdInput.focus();
          return;
        }
        
        if (!validateNationalId(nationalId)) {
          showMessage('الرجاء إدخال الرقم القومي بشكل صحيح (14 رقمًا)', 'error');
          nationalIdInput.focus();
          return;
        }
        
        // Show loading state
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جاري التحقق...';
        submitBtn.disabled = true;
        
        // Send AJAX request
        const formData = new FormData();
        formData.append('national_id', nationalId);
        formData.append('remember_me', rememberMe ? '1' : '0');
        
        fetch('new_login_process.php', {
          method: 'POST',
          body: formData
        })
        .then(response => response.json())
        .then(data => {
          if (data.success) {
            showMessage(data.message, 'success');
            // Redirect after short delay
            setTimeout(function() {
              window.location.href = data.redirect;
            }, 1000);
          } else {
            showMessage(data.message, 'error');
            // Reset button
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
            nationalIdInput.focus();
          }
        })
        .catch(error => {
          console.error('Error:', error);
          showMessage('حدث خطأ في الاتصال. يرجى المحاولة مرة أخرى.', 'error');
          // Reset button
          submitBtn.innerHTML = originalText;
          submitBtn.disabled = false;
        });
      });
      
      // Real-time validation
      nationalIdInput.addEventListener('input', function() {
        const value = this.value;
        if (value.length > 0) {
          if (validateNationalId(value)) {
            this.className = 'form-control success';
          } else {
            this.className = 'form-control error';
          }
        } else {
          this.className = 'form-control';
        }
        hideMessage();
      });
      
      // Auto-focus on national ID field
      nationalIdInput.focus();
    });
  </script>
</body>
</html>