<?php
// api-sync.php - Endpoint untuk kasir sinkronisasi data
require_once __DIR__ . '/config.php';

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

$user = checkAuth();
if (!$user) {
    jsonResponse(['status' => 'error', 'message' => 'Unauthorized'], 401);
}

$db = getDB();

$rows = $db->query('
    SELECT p.*, c.name AS category_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    ORDER BY p.id
')->fetchAll();

$products = [];
foreach ($rows as $row) {
    $products[] = [
        'id' => (int)$row['id'],
        'category_id' => $row['category_id'] ? (int)$row['category_id'] : null,
        'name' => $row['name'],
        'description' => $row['description'],
        'image' => $row['image'] ?: '',
        'price' => $row['price'],
        'stock' => (int)$row['stock'],
        'status' => (int)$row['status'],
        'is_favorite' => (int)$row['is_favorite'],
        'created_at' => $row['created_at'],
        'updated_at' => $row['updated_at'],
        'category' => $row['category_id'] ? [
            'id' => (int)$row['category_id'],
            'name' => $row['category_name'],
        ] : null,
    ];
}

$categories = $db->query('SELECT * FROM categories ORDER BY name')->fetchAll();

$pmList = [];
try {
    $paymentMethods = $db->query('SELECT id, name, type, bank_name, account_name, account_number, is_active, sort_order FROM payment_methods WHERE is_active = 1 ORDER BY sort_order, id')->fetchAll();
    foreach ($paymentMethods as $pm) {
        $pmList[] = [
            'id' => (int)$pm['id'],
            'name' => $pm['name'],
            'type' => $pm['type'],
            'bank_name' => $pm['bank_name'],
            'account_name' => $pm['account_name'],
            'account_number' => $pm['account_number'],
            'is_active' => (int)$pm['is_active'],
            'sort_order' => (int)$pm['sort_order'],
        ];
    }
} catch (Exception $e) {
    // tabel payment_methods belum ada (migrasi belum dijalankan) — biarkan kosong
    $pmList = [];
}

$deviceId = $_GET['device_id'] ?? 'unknown';
$db->prepare('INSERT INTO sync_log (device_id) VALUES (?) ON DUPLICATE KEY UPDATE last_sync_at = NOW()')->execute([$deviceId]);

jsonResponse([
    'status' => 'success',
    'data' => [
        'products' => $products,
        'categories' => $categories,
        'payment_methods' => $pmList,
        'synced_at' => date('Y-m-d H:i:s'),
    ],
]);