<?php
// ══════════════════════════════════════════
// auth.php — Login & Auth handler
// Path: spp_admin/api/auth.php
// ══════════════════════════════════════════

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/db.php';

// Validasi API Key
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? $_GET['api_key'] ?? '';
if ($apiKey !== 'spp_secret_key_2024') {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'login':   handleLogin($pdo);   break;
    case 'logout':  handleLogout();       break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Action tidak dikenal']);
}

// ── LOGIN ──────────────────────────────────
function handleLogin($pdo) {
    $body = json_decode(file_get_contents('php://input'), true);
    $username = trim($body['username'] ?? $_POST['username'] ?? '');
    $password = trim($body['password'] ?? $_POST['password'] ?? '');

    if (empty($username) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => 'Username dan password wajib diisi']);
        return;
    }

    $stmt = $pdo->prepare("
        SELECT u.*, s.kelas, s.jurusan, s.nis
        FROM users u
        LEFT JOIN siswa s ON u.siswa_id = s.id
        WHERE u.username = ? AND u.is_active = 1
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password'])) {
        echo json_encode(['status' => 'error', 'message' => 'NIS atau password salah']);
        return;
    }

    // Generate token sederhana
    $token = bin2hex(random_bytes(32));

    // Simpan token di session atau DB (simplified: return token)
    $response = [
        'status' => 'success',
        'data' => [
            'token'     => $token,
            'role'      => $user['role'],
            'id'        => $user['id'],
            'nama'      => $user['nama'],
            'username'  => $user['username'],
            'siswa_id'  => $user['siswa_id'],
            'nis'       => $user['nis'] ?? $user['username'],
            'kelas'     => $user['kelas'] ?? '',
            'jurusan'   => $user['jurusan'] ?? '',
        ]
    ];
    echo json_encode($response);
}

function handleLogout() {
    echo json_encode(['status' => 'success', 'message' => 'Logout berhasil']);
}