<?php
ob_start();
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Database connection
$conn = new mysqli("localhost", "gobolcha_gobolchain", "@Jibala1997", "gobolcha_gobolchain");
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// Get email and password from form
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

if (empty($email) || empty($password)) {
    echo "Email and password are required.";
    exit();
}

// Query to fetch user (including status for freeze check)
$stmt = $conn->prepare("SELECT id, email, password, first_name, status FROM users WHERE email = ?");
if ($stmt === false) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param("s", $email);
$stmt->execute();

// Bind result variables (alternative to get_result())
$stmt->bind_result($id, $db_email, $db_password, $first_name, $status);

// Fetch the data
if (!$stmt->fetch()) {
    echo "Invalid email or password.";
    exit();
}

$stmt->close();

// Check if account is frozen
if (isset($status) && $status === 'frozen') {
    $_SESSION['login_error'] = '⚠️ Your account has been frozen by the administrator. Please contact support.';
    header('Location: login.html');
    exit();
}

// Verify password
if (password_verify($password, $db_password)) {
    $_SESSION['user_id'] = $id;
    $_SESSION['email'] = $db_email;
    $_SESSION['firstName'] = $first_name;

    header("Location: mining.php");
    exit();
} else {
    echo "Invalid email or password.";
    exit();
}

ob_end_flush();
?>