<?php
/**
 * Role-Based Login System (Super Admin, Provider, Customer)
 * ShivSahodar Dairy Marketplace (AASHA ENTERPRISE)
 */

declare(strict_types=1);
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/auth/auth_helper.php';

$error_message = '';
$selected_role = $_GET['role'] ?? 'CUSTOMER';

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $role = $_POST['role'] ?? 'CUSTOMER';
    $identifier = trim($_POST['identifier'] ?? ''); // email or phone
    $password = $_POST['password'] ?? '';
    $csrf = $_POST['csrf_token'] ?? '';

    if (!verify_csrf($csrf)) {
        $error_message = 'Security validation failed (Invalid CSRF token). Please retry.';
    } elseif (empty($identifier) || empty($password)) {
        $error_message = 'Please provide your email/phone and password.';
    } else {
        try {
            $pdo = Database::getConnection();
            $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

            // BRUTE-FORCE PROTECTION: Check failed attempts in past 15 minutes
            $lockStmt = $pdo->prepare("SELECT COUNT(*) as failed_count FROM login_attempts WHERE ip_address = :ip AND attempt_time > (NOW() - INTERVAL '15 minutes')");
            $lockStmt->execute(['ip' => $ip]);
            $failed_attempts = (int) ($lockStmt->fetch()['failed_count'] ?? 0);

            if ($failed_attempts >= 5) {
                $error_message = 'Security Lockout: Too many failed login attempts from your IP. Please try again after 15 minutes.';
            } else {
                // Lookup user by email OR phone AND matching role
                $stmt = $pdo->prepare("SELECT * FROM users WHERE (email = :id1 OR phone = :id2) AND role = :role LIMIT 1");
                $stmt->execute([
                    'id1'  => $identifier,
                    'id2'  => $identifier,
                    'role' => $role
                ]);
                $user = $stmt->fetch();

                if ($user && password_verify($password, $user['password_hash'])) {
                    if ($user['status'] === 'SUSPENDED') {
                        $error_message = 'Your account has been suspended. Please contact AASHA ENTERPRISE support.';
                    } else {
                        // Clear past failed attempts for this IP
                        $clearStmt = $pdo->prepare("DELETE FROM login_attempts WHERE ip_address = :ip");
                        $clearStmt->execute(['ip' => $ip]);

                        // Prevent Session Fixation
                        session_regenerate_id(true);

                        $_SESSION['user_id']    = (int) $user['id'];
                        $_SESSION['user_name']  = $user['name'];
                        $_SESSION['user_email'] = $user['email'];
                        $_SESSION['user_role']  = $user['role'];

                        // If Provider, store provider_id for ownership validation
                        if ($user['role'] === 'PROVIDER') {
                            $pStmt = $pdo->prepare("SELECT id FROM providers WHERE user_id = :uid LIMIT 1");
                            $pStmt->execute(['uid' => $user['id']]);
                            $prov = $pStmt->fetch();
                            $_SESSION['provider_id'] = $prov ? (int) $prov['id'] : 0;
                        }

                        // Redirect according to role
                        if ($user['role'] === 'SUPER_ADMIN') {
                            header("Location: index.html#view-admin");
                        } elseif ($user['role'] === 'PROVIDER') {
                            header("Location: index.html#view-provider");
                        } else {
                            header("Location: index.html#buyer-dashboard");
                        }
                        exit();
                    }
                } else {
                    // Record failed attempt for brute force tracking
                    $logFail = $pdo->prepare("INSERT INTO login_attempts (ip_address, username) VALUES (:ip, :user)");
                    $logFail->execute(['ip' => $ip, 'user' => $identifier]);

                    $remaining = 5 - ($failed_attempts + 1);
                    $error_message = "Invalid credentials for {$role}. ({$remaining} attempts remaining before temporary lockout).";
                }
            }
        } catch (Exception $e) {
            error_log("Login Exception: " . $e->getMessage());
            $error_message = 'Authentication service temporarily unavailable. Please try again.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login | ShivSahodar Dairy Marketplace</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    .auth-container {
      max-width: 460px;
      margin: 3.5rem auto;
      background: #ffffff;
      border: 1px solid var(--border-subtle);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-md);
      overflow: hidden;
    }
    .auth-header {
      background: var(--bg-surface-alt);
      padding: 1.5rem;
      text-align: center;
      border-bottom: 1px solid var(--border-subtle);
    }
    .auth-role-tabs {
      display: flex;
      background: #e7dfce;
      padding: 0.25rem;
      border-radius: var(--radius-md);
      margin: 1.25rem 1.5rem 0;
    }
    .auth-role-tab {
      flex: 1;
      border: none;
      background: transparent;
      padding: 0.5rem;
      font-size: 0.775rem;
      font-weight: 700;
      border-radius: var(--radius-sm);
      cursor: pointer;
      color: var(--text-muted);
      transition: all 0.2s;
    }
    .auth-role-tab.active {
      background: var(--primary);
      color: #ffffff;
      box-shadow: 0 2px 6px rgba(0,0,0,0.15);
    }
    .auth-body {
      padding: 1.75rem;
    }
    .alert-error {
      background: var(--status-failed-bg);
      color: var(--status-failed);
      padding: 0.75rem 1rem;
      border-radius: var(--radius-md);
      font-size: 0.85rem;
      margin-bottom: 1.25rem;
      border: 1px solid #fecaca;
    }
    .seed-info-box {
      background: #f8fafc;
      border: 1px dashed #cbd5e1;
      border-radius: var(--radius-md);
      padding: 0.85rem;
      font-size: 0.775rem;
      color: #475569;
      margin-top: 1.5rem;
    }
  </style>
</head>
<body>

  <!-- Top Bar -->
  <div class="ecosystem-role-bar">
    <div class="container role-bar-container">
      <div class="role-badge-facilitator">
        <span>Facilitator Platform: <strong>AASHA ENTERPRISE</strong> &bull; Unit: <strong>ShivSahodar Dairy</strong></span>
        <span class="udyam-pill">Udyam: UDYAM-BR-38-0075026</span>
      </div>
      <a href="index.html" style="color: #a7f3d0; font-size: 0.8rem;">← Back to Marketplace</a>
    </div>
  </div>

  <div class="container">
    <div class="auth-container">
      <div class="auth-header">
        <h2 style="font-size: 1.45rem; color: var(--primary-dark);">Sign In to Platform</h2>
        <p style="font-size: 0.85rem; color: var(--text-muted); margin-top: 0.25rem;">
          Role-Based Access for Buyers, Dairy Providers &amp; Admin
        </p>
      </div>

      <!-- Role Selector Tabs -->
      <div class="auth-role-tabs">
        <button type="button" class="auth-role-tab <?= $selected_role === 'CUSTOMER' ? 'active' : '' ?>" onclick="switchTab('CUSTOMER')">
          👤 Customer
        </button>
        <button type="button" class="auth-role-tab <?= $selected_role === 'PROVIDER' ? 'active' : '' ?>" onclick="switchTab('PROVIDER')">
          🏪 Dairy Seller
        </button>
        <button type="button" class="auth-role-tab <?= $selected_role === 'SUPER_ADMIN' ? 'active' : '' ?>" onclick="switchTab('SUPER_ADMIN')">
          👑 Super Admin
        </button>
      </div>

      <div class="auth-body">
        <?php if ($error_message): ?>
          <div class="alert-error">
            ⚠️ <?= htmlspecialchars($error_message) ?>
          </div>
        <?php endif; ?>

        <form method="POST" action="login.php">
          <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">
          <input type="hidden" id="login-role" name="role" value="<?= htmlspecialchars($selected_role) ?>">

          <div class="form-group">
            <label class="form-label" for="identifier">Email Address or Mobile Number *</label>
            <input type="text" id="identifier" name="identifier" class="form-input" placeholder="e.g. 9876543210 or user@example.com" required>
          </div>

          <div class="form-group">
            <label class="form-label" for="password">Account Password *</label>
            <input type="password" id="password" name="password" class="form-input" placeholder="Enter password" required>
          </div>

          <button type="submit" class="btn btn-primary" style="width: 100%; margin-top: 0.5rem;">
            Sign In as <span id="btn-role-label"><?= htmlspecialchars($selected_role) ?></span>
          </button>
        </form>

        <div style="text-align: center; margin-top: 1.25rem; font-size: 0.85rem;">
          Don't have an account? <a href="register.php" style="font-weight: 700;">Register as Customer or Dairy Seller</a>
        </div>

        <!-- Default Credentials helper for cPanel setup testing -->
        <div class="seed-info-box">
          <strong>Default Seed Accounts (from database.sql):</strong><br>
          &bull; <strong>Super Admin:</strong> <code>admin@shivsahodardairy.com</code> / <code>Password@123</code><br>
          &bull; <strong>Provider:</strong> <code>champaran.dairy@gmail.com</code> / <code>Password@123</code><br>
          &bull; <strong>Customer:</strong> <code>9876543210</code> / <code>Password@123</code>
        </div>
      </div>
    </div>
  </div>

  <script>
    function switchTab(role) {
      document.getElementById('login-role').value = role;
      document.getElementById('btn-role-label').innerText = role;
      document.querySelectorAll('.auth-role-tab').forEach(t => t.classList.remove('active'));
      event.target.classList.add('active');

      if (role === 'SUPER_ADMIN') {
        document.getElementById('identifier').placeholder = 'admin@shivsahodardairy.com';
      } else if (role === 'PROVIDER') {
        document.getElementById('identifier').placeholder = 'champaran.dairy@gmail.com';
      } else {
        document.getElementById('identifier').placeholder = '9876543210';
      }
    }
  </script>
</body>
</html>
