<?php
// api-login.php
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['status' => 'error', 'message' => 'POST only'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$email = trim($input['email'] ?? '');
$password = $input['password'] ?? '';

if (empty($email) || empty($password)) {
    jsonResponse(['status' => 'error', 'message' => 'Email dan password wajib diisi'], 400);
}

$db = getDB();
$stmt = $db->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password'])) {
    jsonResponse(['status' => 'error', 'message' => 'Email atau password salah'], 401);
}

// Outlet info (kalau tabel outlets & kolom outlet_id udah ada)
$outletName = null;
$outletId = isset($user['outlet_id']) ? $user['outlet_id'] : null;
if ($outletId) {
    try {
        $stmt = $db->prepare('SELECT name FROM outlets WHERE id = ?');
        $stmt->execute([$outletId]);
        $o = $stmt->fetch();
        $outletName = $o ? $o['name'] : null;
    } catch (Exception $e) {
        $outletName = null;
    }
}

jsonResponse([
    'status' => 'success',
    'token' => $user['email'],
    'user' => [
        'id' => (int)$user['id'],
        'name' => $user['name'],
        'email' => $user['email'],
        'role' => $user['role'],
        'outlet_id' => $outletId ? (int)$outletId : null,
        'outlet_name' => $outletName,
    ],
]);