<?php
// /api/middleware/auth_check.php

require_once '../config/database.php';
require_once '../config/jwt_helper.php';

// Ambil header Authorization dari Sketchware
$headers = apache_request_headers();
$auth_header = isset($headers['Authorization']) ? $headers['Authorization'] : '';

// Jika tidak ada header Authorization atau formatnya salah
if (!$auth_header || !preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Akses ditolak. Token tidak ditemukan."]);
    exit();
}

$jwt = $matches[1];
$user_data = MiniJWT::decode($jwt, $jwt_secret);

if (!$user_data) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Token tidak valid atau sudah kedaluwarsa."]);
    exit();
}

// Token valid! Kita simpan data payload-nya ke variabel global 
// agar bisa dipakai oleh file API yang meng-include file ini.
// Di sini terdapat id_juragan untuk pengaman Multi-Tenant!
$jwt_payload = $user_data->data;
?>
