<?php
error_log($_SERVER['REQUEST_METHOD']);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');

include 'connection.php';
require 'vendor/autoload.php'; // Load Composer dependencies

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key; 
use \Firebase\JWT\ExpiredException;

$secret_key = "1ED495A77B65435D317B3E6582E4C"; 
$issuer = "http://kaninfotech.in"; 
$audience = "http://xesstechlink.com"; 

if ($conn->connect_error) {
    echo json_encode(["success" => false, "message" => "DB connection failed: " . $conn->connect_error]);
    exit;
}

// ✅ Common: Extract and validate token
function getTokenData($secret_key) {
    $headers = function_exists('apache_request_headers') ? apache_request_headers() : [];
    if (isset($headers['Authorization'])) {
        $authHeader = $headers['Authorization'];
        list($jwt) = sscanf($authHeader, 'Bearer %s');
    } else {
        echo json_encode(["success" => false, "message" => "Authorization header missing"]);
        exit;
    }

    try {
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        return $decoded->data;
    } catch (ExpiredException $e) {
        echo json_encode(["success" => false, "message" => "Token expired"]);
        exit;
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Token error: " . $e->getMessage()]);
        exit;
    }
}

// ✅ POST: Insert new staff
// ✅ POST: Insert new staff
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = getTokenData($secret_key);
    $company_id = $data->companyId;
    $uid = $data->uid;

    $input = json_decode(file_get_contents("php://input"), true);
    if (!$input) $input = $_POST;

    $requiredFields = ['reg_id', 'name', 'user_type', 'user_name', 'password', 'permissions'];
    $missingFields = [];
    foreach ($requiredFields as $field) {
        if (!isset($input[$field]) || $input[$field] === '') {
            $missingFields[] = $field;
        }
    }
    if (count($missingFields) > 0) {
        echo json_encode([
            "success" => false,
            "message" => "Missing required fields: " . implode(", ", $missingFields)
        ]);
        exit;
    }

    $reg_id = $input['reg_id'];
    $name = $input['name'];
    $user_type = $input['user_type'];
    $user_name = $input['user_name'];
    $password = password_hash($input['password'], PASSWORD_BCRYPT);

    if (is_array($input['permissions'])) {
        $permissions = json_encode($input['permissions'], JSON_UNESCAPED_UNICODE);
    } else {
        $permissions = json_encode(explode(",", $input['permissions']), JSON_UNESCAPED_UNICODE);
    }

    // ✅ Check if username already exists
    $checkStmt = $conn->prepare("SELECT COUNT(*) as cnt FROM staff WHERE com_id = ? AND user_name = ?");
    $checkStmt->bind_param("is", $company_id, $user_name);
    $checkStmt->execute();
    $result = $checkStmt->get_result()->fetch_assoc();
    $checkStmt->close();

    if ($result['cnt'] > 0) {
        echo json_encode(["success" => false, "message" => "Username already exists"]);
        exit;
    }

    // ✅ Insert new staff
    $stmt = $conn->prepare("INSERT INTO staff (com_id, reg_id, name, user_type, user_name, password, permissions) 
                            VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issssss", $company_id, $reg_id, $name, $user_type, $user_name, $password, $permissions);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "User inserted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Insert failed: " . $stmt->error]);
    }
    $stmt->close();
}


elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $data = getTokenData($secret_key);
    $company_id = $data->companyId;
    $uid = $data->uid;

    try {
        $stmt = $conn->prepare("SELECT uid, reg_id, name, user_type, user_name, permissions 
                                FROM staff 
                                WHERE com_id = ? AND uid = ?
                                ORDER BY uid DESC");
        $stmt->bind_param("ii", $company_id, $uid);
        $stmt->execute();
        $result = $stmt->get_result();

        $staff = [];
        while ($row = $result->fetch_assoc()) {
            // Try decoding JSON
            $decoded = json_decode($row['permissions'], true);

            if ($decoded === null) {
                // Fallback: parse manually
                $clean = trim($row['permissions'], "[]\" "); 
                $items = explode(",", $clean);
                $decoded = array_map(function($v) {
                    return trim(str_replace(":", "", str_replace('"', '', $v)));
                }, $items);
            }

            $row['permissions'] = $decoded ?: [];
            $staff[] = $row;
        }
        $stmt->close();

        echo json_encode([
            "success" => true,
            "com_id" => $company_id,
            "staff" => $staff
        ]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Server error: " . $e->getMessage()]);
    }
}


// Invalid method
else {
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
}

$conn->close();
?>
