<?php
session_start();
require 'db_config.php';

$username = $_POST['username'];
$password = $_POST['password'];

// Check in the admin table first
$stmt = $conn->prepare("SELECT id, password FROM admin WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if (password_verify($password, $row['password'])) {
        // Admin login successful
        $_SESSION['admin_id'] = $row['id'];
        $_SESSION['user_type'] = 'admin'; // Store user type
        header("Location: dashboard.php");
        exit();
    } else {
        echo "Invalid username or password.";
    }
} else {
    // If not found in admin, check in sub_user table
    $stmt = $conn->prepare("SELECT id, password FROM sub_user WHERE email = ?");
    $stmt->bind_param("s", $username); // Assume username for sub_user is their email
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if (password_verify($password, $row['password'])) {
            // Sub-user login successful
            $_SESSION['sub_user_id'] = $row['id'];
            $_SESSION['user_type'] = 'sub_user'; // Store user type
            header("Location: sub_dashboard.php"); // Redirect to sub-user dashboard
            exit();
        } else {
            echo "Invalid username or password.";
        }
    } else {
        echo "Invalid username or password.";
    }
}

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