<?php
/**
 * Parent Login - Fixed Version
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config/database.php';

$error = '';
$success = '';

// Check if user just logged out
if (isset($_GET['logout']) && $_GET['logout'] === 'success') {
    $success = '✅ সফলভাবে লগআউট হয়েছে!';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Simple validation
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = '❌ ইউজারনেম এবং পাসওয়ার্ড প্রয়োজন!';
    } else {
        try {
            // Check if user exists and is a parent
            $stmt = $pdo->prepare("
                SELECT u.*, p.id as parent_id, p.father_name, p.father_phone 
                FROM users u 
                JOIN parents p ON u.id = p.user_id 
                WHERE u.username = ? AND u.role = 'parent' AND u.status = 'active'
            ");
            $stmt->execute([$username]);
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['password'])) {
                // Start session if not already started
                if (session_status() === PHP_SESSION_NONE) {
                    session_start();
                }
                
                // Set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['parent_id'] = $user['parent_id'];
                $_SESSION['role'] = 'parent';
                $_SESSION['user_role'] = 'parent';
                $_SESSION['username'] = $user['username'];
                $_SESSION['name'] = $user['father_name'];
                
                // Log successful login
                $stmt = $pdo->prepare("
                    INSERT INTO login_attempts (username, ip_address, user_agent, attempt_status) 
                    VALUES (?, ?, ?, 'success')
                ");
                $stmt->execute([$username, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
                
                // Use relative path to avoid URL calculation issues
                header('Location: parent_portal/index.php');
                exit;
            } else {
                $error = '❌ ভুল ইউজারনেম অথবা পাসওয়ার্ড!';
                
                // Log failed attempt
                $stmt = $pdo->prepare("
                    INSERT INTO login_attempts (username, ip_address, user_agent, attempt_status, failure_reason) 
                    VALUES (?, ?, ?, 'failed', 'Invalid credentials')
                ");
                $stmt->execute([$username, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]);
            }
        } catch(Exception $e) {
            $error = '❌ লগইন ত্রুটি: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অভিভাবক লগইন - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Apply Hind Siliguri font to all elements */
        * {
            font-family: 'Hind Siliguri', sans-serif !important;
        }
        
        /* Font Awesome Icons - Restore Original Font */
        .fas, .far, .fab, .fa,
        .fas::before, .far::before, .fab::before, .fa::before {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900 !important;
        }
        
        .far::before {
            font-weight: 400 !important;
        }
        
        .fab::before {
            font-family: 'Font Awesome 6 Brands', 'Font Awesome 5 Brands', 'FontAwesome' !important;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .login-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .login-form {
            padding: 40px;
        }
        .form-control {
            border-radius: 10px;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-login {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 600;
        }
        .parent-icon {
            font-size: 60px;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-5">
                <div class="login-card">
                    <div class="login-header">
                        <i class="fas fa-user-tie parent-icon"></i>
                        <h3 class="mb-2">অভিভাবক পোর্টাল</h3>
                        <p class="mb-0">আপনার সন্তানের তথ্য দেখতে লগইন করুন</p>
                    </div>
                    
                    <div class="login-form">
                        <?php if ($error): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <div class="mb-3">
                                <label class="form-label">ইউজারনেম</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                    <input type="text" name="username" class="form-control" placeholder="আপনার ইউজারনেম" value="<?= htmlspecialchars($username ?? '') ?>" required>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">পাসওয়ার্ড</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>
                            
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" id="remember">
                                <label class="form-check-label" for="remember">মনে রাখুন</label>
                            </div>
                            
                            <button type="submit" class="btn btn-login btn-primary w-100 mb-3">
                                <i class="fas fa-sign-in-alt"></i> লগইন করুন
                            </button>
                            
                            <div class="text-center">
                                <a href="forgot_password.php" class="text-decoration-none">পাসওয়ার্ড ভুলে গেছেন?</a>
                            </div>
                            
                            <hr class="my-4">
                            
                            <div class="text-center">
                                <p class="mb-2">একাউন্ট নেই?</p>
                                <a href="parent_register.php" class="btn btn-outline-primary w-100">
                                    <i class="fas fa-user-plus"></i> নিবন্ধন করুন
                                </a>
                            </div>
                            
                            <div class="text-center mt-3">
                                <a href="index.php" class="text-decoration-none text-muted">
                                    <i class="fas fa-arrow-left"></i> মূল পেজে ফিরে যান
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="text-center text-white mt-3">
                    <small>&copy; <?= date('Y') ?> <?= APP_NAME ?>. সর্বস্বত্ব সংরক্ষিত।</small>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>