<?php
// Database connection
include "db_connection.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // User details
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Check if the username exists
    $stmt = $conn->prepare("SELECT id, password, profile_picture FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        // Fetch the user data (id, password, profile_picture)
        $stmt->bind_result($user_id, $hashed_password, $profile_picture);
        $stmt->fetch();

        // Verify the password
        if (password_verify($password, $hashed_password)) {
            // Successful login
            session_start();
            $_SESSION['user_id'] = $user_id;  // Store user ID in the session
            $_SESSION['username'] = $username;
            $_SESSION['profile_picture'] = $profile_picture;

            // Redirect to the dashboard or main page
            header("Location: index.php");
            exit();
        } else {
            // Invalid password
            echo "<script>alert('Incorrect password. Please try again.');</script>";
            echo "<script>window.location.href = '../html/login.html';</script>";
        }
    } else {
        // Username does not exist
        echo "<script>alert('Invalid username. Please register or try again.');</script>";
        echo "<script>window.location.href = '../html/login.html';</script>";
    }
    // After verifying user credentials
    $stmt = $conn->prepare("SELECT password, is_admin FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($haashed_password, $is_admin);
        $stmt->fetch();

        if (password_verify($password, $hashed_password)) {
            // Successful login
            session_start();
            $_SESSION['username'] = $username;
            $_SESSION['is_admin'] = $is_admin; // Store admin status

            // Redirect to appropriate page
            if ($is_admin) {
                header("Location: admin_dashboard.php"); // Admin dashboard
            } else {
                header("Location: user_dashboard.php"); // Regular user dashboard
            }
            exit();
        } else {
            echo "<script>alert('Incorrect password. Please try again.');</script>";
            echo "<script>window.location.href = 'login.html';</script>";
        }
    }

    $stmt->close();
}
$conn->close();
?>