<?php
require 'cors.php'; 
include 'connection.php';  // Ensure you include your database connection
require 'vendor/autoload.php'; // Load Composer dependencies

use \Firebase\JWT\JWT; 

$secret_key = "1ED495A77B65435D317B3E6582E4C"; // Replace with your secret key
$issuer = "http://kaninfotech.in"; // Your domain or issuer
$audience = "http://xesstechlink.com"; // Your audience or client

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Read JSON input from request body
    $input = json_decode(file_get_contents('php://input'), true);

    // Retrieve mobile and password from the request
    $companyId = isset($input['companyId']) ? $input['companyId'] : '';
    $username = isset($input['username']) ? $input['username'] : '';
    $password = isset($input['password']) ? $input['password'] : '';
    
    error_log("Received username: $username");
    error_log("Received password: $password");
    error_log("Received companyId: $companyId");

    if (empty($username) || empty($password)) {
        echo json_encode(array('status' => 'error', 'message' => 'User Name and Password are required'));
        exit;
    }

    // Prepare and execute the SQL query for staff
    $stmt = $conn->prepare("SELECT uid, user_type, name, permissions FROM staff WHERE user_name = ? AND password = ? AND com_id = ?");
    $stmt->bind_param('ssi', $username, $password, $companyId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Fetch the user data
        $user = $result->fetch_assoc();
        $uid = $user['uid'];
        $user_type = $user['user_type'];
        $user_name = $username;
        $name = $user['name'];
        $permissions = ($user_type === 'normal') ? $user['permissions'] : null;

        // ✅ Fetch company name from the company table using companyId
        $companyName = "";
        $companyStmt = $conn->prepare("SELECT com_name FROM company WHERE com_id = ?");
        $companyStmt->bind_param('i', $companyId);
        $companyStmt->execute();
        $companyResult = $companyStmt->get_result();

        if ($companyResult->num_rows > 0) {
            $companyRow = $companyResult->fetch_assoc();
            $companyName = $companyRow['com_name'];
        } else {
            $companyName = "Unknown Company"; // fallback if not found
        }
        $companyStmt->close();

        // Create the token payload
        $payload = array(
            "iss" => $issuer,
            "aud" => $audience,
            "iat" => time(),
            "exp" => time() + (3600 * 12), // Token expires in 12 hours
            "data" => array(
                "companyId" => $companyId,
                "uid" => $uid,
                "user_type" => $user_type,
                "user_name" => $name,
                "com_name" => $companyName, // ✅ Replaced with company table name
                "permissions" => $permissions // Add permissions to the payload
            )
        );

        // Encode the payload to generate JWT
        $jwt = JWT::encode($payload, $secret_key, 'HS256');

        echo json_encode(array(
            'status' => 'success', 
            'token' => $jwt,
            "uid" => $uid,
            "com_name" => $companyName, // ✅ Also reflect correct company name in response
            "user_name" => $user_name,
            "password" => $password,
            'permissions' => $permissions // Include permissions in the response
        ));
    } else {
        echo json_encode(array('status' => 'error', 'message' => 'Invalid username or password'));
    }

    $stmt->close();
} else {
    // If request method is not POST
    echo json_encode(array('status' => 'error', 'message' => 'Invalid request method'));
}

$conn->close();
?>
