<?php
session_start();
require_once 'config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';

if (empty($email) || empty($password)) {
    $_SESSION['login_error'] = 'Please enter both email and password.';
    header('Location: index.php');
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id, name, email, password FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password'])) {
        $_SESSION['login_error'] = 'Invalid email or password.';
        header('Location: index.php');
        exit;
    }

    // No email verification check

    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_name'] = $user['name'];
    $_SESSION['user_email'] = $user['email'];

    if (isset($_POST['remember'])) {
        setcookie('remember_email', $email, time() + 86400 * 30, '/');
    }

    header('Location: dashboard.php');
} catch (PDOException $e) {
    error_log("Login error: " . $e->getMessage());
    $_SESSION['login_error'] = 'An error occurred. Please try again.';
    header('Location: index.php');
}
?>