<?php
/**
 * ============================================================================
 * FILE 1: auth/login.php
 * ============================================================================
 */
?>
<?php
define('AIMS_ACCESS', true);
require_once '../config/config.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: ../dashboard/');
    exit();
}

$pageTitle = 'Login - AIMS';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- Toastify CSS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #059669;
            --primary-dark: #047857;
            --primary-light: #10b981;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .auth-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 450px;
            width: 100%;
            overflow: hidden;
            animation: fadeInUp 0.6s ease;
        }
        
        .auth-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }
        
        .auth-logo {
            font-size: 4rem;
            margin-bottom: 15px;
        }
        
        .auth-body {
            padding: 35px 30px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
            padding: 12px;
            font-weight: 600;
            border-radius: 10px;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(5, 150, 105, 0.3);
        }
        
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6b7280;
            z-index: 10;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <div class="auth-card">
        <div class="auth-header">
            <div class="auth-logo">🌾</div>
            <h1 class="h2 fw-bold">Welcome Back!</h1>
            <p class="mb-0">Agricultural Information & Market Linkage</p>
        </div>
        
        <div class="auth-body">
            <form id="loginForm" novalidate>
                <div class="mb-3">
                    <div class="form-floating">
                        <input type="tel" class="form-control" id="phone" placeholder="Phone Number" required>
                        <label for="phone"><i class="bi bi-phone me-2"></i>Phone Number</label>
                        <div class="invalid-feedback">Please enter a valid phone number</div>
                    </div>
                    <small class="text-muted">Format: 0700000000 or +256700000000</small>
                </div>
                
                <div class="mb-3">
                    <div class="form-floating position-relative">
                        <input type="password" class="form-control" id="password" placeholder="Password" required>
                        <label for="password"><i class="bi bi-lock me-2"></i>Password</label>
                        <i class="bi bi-eye password-toggle" id="togglePassword"></i>
                        <div class="invalid-feedback">Please enter your password</div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="remember">
                        <label class="form-check-label" for="remember">Remember me</label>
                    </div>
                    <a href="forgot-password.php" class="text-decoration-none">Forgot Password?</a>
                </div>
                
                <button type="submit" class="btn btn-primary w-100 mb-3">
                    <i class="bi bi-box-arrow-in-right me-2"></i>Login
                </button>
            </form>
            
            <hr>
            
            <p class="text-center mb-0">
                Don't have an account? <a href="register.php" class="text-decoration-none fw-bold">Register Now</a>
            </p>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Toastify -->
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    
    <script>
        const APP_URL = '<?php echo APP_URL; ?>';
        
        function showToast(message, type = 'info') {
            const colors = {
                success: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
            };
            
            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                style: {
                    background: colors[type],
                    borderRadius: "10px",
                    padding: "15px 20px"
                },
                stopOnFocus: true
            }).showToast();
        }
        
        // Toggle password visibility
        $('#togglePassword').click(function() {
            const input = $('#password');
            const type = input.attr('type') === 'password' ? 'text' : 'password';
            input.attr('type', type);
            $(this).toggleClass('bi-eye bi-eye-slash');
        });
        
        // Login form submit
        $('#loginForm').submit(function(e) {
            e.preventDefault();
            
            if (!this.checkValidity()) {
                e.stopPropagation();
                $(this).addClass('was-validated');
                return;
            }
            
            const btn = $(this).find('button[type="submit"]');
            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Logging in...');
            
            $.ajax({
                url: APP_URL + '/api/auth.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'login',
                    phone: $('#phone').val(),
                    password: $('#password').val()
                },
                success: function(response) {
                    if (response.success) {
                        showToast('Login successful! Redirecting...', 'success');
                        setTimeout(() => {
                            window.location.href = APP_URL + '/dashboard/';
                        }, 1500);
                    } else if (response.requires_verification) {
                        showToast('Please verify your phone number', 'warning');
                        setTimeout(() => {
                            window.location.href = 'verify-otp.php?phone=' + encodeURIComponent($('#phone').val());
                        }, 1500);
                    } else {
                        showToast(response.message || 'Login failed', 'error');
                        btn.prop('disabled', false).html('<i class="bi bi-box-arrow-in-right me-2"></i>Login');
                    }
                },
                error: function(xhr) {
                    console.error(xhr);
                    showToast('Connection error. Please try again.', 'error');
                    btn.prop('disabled', false).html('<i class="bi bi-box-arrow-in-right me-2"></i>Login');
                }
            });
        });
    </script>
</body>
</html>