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

// Include your database connection file
require_once('../_db.php');

// Start the session
session_start();

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    // Get user input
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate user input (add more validation as needed)
    if (empty($username) || empty($password)) {
        $_SESSION['mgs'] = '<div class="alert alert-danger" role="alert">Enter all fields</div>';
        header('Location: index.php');
        exit();
    } else {
        // Perform database query to check user credentials (use prepared statements for security)
        $query = "SELECT userid, email, password FROM admin_login WHERE username = ?";
        $stmt = $conn->prepare($query);

        if ($stmt) {
            $stmt->bind_param("s", $username); // "s" indicates a string parameter
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close(); // Close the statement

            if ($result) {
                // User found, check password
                if (password_verify($password, $result['password'])) {
                    // Password is correct
                    $_SESSION['loginUser'] = true;
                    $_SESSION['email'] = $result['email'];
                    $_SESSION['userid'] = $result['userid'];
                    header('Location: dashboard.php');
                    exit();
                } else {
                    // Incorrect password
                    $_SESSION['mgs'] = '<div class="alert alert-danger" role="alert">Invalid username or password</div>';
                    header('Location: index.php');
                    exit();
                }
            } else {
                // No user found with the given username
                $_SESSION['mgs'] = '<div class="alert alert-danger" role="alert">Invalid username or password</div>';
                header('Location: index.php');
                exit();
            }
        } else {
            $_SESSION['mgs'] = '<div class="alert alert-danger" role="alert">Error in database query</div>';
            header('Location: index.php');
            exit();
        }
    }
} else {
    header('Location: manage-blog.php?status=error&message=Invalid request');
    exit();
}
?>
