<?php
session_start();
error_reporting(0);
include('includes/config.php');

if (isset($_POST['login'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    // 1. Fetch user by email (Secure Prepared Statement)
    $stmt = $con->prepare("SELECT u.*, v.id as vendor_id, v.status as vendor_status 
                           FROM users u 
                           LEFT JOIN vendors v ON u.id = v.user_id 
                           WHERE u.email = ? AND u.role = 'vendor'");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $stored_password = $row['password'];
        $login_success = false;

        // 2. Verify Password
        if (strlen($stored_password) === 32) {
            // Legacy MD5 Check
            if (md5($password) === $stored_password) {
                $login_success = true;
                // Optional: Upgrade to Bcrypt here if desired
            }
        } else {
            // Modern Bcrypt Check
            if (password_verify($password, $stored_password)) {
                $login_success = true;
            }
        }

        if ($login_success) {
            // 3. Check Vendor Status
            if ($row['vendor_status'] == 'pending') {
                echo "<script>alert('Your vendor application is pending approval.');</script>";
            } elseif ($row['vendor_status'] == 'rejected') {
                echo "<script>alert('Your vendor application was rejected. Please contact support.');</script>";
            } elseif ($row['vendor_status'] == 'suspended') {
                echo "<script>alert('Your vendor account has been suspended. Please contact support.');</script>";
            } elseif ($row['vendor_status'] == 'active') {
                // Include Unified Activity Logger
                include_once('includes/activity_logger.php');

                // Login successful
                $_SESSION['vendor_id'] = $row['vendor_id'];
                $_SESSION['id'] = $row['id']; // Used for logging
                $_SESSION['vendor_user_id'] = $row['id'];
                $_SESSION['vendor_login'] = $row['email'];
                $_SESSION['vendor_username'] = $row['username'];
                $_SESSION['role'] = 'vendor'; // Ensure role is set for admin-security.php

                log_activity("Vendor Login", "Store: " . $row['username'] . " logged in successfully.", "vendor");

                header('location: vendorportal/dashboard.php');
                exit();
            } else {
                // Fallback if status is weird or NULL
                echo "<script>alert('Vendor profile status unknown (Found: " . htmlspecialchars($row['vendor_status']) . "). Please contact support.');</script>";
            }
        } else {
            include_once('includes/activity_logger.php');
            $uip = $_SERVER['REMOTE_ADDR'];
            $details = mysqli_real_escape_string($con, "Failed vendor login for email: " . $email);
            mysqli_query($con, "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) VALUES ('vendor', 0, 'Failed Login', '$details', '$uip')");
            echo "<script>alert('Invalid email or password!');</script>";
        }
    } else {
        include_once('includes/activity_logger.php');
        $uip = $_SERVER['REMOTE_ADDR'];
        $details = mysqli_real_escape_string($con, "Failed vendor login for unrecognized email: " . $email);
        mysqli_query($con, "INSERT INTO admin_activity_log (portal, admin_id, action, details, ip_address) VALUES ('vendor', 0, 'Failed Login', '$details', '$uip')");
        echo "<script>alert('Invalid email or password!');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Vendor Login - Awesome Mall</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }

        .login-card {
            max-width: 450px;
            margin: auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="login-card">
            <div class="card shadow-lg">
                <div class="card-header bg-primary text-white text-center py-4">
                    <h2><i class="fas fa-store me-2"></i>Vendor Login</h2>
                    <p class="mb-0">Access your vendor dashboard</p>
                </div>
                <div class="card-body p-4">
                    <form method="post">
                        <div class="mb-3">
                            <label class="form-label">Email Address</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                <input type="email" name="email" class="form-control" placeholder="your@email.com"
                                    required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Password</label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                <input type="password" name="password" class="form-control" placeholder="••••••••"
                                    required>
                            </div>
                        </div>

                        <button type="submit" name="login" class="btn btn-primary w-100 mb-3">
                            <i class="fas fa-sign-in-alt me-2"></i>Login
                        </button>
                    </form>

                    <hr>

                    <!-- <div class="text-center">
                        <p class="mb-2">Not a vendor yet?</p>
                        <a href="vendor-register.php" class="btn btn-outline-primary">
                            <i class="fas fa-user-plus me-2"></i>Register as Vendor
                        </a>
                    </div> -->

                    <div class="text-center mt-3">
                        <a href="index.php" class="text-muted">Back to Store</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>