<?php
// Izinkan akses dari domain manapun (CORS)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header('Content-Type: application/json');

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

// ==========================================================
// 1. KONEKSI SQLITE (TANPA USER & TANPA PASSWORD)
// ==========================================================
try {
    // File database akan otomatis dibuat dengan nama "database_arsip.db"
    $conn = new PDO("sqlite:database_arsip.db");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Gagal koneksi: ' . $e->getMessage()]);
    exit();
}

// ==========================================================
// 2. AUTO-CREATE TABEL (VERSI SQLITE)
// ==========================================================
$sql_create = "CREATE TABLE IF NOT EXISTS riwayat_arsip (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uid TEXT NOT NULL,
    username TEXT,
    tujuan TEXT,
    produk TEXT,
    kode_produk TEXT,
    harga INTEGER,
    status TEXT,
    sn TEXT,
    trx_id TEXT UNIQUE,
    raw_json TEXT,
    timestamp_str TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)";
$conn->exec($sql_create);

// ==========================================================
// 3. ROUTING ACTION
// ==========================================================
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {

    case 'arsip_masal':
        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        if (!$data || !isset($data['uid']) || !isset($data['data'])) {
            echo json_encode(['status' => 'error', 'message' => 'Data tidak valid']);
            exit();
        }

        $uid = $data['uid'];
        $berhasil = 0;

        // Gunakan INSERT OR IGNORE khas SQLite
        $stmt = $conn->prepare("INSERT OR IGNORE INTO riwayat_arsip (uid, username, tujuan, produk, kode_produk, harga, status, sn, trx_id, raw_json, timestamp_str) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        foreach ($data['data'] as $row) {
            $stmt->execute([
                $uid, 
                $row['username'] ?? '-', 
                $row['tujuan'] ?? '-', 
                $row['produk'] ?? '-', 
                $row['kode_produk'] ?? '', 
                intval($row['harga'] ?? 0), 
                $row['status'] ?? 'PENDING', 
                $row['sn'] ?? '', 
                $row['trx_id'] ?? uniqid('arsip_'), 
                $row['raw_json'] ?? '{}', 
                $row['timestamp_str'] ?? date('c')
            ]);
            if ($stmt->rowCount() > 0) $berhasil++;
        }

        echo json_encode(['status' => 'success', 'berhasil' => $berhasil]);
        break;

    case 'get_arsip':
        $uid = isset($_GET['uid']) ? $_GET['uid'] : '';
        $stmt = $conn->prepare("SELECT * FROM riwayat_arsip WHERE uid = ? ORDER BY timestamp_str DESC");
        $stmt->execute([$uid]);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['status' => 'success', 'data' => $data]);
        break;

    case 'get_admin_date':
        $date = isset($_GET['date']) ? $_GET['date'] : '';
        $stmt = $conn->prepare("SELECT * FROM riwayat_arsip WHERE timestamp_str LIKE ? ORDER BY timestamp_str DESC");
        $stmt->execute(["%$date%"]);
        echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    case 'update_status':
        $stmt = $conn->prepare("UPDATE riwayat_arsip SET status = ? WHERE uid = ? AND trx_id = ?");
        $stmt->execute([$_GET['status'], $_GET['uid'], $_GET['trx_id']]);
        echo json_encode(['status' => 'success']);
        break;

    case 'hapus_arsip':
        $stmt = $conn->prepare("DELETE FROM riwayat_arsip WHERE uid = ? AND trx_id = ?");
        $stmt->execute([$_GET['uid'], $_GET['trx_id']]);
        echo json_encode(['status' => 'success']);
        break;

    default:
        echo json_encode(['status' => 'error', 'message' => 'Action tidak ditemukan']);
        break;
}
?>