<?php
// doctor_login.php — themed like committee_login, plaintext password check
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

require 'db.php';
require 'helpers.php';

// Start session
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
        $error = 'Invalid session token.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = (string)($_POST['password'] ?? '');

        $stmt = $mysqli1->prepare("SELECT id, full_name, password_hash, is_active FROM doctors WHERE username = ? LIMIT 1");
        if (!$stmt) {
            $error = 'System error. Please try again later.';
        } else {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $stmt->bind_result($id, $full_name, $stored_plain, $active);

            if ($stmt->fetch() && (int)$active === 1 && hash_equals((string)$stored_plain, $password)) {
                $_SESSION['doctor_id']   = (int)$id;
                $_SESSION['doctor_name'] = $full_name;
                $stmt->close();
                header("Location: medical_list.php");
                exit;
            } else {
                $error = 'Invalid credentials or inactive account.';
            }
            $stmt->close();
        }
    }
}
?>
<!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>
    
    <!-- Font Awesome CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
          integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
          crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Bootstrap Icons Backup -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    
    <style>
      :root {
        --medical-blue: #0ea5e9;
        --medical-teal: #06b6d4;
        --medical-green: #10b981;
        --medical-purple: #8b5cf6;
        --light-bg: #f0f9ff;
        --dark-text: #1e293b;
        --gray-border: #e2e8f0;
        --danger: #ef4444;
        --warning: #f59e0b;
      }

      * {
        font-family: 'Cairo', system-ui, -apple-system, sans-serif !important;
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 50%, #dbeafe 100%);
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 20px;
        position: relative;
        overflow-x: hidden;
      }

      body::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-image: url('data:image/svg+xml,<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M20,20 Q40,5 60,20 T100,20 Q80,35 60,20 T20,20" fill="none" stroke="%230ea5e9" stroke-width="0.5" opacity="0.1"/><circle cx="30" cy="70" r="8" fill="%2306b6d4" opacity="0.1"/><circle cx="70" cy="30" r="6" fill="%238b5cf6" opacity="0.1"/></svg>');
        background-size: 200px;
        opacity: 0.3;
        z-index: -1;
      }

      .login-container {
        width: 100%;
        max-width: 1200px;
        margin: 0 auto;
      }

      .login-card {
        background: white;
        border-radius: 24px;
        box-shadow: 0 20px 60px rgba(14, 165, 233, 0.15), 0 0 0 1px rgba(14, 165, 233, 0.05);
        overflow: hidden;
        display: flex;
        min-height: 700px;
        position: relative;
        border: 1px solid rgba(14, 165, 233, 0.1);
      }

      .login-left {
        flex: 1;
        background: linear-gradient(135deg, var(--medical-blue) 0%, var(--medical-teal) 100%);
        padding: 60px 40px;
        color: white;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
        overflow: hidden;
      }

      .login-left::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -20%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.15) 0%, transparent 70%);
        opacity: 0.4;
      }

      .medical-icon {
        position: absolute;
        font-size: 5rem;
        opacity: 0.1;
        color: white;
        z-index: 1;
      }

      .medical-icon:nth-child(1) { top: 15%; left: 15%; }
      .medical-icon:nth-child(2) { bottom: 20%; right: 20%; }
      .medical-icon:nth-child(3) { top: 40%; right: 10%; }

      .login-right {
        flex: 1.2;
        padding: 60px 50px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        background: white;
      }

      .welcome-text {
        font-size: 2.8rem;
        font-weight: 800;
        line-height: 1.2;
        margin-bottom: 20px;
        position: relative;
        z-index: 2;
      }

      .system-name {
        font-size: 1.5rem;
        font-weight: 600;
        opacity: 0.9;
        margin-bottom: 40px;
        position: relative;
        z-index: 2;
      }

      .features-list {
        list-style: none;
        padding: 0;
        margin-top: 40px;
        position: relative;
        z-index: 2;
      }

      .features-list li {
        margin-bottom: 25px;
        display: flex;
        align-items: center;
        font-size: 1.1rem;
      }

      .features-list li i {
        background: rgba(255, 255, 255, 0.2);
        width: 36px;
        height: 36px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 15px;
        flex-shrink: 0;
      }

      .login-header {
        text-align: center;
        margin-bottom: 40px;
      }

      .doctor-icon {
        width: 100px;
        height: 100px;
        background: linear-gradient(135deg, var(--medical-blue), var(--medical-purple));
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 25px;
        box-shadow: 0 15px 35px rgba(14, 165, 233, 0.3);
        position: relative;
        overflow: hidden;
      }

      .doctor-icon::before {
        content: '';
        position: absolute;
        width: 70%;
        height: 70%;
        border: 3px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
      }

      .doctor-icon i {
        font-size: 3rem;
        color: white;
        z-index: 1;
      }

      .role-badge {
        display: inline-block;
        background: linear-gradient(135deg, var(--medical-green), var(--medical-teal));
        color: white;
        padding: 8px 20px;
        border-radius: 50px;
        font-weight: 700;
        font-size: 1rem;
        margin-bottom: 15px;
        box-shadow: 0 5px 15px rgba(16, 185, 129, 0.3);
      }

      .login-title {
        font-size: 2.2rem;
        font-weight: 800;
        color: var(--medical-blue);
        margin-bottom: 10px;
        background: linear-gradient(135deg, var(--medical-blue), var(--medical-purple));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }

      .login-subtitle {
        color: #64748b;
        font-size: 1.1rem;
        margin-bottom: 30px;
      }

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

      .input-with-icon {
        position: relative;
      }

      .input-icon {
        position: absolute;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
        font-size: 1.2rem;
        z-index: 2;
      }

      .form-control {
        width: 100%;
        height: 60px;
        border-radius: 15px;
        border: 2px solid var(--gray-border);
        padding: 0 20px 0 50px;
        font-size: 1.1rem;
        transition: all 0.3s ease;
        background: #f8fafc;
      }

      .form-control:focus {
        border-color: var(--medical-blue);
        box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.15);
        background: white;
        outline: none;
      }

      .login-btn {
        background: linear-gradient(135deg, var(--medical-blue), var(--medical-teal));
        color: white;
        border: none;
        height: 60px;
        border-radius: 15px;
        font-size: 1.2rem;
        font-weight: 700;
        transition: all 0.3s ease;
        width: 100%;
        margin-top: 10px;
        position: relative;
        overflow: hidden;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .login-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: 0.5s;
      }

      .login-btn:hover::before {
        left: 100%;
      }

      .login-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 15px 35px rgba(14, 165, 233, 0.4);
      }

      .alert-custom {
        border-radius: 12px;
        padding: 15px 20px;
        font-size: 1rem;
        border: none;
        background: #fee2e2;
        color: var(--danger);
        margin-bottom: 25px;
        border-right: 4px solid var(--danger);
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .alert-custom i {
        font-size: 1.2rem;
      }

      .footer-links {
        text-align: center;
        margin-top: 30px;
        color: #64748b;
        font-size: 0.95rem;
      }

      .footer-links a {
        color: var(--medical-blue);
        text-decoration: none;
        font-weight: 600;
        transition: all 0.3s ease;
        border-bottom: 1px dashed transparent;
      }

      .footer-links a:hover {
        color: var(--medical-teal);
        border-bottom-color: var(--medical-teal);
      }

      .password-toggle {
        position: absolute;
        left: 20px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: #94a3b8;
        cursor: pointer;
        z-index: 2;
        padding: 10px;
        font-size: 1.2rem;
      }

      .back-home {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-top: 20px;
        color: var(--medical-blue);
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
      }

      .back-home:hover {
        color: var(--medical-purple);
        transform: translateX(-5px);
      }

      @media (max-width: 992px) {
        .login-card {
          flex-direction: column;
          min-height: auto;
        }
        
        .login-left, .login-right {
          padding: 40px 30px;
        }
        
        .welcome-text {
          font-size: 2.2rem;
        }
        
        .login-title {
          font-size: 1.8rem;
        }
        
        .doctor-icon {
          width: 80px;
          height: 80px;
        }
        
        .doctor-icon i {
          font-size: 2.5rem;
        }
      }

      @media (max-width: 576px) {
        body {
          padding: 15px;
        }
        
        .login-left, .login-right {
          padding: 30px 20px;
        }
        
        .login-title {
          font-size: 1.6rem;
        }
        
        .form-control {
          height: 55px;
        }
        
        .login-btn {
          height: 55px;
        }
      }

      /* Fallback icons if Font Awesome fails */
      .icon-fallback {
        display: none;
      }
      
      .fa-heartbeat:before { content: "❤️"; }
      .fa-stethoscope:before { content: "🩺"; }
      .fa-hospital:before { content: "🏥"; }
      .fa-user-md:before { content: "👨‍⚕️"; }
      .fa-file-medical-alt:before { content: "📋"; }
      .fa-clipboard-check:before { content: "✓"; }
      .fa-shield-alt:before { content: "🛡️"; }
      .fa-lock:before { content: "🔒"; }
      .fa-key:before { content: "🔑"; }
      .fa-eye:before { content: "👁️"; }
      .fa-eye-slash:before { content: "👁️‍🗨️"; }
      .fa-sign-in-alt:before { content: "➡️"; }
      .fa-info-circle:before { content: "ℹ️"; }
      .fa-phone-alt:before { content: "📞"; }
      .fa-arrow-right:before { content: "→"; }
      .fa-exclamation-triangle:before { content: "⚠️"; }
      .fa-exclamation-circle:before { content: "⭕"; }
    </style>
</head>
<body>
<div class="login-container">
  <div class="login-card">
    
    <!-- Left Panel - Medical Welcome Section -->
    <div class="login-left">
      <i class="medical-icon fas fa-heartbeat"></i>
      <i class="medical-icon fas fa-stethoscope"></i>
      <i class="medical-icon fas fa-hospital"></i>
      
      <h1 class="welcome-text">مرحبًا دكتور</h1>
      <p class="system-name">نظام ادارة الخدمات الصحية الإلكتروني</p>
      
      <ul class="features-list">
        <li>
          <i class="fas fa-user-md"></i>
          <span>وصول آمن للملفات الطبية</span>
        </li>
        <li>
          <i class="fas fa-file-medical-alt"></i>
          <span>تسجيل وتعديل بيانات الكشف الطبي بسهولة</span>
        </li>
        <li>
          <i class="fas fa-clipboard-check"></i>
          <span>متابعة الحالات الصحية للطلاب</span>
        </li>
        <li>
          <i class="fas fa-shield-alt"></i>
          <span>حماية كاملة لبيانات المرضى</span>
        </li>
      </ul>
      
      <div style="margin-top: auto; opacity: 0.8; font-size: 0.9rem; position: relative; z-index: 2;">
        <p><i class="fas fa-lock" style="margin-left: 8px;"></i>جميع البيانات محمية وفقًا للقوانين الطبية</p>
      </div>
    </div>
    
    <!-- Right Panel - Doctor Login Form -->
    <div class="login-right">
      <div class="login-header">
        <div class="doctor-icon">
          <i class="fas fa-user-md"></i>
        </div>
        
        <div class="role-badge">
          <i class="fas fa-stethoscope" style="margin-left: 8px;"></i>دخول الأطباء
        </div>
        
        <h2 class="login-title">الكشف الطبي </h2>
        <p class="login-subtitle">الرجاء إدخال بيانات الاعتماد الطبية الخاصة بك</p>
      </div>
      
      <?php if ($error): ?>
        <div class="alert-custom">
          <i class="fas fa-exclamation-triangle"></i>
          <div><?php echo htmlspecialchars($error); ?></div>
        </div>
      <?php endif; ?>

      <form method="post" autocomplete="off">
        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        
        <div class="form-group">
          <div class="input-with-icon">
            <i class="input-icon fas fa-user-md"></i>
            <input type="text"
                   class="form-control"
                   id="username" name="username"
                   placeholder="اسم المستخدم الطبي"
                   required
                   autocomplete="off" dir="ltr">
          </div>
        </div>
        
        <div class="form-group">
          <div class="input-with-icon">
            <i class="input-icon fas fa-key"></i>
            <button type="button" class="password-toggle" id="togglePassword">
              <i class="fas fa-eye"></i>
            </button>
            <input type="password"
                   class="form-control"
                   id="password" name="password"
                   placeholder="كلمة المرور الخاصة"
                   required
                   autocomplete="off" dir="ltr">
          </div>
        </div>
        
        <button class="login-btn" type="submit">
          <i class="fas fa-sign-in-alt" style="margin-left: 8px;"></i>
          دخول إلى النظام الطبي
        </button>
        
        <div class="footer-links">
          <p class="mb-2">
            <i class="fas fa-info-circle" style="margin-left: 8px;"></i>
            للمساعدة التقنية، الرجاء الاتصال بقسم الدعم الطبي
          </p>
          <p class="mb-0">
            <i class="fas fa-phone-alt" style="margin-left: 8px;"></i>
            هاتف الدعم: 7777-33-0128
          </p>
          
          <a href="index.php" class="back-home">
            <i class="fas fa-arrow-right" style="margin-left: 8px;"></i>
            العودة إلى الصفحة الرئيسية
          </a>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
  // Check if Font Awesome loaded
  function checkFontAwesomeLoaded() {
    const testIcon = document.createElement('i');
    testIcon.className = 'fas fa-heartbeat';
    testIcon.style.position = 'absolute';
    testIcon.style.left = '-9999px';
    document.body.appendChild(testIcon);
    
    setTimeout(() => {
      const computedStyle = window.getComputedStyle(testIcon, ':before');
      const content = computedStyle.content;
      
      // If Font Awesome not loaded, show fallback
      if (content === 'none' || content === '' || content === 'normal') {
        console.log('Font Awesome not loaded, using fallback icons');
        document.querySelectorAll('i.fas, i.far, i.fab').forEach(icon => {
          icon.classList.add('icon-fallback');
          icon.style.fontFamily = 'Arial, sans-serif';
        });
      }
      document.body.removeChild(testIcon);
    }, 100);
  }
  
  // Password visibility toggle
  document.getElementById('togglePassword').addEventListener('click', function() {
    const passwordInput = document.getElementById('password');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
      passwordInput.type = 'text';
      icon.classList.remove('fa-eye');
      icon.classList.add('fa-eye-slash');
    } else {
      passwordInput.type = 'password';
      icon.classList.remove('fa-eye-slash');
      icon.classList.add('fa-eye');
    }
  });
  
  // Add focus effects to inputs
  const inputs = document.querySelectorAll('.form-control');
  inputs.forEach(input => {
    input.addEventListener('focus', function() {
      this.parentElement.querySelector('.input-icon').style.color = '#0ea5e9';
    });
    
    input.addEventListener('blur', function() {
      this.parentElement.querySelector('.input-icon').style.color = '#94a3b8';
    });
  });
  
  // Form validation
  document.querySelector('form').addEventListener('submit', function(e) {
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value;
    
    if (!username || !password) {
      e.preventDefault();
      const alertDiv = document.createElement('div');
      alertDiv.className = 'alert-custom';
      alertDiv.innerHTML = `
        <i class="fas fa-exclamation-circle"></i>
        <div>الرجاء ملء جميع الحقول المطلوبة</div>
      `;
      
      const existingAlert = document.querySelector('.alert-custom');
      if (existingAlert) {
        existingAlert.replaceWith(alertDiv);
      } else {
        document.querySelector('.login-header').after(alertDiv);
      }
      
      // Scroll to alert
      alertDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
  
  // Load Font Awesome check on page load
  window.addEventListener('load', function() {
    checkFontAwesomeLoaded();
    
    // Add pulsing animation to login button
    const loginBtn = document.querySelector('.login-btn');
    setTimeout(() => {
      loginBtn.style.transform = 'translateY(-3px)';
      loginBtn.style.boxShadow = '0 20px 40px rgba(14, 165, 233, 0.4)';
      
      setTimeout(() => {
        loginBtn.style.transform = 'translateY(0)';
        loginBtn.style.boxShadow = '0 10px 25px rgba(14, 165, 233, 0.3)';
      }, 1000);
    }, 500);
  });
  
  // Fallback for older browsers
  if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
      'use strict';
      if (typeof start !== 'number') {
        start = 0;
      }
      if (start + search.length > this.length) {
        return false;
      } else {
        return this.indexOf(search, start) !== -1;
      }
    };
  }
</script>

<!-- Local fallback for Font Awesome if CDN fails -->
<script>
(function() {
  // Try to load Font Awesome from CDN, fallback to local if needed
  var fontAwesomeLoaded = false;
  
  // Check if Font Awesome is loaded by testing an icon
  var testIcon = document.createElement('i');
  testIcon.className = 'fa fa-heart';
  testIcon.style.visibility = 'hidden';
  document.body.appendChild(testIcon);
  
  setTimeout(function() {
    var style = window.getComputedStyle(testIcon, ':before');
    var content = style.getPropertyValue('content');
    
    // If Font Awesome not loaded, try Bootstrap Icons
    if (content === 'none' || content === '' || content === 'normal') {
      console.log('Loading Bootstrap icons as fallback');
      
      // Create a backup link for Bootstrap icons
      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css';
      document.head.appendChild(link);
      
      // Replace Font Awesome classes with Bootstrap
      setTimeout(function() {
        document.querySelectorAll('.fa').forEach(function(icon) {
          var faClass = Array.from(icon.classList).find(function(c) {
            return c.startsWith('fa-');
          });
          
          if (faClass) {
            var iconName = faClass.replace('fa-', '');
            var biMap = {
              'heartbeat': 'heart-pulse',
              'stethoscope': 'activity',
              'hospital': 'hospital',
              'user-md': 'person-badge',
              'file-medical-alt': 'file-medical',
              'clipboard-check': 'clipboard-check',
              'shield-alt': 'shield-check',
              'lock': 'lock',
              'key': 'key',
              'eye': 'eye',
              'eye-slash': 'eye-slash',
              'sign-in-alt': 'box-arrow-in-right',
              'info-circle': 'info-circle',
              'phone-alt': 'telephone',
              'arrow-right': 'arrow-right',
              'exclamation-triangle': 'exclamation-triangle',
              'exclamation-circle': 'exclamation-circle'
            };
            
            if (biMap[iconName]) {
              icon.classList.remove('fa', faClass);
              icon.classList.add('bi', 'bi-' + biMap[iconName]);
            }
          }
        });
      }, 500);
    }
    
    document.body.removeChild(testIcon);
  }, 2000);
})();
</script>

</body>
</html>