<?php
session_start();
require 'config.php'; // Pastikan ini berisi pengaturan API dan database

// Ambil token akses dari sesi
$accessToken = isset($_SESSION['access_token']) ? $_SESSION['access_token'] : null;

if (!$accessToken) {
    die("Error: Token akses tidak ditemukan. Harap login kembali.");
}

// Fungsi untuk melakukan permintaan API
function apiRequest($endpoint, $method = 'GET', $data = null) {
    global $accessToken;

    $url = "https://api.accurate.id/warehouse" . $endpoint;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer $accessToken",
        "Content-Type: application/json"
    ));

    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    } elseif ($method == 'DELETE') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
        if ($data) {
            $url .= '?' . http_build_query($data);
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        die("cURL Error: " . curl_error($ch));
    }
    curl_close($ch);

    return json_decode($response, true);
}

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : null;
$id = isset($_GET['id']) ? $_GET['id'] : null;

if ($action == 'delete' && $id) {
    $result = apiRequest('/delete.do', 'DELETE', array('id' => $id));
    if (isset($result['success']) && $result['success']) {
        $_SESSION['msg']['success'] = "Data berhasil dihapus.";
    } else {
        $_SESSION['msg']['danger'] = "Gagal menghapus data.";
    }
    header("Location: warehouse_accurate.php");
    exit();
}

if ($action == 'save' && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = array(
        'name' => $_POST['name'],
        'location' => $_POST['location'],
        // tambahkan data lain sesuai kebutuhan
    );

    if ($id) {
        $result = apiRequest('/save.do', 'POST', $data);
        $_SESSION['msg']['success'] = "Data berhasil diperbarui.";
    } else {
        $result = apiRequest('/save.do', 'POST', $data);
        $_SESSION['msg']['success'] = "Data berhasil ditambahkan.";
    }
    header("Location: warehouse_accurate.php");
    exit();
}

// Ambil daftar warehouse
$warehouses = apiRequest('/list.do');

// Ambil detail warehouse jika ada ID
$warehouse = null;
if ($id && $action == 'edit') {
    $warehouse = apiRequest('/detail.do', 'GET', array('id' => $id));
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Warehouse Management</title>
    <link rel="stylesheet" href="styles.css"> <!-- Tambahkan gaya sesuai kebutuhan -->
</head>
<body>
    <h1>Warehouse Management</h1>

    <?php if (isset($_SESSION['msg'])): ?>
        <?php foreach ($_SESSION['msg'] as $type => $message): ?>
            <div class="alert alert-<?php echo htmlspecialchars($type); ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endforeach; ?>
        <?php unset($_SESSION['msg']); ?>
    <?php endif; ?>

    <form action="warehouse_accurate.php?action=save<?php echo $warehouse ? '&id=' . htmlspecialchars($id) : ''; ?>" method="POST">
        <h2><?php echo $warehouse ? 'Edit Warehouse' : 'Add New Warehouse'; ?></h2>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" value="<?php echo $warehouse ? htmlspecialchars($warehouse['name']) : ''; ?>" required>

        <label for="location">Location:</label>
        <input type="text" id="location" name="location" value="<?php echo $warehouse ? htmlspecialchars($warehouse['location']) : ''; ?>" required>

        <button type="submit"><?php echo $warehouse ? 'Update' : 'Add'; ?></button>
    </form>

    <h2>Warehouse List</h2>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Location</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($warehouses)): ?>
                <?php foreach ($warehouses as $wh): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($wh['id']); ?></td>
                        <td><?php echo htmlspecialchars($wh['name']); ?></td>
                        <td><?php echo htmlspecialchars($wh['location']); ?></td>
                        <td>
                            <a href="warehouse_accurate.php?action=edit&id=<?php echo htmlspecialchars($wh['id']); ?>">Edit</a>
                            <a href="warehouse_accurate.php?action=delete&id=<?php echo htmlspecialchars($wh['id']); ?>" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4">No data available</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</body>
</html>
