<?php
// Login page for CentraMEDKIT

// Include database configuration
require_once '../../../../Config/db.php';

// Check if database setup is required
checkDatabaseSetup();

// Include logging utility
require_once '../../../lib/logging.php';

// Include mail helper
require_once '../../../lib/mail_helper.php';

// Start session
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Password reset rate limiting helper
if (!function_exists('checkPasswordResetRateLimit')) {
    function checkPasswordResetRateLimit($pdo, $email) {
        $email = trim(strtolower($email));
        $now = time();

        // Count in the last 1 hour
        $stmt = $pdo->prepare("SELECT created_at FROM password_resets WHERE email = ? ORDER BY created_at DESC LIMIT 4");
        $stmt->execute([$email]);
        $rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (count($rows) >= 4) {
            $fourth = $rows[count($rows)-1]; // 4th latest
            $retry_at = strtotime($fourth) + 3600;
            $retry_after = $retry_at - $now;
            if ($retry_after > 0) {
                return ['allowed' => false, 'reason' => 'hourly_limit', 'retry_after' => $retry_after];
            }
        }

        // Count in the last 24 hours
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM password_resets WHERE email = ? AND created_at >= (NOW() - INTERVAL 24 HOUR)");
        $stmt->execute([$email]);
        $count24 = (int)$stmt->fetchColumn();
        if ($count24 >= 8) {
            // get latest attempt time
            $stmt = $pdo->prepare("SELECT MAX(created_at) FROM password_resets WHERE email = ?");
            $stmt->execute([$email]);
            $latest = $stmt->fetchColumn();
            $block_until = strtotime($latest) + 6 * 3600; // 6 hours after latest
            $retry_after = $block_until - $now;
            if ($retry_after > 0) {
                return ['allowed' => false, 'reason' => 'daily_block', 'retry_after' => $retry_after];
            }
        }

        return ['allowed' => true];
    }
}

// Handle login form submission
$message = '';
$message_type = 'error'; // Default to error

// Check for logout success parameter
if (isset($_GET['logout']) && $_GET['logout'] === 'success') {
    $message = "You have been successfully logged out.";
    $message_type = 'success';
}

// Check for password reset success parameter
if (isset($_GET['reset']) && $_GET['reset'] === 'success' && isset($_SESSION['reset_success'])) {
    $message = $_SESSION['reset_success'];
    $message_type = 'success';
    unset($_SESSION['reset_success']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email_or_username = trim($_POST['email_or_username'] ?? '');
    $password = $_POST['password'] ?? '';

    // Validate input
    if (empty($email_or_username)) {
        $message = "Please enter your email or username.";
    } elseif (empty($password)) {
        $message = "Please enter your password.";
    } elseif (strlen($password) < 6) {
        $message = "Password must be at least 6 characters long.";
    } else {
        try {
            // Check if input is email or username
            $field = filter_var($email_or_username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

            $stmt = $pdo->prepare("SELECT id, email, username, password, role, company_id, is_active FROM users WHERE $field = ?");
            $stmt->execute([$email_or_username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                $message = "Your login credentials are wrong, check and retry again.";
                logAuthEvent('Failed Login', "Invalid credentials for: $email_or_username", null);
            } elseif (!$user['is_active']) {
                $message = "Your account has been deactivated. Please contact your administrator.";
                logAuthEvent('Failed Login', "Attempted login to deactivated account: $email_or_username", $user['id']);
            } elseif (!password_verify($password, $user['password'])) {
                // Check if password is stored in plain text (for backward compatibility)
                if ($password === $user['password']) {
                    // Password is plain text, hash it and update in database
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $update_stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $update_stmt->execute([$hashed_password, $user['id']]);
                    // Now proceed with login
                } else {
                    $message = "Your login credentials are wrong, check and retry again.";
                    logAuthEvent('Failed Login', "Incorrect password for: $email_or_username", $user['id']);
                    $user = null; // Prevent login
                }
            }

            if ($user) {
                // Login successful - set session and redirect based on role permissions
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['company_id'] = $user['company_id'];

                logAuthEvent('Successful Login', "User logged in from IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'), $user['id']);

                // Determine redirect based on role and permissions
                $redirectUrl = '/includes/lib/pages/general/dashboard.php?login=success';
                
                if ($user['role'] === 'doctor') {
                    // Check if doctor has access to doctor dashboard
                    try {
                        $roleStmt = $pdo->prepare("SELECT access_doctor_dashboard FROM user_roles WHERE name = ? AND company_id = ? LIMIT 1");
                        $roleStmt->execute([$user['role'], $user['company_id']]);
                        $rolePerms = $roleStmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($rolePerms && $rolePerms['access_doctor_dashboard']) {
                            $redirectUrl = '/includes/lib/pages/doctor/dashboard.php?login=success';
                        }
                    } catch (Exception $e) {
                        // Fallback to doctor dashboard if no custom role found
                        $redirectUrl = '/includes/lib/pages/doctor/dashboard.php?login=success';
                    }
                } else if ($user['role'] === 'admin' || $user['role'] === 'manager') {
                    // Admins and managers go to general dashboard
                    $redirectUrl = '/includes/lib/pages/general/dashboard.php?login=success';
                }
                
                header('Location: ' . $redirectUrl);
                exit;
            }
        } catch (PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $message = "A system error occurred. Please try again later.";
        }
    }
}

// Handle password reset request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reset_password') {
    $reset_email = trim($_POST['reset_email'] ?? '');
    
    // Log password reset attempt
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    error_log("Password reset attempt from IP: $ip_address for email: $reset_email");
    
    if (empty($reset_email)) {
        $message = "Please enter your email address.";
        logAuthEvent('Password Reset Failed', "Empty email provided from IP: $ip_address", null);
    } elseif (!filter_var($reset_email, FILTER_VALIDATE_EMAIL)) {
        $message = "Please enter a valid email address.";
        logAuthEvent('Password Reset Failed', "Invalid email format: $reset_email from IP: $ip_address", null);
    } else {
        try {
            // Check rate limit for this email before proceeding
            $rate = checkPasswordResetRateLimit($pdo, $reset_email);
            if (!$rate['allowed']) {
                if ($rate['reason'] === 'hourly_limit') {
                    $minutes = ceil($rate['retry_after'] / 60);
                    $message = "Too many password reset requests. Please try again in {$minutes} minute(s).";
                } else {
                    $hours = ceil($rate['retry_after'] / 3600);
                    $message = "Too many password reset requests today. Please try again in {$hours} hour(s).";
                }
                $message_type = 'error';
                logAuthEvent('Password Reset Rate Limited', "Rate limited reset for: $reset_email, reason: {$rate['reason']}", null);
            } else {
                // Check if email exists
                $stmt = $pdo->prepare("SELECT id, username, email, company_id FROM users WHERE email = ? AND is_active = 1");
                $stmt->execute([$reset_email]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$user) {
                    // Don't reveal if email exists or not for security
                    $message = "If an account with this email exists, a password reset link has been sent.";
                    $message_type = 'success';
                    logAuthEvent('Password Reset Attempted', "Reset requested for non-existent email: $reset_email from IP: $ip_address", null);
                } else {
                    // Generate reset token
                    $reset_token = bin2hex(random_bytes(32));
                    $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));
                    
                    // Log token generation
                    logAuthEvent('Password Reset Token Generated', "Token generated for user: {$user['username']} (ID: {$user['id']}) from IP: $ip_address, expires at: $expires_at", $user['id']);
                
                // Store reset token
                $stmt = $pdo->prepare("INSERT INTO password_resets (user_id, email, token, expires_at, created_at) VALUES (?, ?, ?, ?, NOW())");
                $stmt->execute([$user['id'], $reset_email, $reset_token, $expires_at]);
                
                // Get company name for email template
                $company_stmt = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'company_name' AND company_id = ? LIMIT 1");
                $company_stmt->execute([$user['company_id']]);
                $company_name = $company_stmt->fetchColumn() ?: 'CentraMEDKIT';
                
                // Generate reset link
                $reset_link = "http://" . $_SERVER['HTTP_HOST'] . "/includes/lib/pages/auth/reset-password.php?token=" . $reset_token;
                
                // Send password reset email using the template system
                $email_data = [
                    'user_name' => $user['username'],
                    'reset_link' => $reset_link,
                    'expiration_time' => '1 hour',
                    'company_name' => $company_name
                ];
                
                $mailer = new MailService();
                $email_sent = $mailer->sendTemplateEmail($reset_email, 'password_reset_request', $email_data, $user['company_id']);
                
                if ($email_sent) {
                    $message = "If an account with this email exists, a password reset link has been sent.";
                    $message_type = 'success';
                    logAuthEvent('Password Reset Email Sent', "Reset email successfully sent to: $reset_email for user: {$user['username']} (ID: {$user['id']}) from IP: $ip_address", $user['id']);
                    error_log("Password reset email sent successfully to: $reset_email for user ID: {$user['id']}");
                } else {
                    $message = "Failed to send password reset email. Please try again later.";
                    logAuthEvent('Password Reset Email Failed', "Email sending failed for: $reset_email, user: {$user['username']} (ID: {$user['id']}) from IP: $ip_address", $user['id']);
                    error_log("Password reset email sending failed for: $reset_email");
                }
            }
        } catch (PDOException $e) {
            error_log("Password reset error: " . $e->getMessage());
            logAuthEvent('Password Reset System Error', "Database error during password reset for email: $reset_email from IP: $ip_address. Error: " . $e->getMessage(), null);
            $message = "A system error occurred. Please try again later.";
        }
    }
}

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    $role = $_SESSION['role'] ?? 'staff';
    $redirectUrl = $role === 'doctor' 
        ? '/includes/lib/pages/doctor/dashboard.php'
        : '/includes/lib/pages/general/dashboard.php';
    header('Location: ' . $redirectUrl);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CentraMEDKIT - Login</title>
    <link rel="stylesheet" href="../../../../assets/css/login.css">
    <link rel="icon" href="/assets/image/icon/medicine.jpg">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
    <!-- Database Connection Indicator -->
    <div class="db-status-indicator connected" id="dbStatusIndicator">
        <div class="db-icon">🗄️</div>
        <span class="db-status-text">DB Connected</span>
    </div>

    <div class="container">
        <img src="../../../../assets/image/icon/medicine.jpg" alt="CentraMEDKIT Icon" style="width: 50px; height: 50px; border-radius: 50%; display: block; margin: 0 auto 10px;">
        <h1>CentraMEDKIT</h1>
        <p class="subtitle">Welcome back! Please sign in to your account.</p>

        <?php if ($message): ?>
            <div class="message <?php echo $message_type; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <form method="POST" id="loginForm">
            <div class="form-group">
                <label for="email_or_username">Email or Username</label>
                <input type="text" id="email_or_username" name="email_or_username" placeholder="Enter your email or username" required>
            </div>

            <div class="form-group">
                <label for="password">Password</label>
                <div style="position: relative;">
                    <input type="password" id="password" name="password" placeholder="Enter your password" autocomplete="current-password" required>
                    <button type="button" class="password-toggle" data-target="password">👁️</button>
                </div>
            </div>

            <button type="submit" id="loginBtn">Sign In</button>
        </form>

        <div class="forgot-password">
            <a href="reset-password.php" id="forgotPasswordLink">Forgot your password?</a>
        </div>

        <!-- Password Reset Form -->
        <div id="resetForm" style="display: none;">
            <h2>Reset Your Password</h2>
            <p class="subtitle">Enter your email address and we'll send you a link to reset your password.</p>
            
            <form method="POST" id="passwordResetForm">
                <input type="hidden" name="action" value="reset_password">
                <div class="form-group">
                    <label for="reset_email">Email Address</label>
                    <input type="email" id="reset_email" name="reset_email" placeholder="Enter your email address" required>
                </div>
                
                <button type="submit" id="resetBtn">Send Reset Link</button>
            </form>
            
            <div class="back-to-login">
                <a href="#" id="backToLoginLink">← Back to Login</a>
            </div>
        </div>

        <div class="legal-links">
            <a href="/legal/privacy_policy.php" target="_blank">Privacy Policy</a> | <a href="/legal/terms_and_conditions.php" target="_blank">Terms and Conditions</a>
        </div>


    </div>

    <script src="../../../../assets/js/install.js"></script>
    <script>
        // Database Connection Status Check
        (function() {
            const dbIndicator = document.getElementById('dbStatusIndicator');
            const dbIcon = dbIndicator.querySelector('.db-icon');
            const dbText = dbIndicator.querySelector('.db-status-text');
            
            // Check if database connection exists from PHP
            <?php
            try {
                // Test database connection
                $testConnection = $pdo->query("SELECT 1");
                echo "const dbConnected = true;";
            } catch (PDOException $e) {
                echo "const dbConnected = false;";
            }
            ?>
            
            if (dbConnected) {
                dbIndicator.classList.add('connected');
                dbIndicator.classList.remove('disconnected');
                dbText.textContent = 'DB Connected';
            } else {
                dbIndicator.classList.add('disconnected');
                dbIndicator.classList.remove('connected');
                dbText.textContent = 'DB Disconnected';
            }
        })();

        // Enhanced JavaScript for login
        document.addEventListener('DOMContentLoaded', function() {
            // Password toggle functionality
            const passwordToggles = document.querySelectorAll('.password-toggle');
            passwordToggles.forEach(toggle => {
                toggle.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    const targetInput = document.getElementById(targetId);
                    
                    if (targetInput.type === 'password') {
                        targetInput.type = 'text';
                        this.textContent = '🙈';
                    } else {
                        targetInput.type = 'password';
                        this.textContent = '👁️';
                    }
                });
            });

            // Form submission
            document.getElementById('loginForm').addEventListener('submit', function(e) {
                const btn = document.getElementById('loginBtn');
                btn.classList.add('loading');
                btn.textContent = 'Signing In...';
            });

            // Password reset form submission
            document.getElementById('passwordResetForm').addEventListener('submit', function(e) {
                const btn = document.getElementById('resetBtn');
                btn.classList.add('loading');
                btn.textContent = 'Sending...';
            });

            // Toggle between login and reset forms
            document.getElementById('forgotPasswordLink').addEventListener('click', function(e) {
                var href = this.getAttribute('href');
                // Only intercept if link points to '#' (inline reset form)
                if (!href || href === '#') {
                    e.preventDefault();
                    document.getElementById('loginForm').parentElement.style.display = 'none';
                    document.querySelector('.subtitle').style.display = 'none';
                    document.getElementById('resetForm').style.display = 'block';
                    document.querySelector('h1').textContent = 'Password Reset';
                }
                // otherwise let the browser navigate to the reset page
            });

            document.getElementById('backToLoginLink').addEventListener('click', function(e) {
                e.preventDefault();
                document.getElementById('resetForm').style.display = 'none';
                document.getElementById('loginForm').parentElement.style.display = 'block';
                document.querySelector('.subtitle').style.display = 'block';
                document.querySelector('h1').textContent = 'CentraMEDKIT';
            });

            // Auto-hide message after 3 seconds
            const messageElement = document.querySelector('.message');
            if (messageElement) {
                setTimeout(function() {
                    messageElement.style.animation = 'slideUp 0.3s ease-in forwards';
                    setTimeout(function() {
                        messageElement.style.display = 'none';
                    }, 300);
                }, 3000);
            }
        });
    </script>
</body>
</html>