<?php
/**
 * File: update_provider.php
 * Lokasi: Root folder
 */

// 1. Perbaikan Path: Pastikan file ini ada di folder config
// Jika koneksi.php mendefinisikan variabel dengan nama lain (misal $conn), 
// ganti semua $conn di bawah menjadi $conn.
require_once 'config/koneksi.php'; 
require_once 'config/class.hgi.php';

$api = new HypergateAPI();
$message = "";

// Cek apakah koneksi tersedia
if (!$conn) {
    die("Koneksi gagal: " . mysqli_connect_error());
}

// Logika ketika tombol Sync ditekan
if (isset($_POST['sync_provider'])) {
    $response = $api->provider_list();
    
    if ($response && isset($response['status']) && $response['status'] == 1) {
        $countSuccess = 0;
        foreach ($response['providers'] as $prov) {
            // Sanitasi data
            $code = mysqli_real_escape_string($conn, $prov['code']);
            $name = mysqli_real_escape_string($conn, $prov['name']);
            $status = (int)$prov['status'];

            // Query dengan ON DUPLICATE KEY UPDATE berdasarkan UNIQUE KEY 'code'
            $sql = "INSERT INTO tb_provider (code, name, status, created_at, updated_at) 
                    VALUES ('$code', '$name', $status, NOW(), NOW())
                    ON DUPLICATE KEY UPDATE 
                    name = VALUES(name), 
                    status = VALUES(status), 
                    updated_at = NOW()";
            
            if (mysqli_query($conn, $sql)) {
                $countSuccess++;
            }
        }
        $message = "<div class='alert alert-success shadow-sm'><strong>Berhasil!</strong> Memperbarui $countSuccess data provider.</div>";
    } else {
        $err_msg = isset($response['msg']) ? $response['msg'] : "Koneksi API Gagal";
        $message = "<div class='alert alert-danger shadow-sm'><strong>Gagal!</strong> $err_msg</div>";
    }
}

// Ambil data terbaru untuk laporan tabel
$query_db = mysqli_query($conn, "SELECT * FROM tb_provider ORDER BY name ASC");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Provider - Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body { background-color: #f4f7f6; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .main-card { border: none; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); }
        .btn-sync { border-radius: 10px; padding: 12px 30px; font-weight: 600; transition: all 0.3s; }
        .btn-sync:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(13, 110, 253, 0.3); }
        .table-res { border-radius: 12px; overflow: hidden; background: white; }
        .badge-status { font-size: 0.75rem; padding: 5px 10px; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-xl-10">
            
            <div class="card main-card mb-4 text-center p-4">
                <div class="card-body">
                    <i class="bi bi-cloud-arrow-down-fill text-primary" style="font-size: 3rem;"></i>
                    <h2 class="fw-bold mt-2">Provider Synchronizer</h2>
                    <p class="text-muted">Klik tombol di bawah untuk menyinkronkan data dari Hypergate API ke database lokal.</p>
                    
                    <form method="POST" class="mt-4">
                        <button type="submit" name="sync_provider" class="btn btn-primary btn-sync">
                            <i class="bi bi-arrow-repeat me-2"></i> Jalankan Sinkronisasi
                        </button>
                    </form>
                    
                    <div class="mt-4">
                        <?php echo $message; ?>
                    </div>
                </div>
            </div>

            <div class="table-res shadow-sm">
                <div class="bg-dark p-3 d-flex justify-content-between align-items-center">
                    <h5 class="text-white mb-0"><i class="bi bi-table me-2"></i> Laporan Provider</h5>
                    <span class="badge bg-light text-dark"><?php echo mysqli_num_rows($query_db); ?> Total</span>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-4">ID</th>
                                <th>Kode Provider</th>
                                <th>Nama Provider</th>
                                <th>Status</th>
                                <th>Terakhir Update</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($query_db) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($query_db)): ?>
                                <tr>
                                    <td class="ps-4 text-muted"><?php echo $row['id']; ?></td>
                                    <td><code class="fw-bold text-primary"><?php echo $row['code']; ?></code></td>
                                    <td class="fw-semibold"><?php echo $row['name']; ?></td>
                                    <td>
                                        <?php if($row['status'] == 1): ?>
                                            <span class="badge bg-success-subtle text-success border border-success-subtle badge-status">
                                                <i class="bi bi-check-circle-fill me-1"></i> Open
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-danger-subtle text-danger border border-danger-subtle badge-status">
                                                <i class="bi bi-exclamation-triangle-fill me-1"></i> Maintenance
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-muted small"><?php echo date('d M Y, H:i', strtotime($row['updated_at'])); ?></td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="text-center py-5 text-muted">
                                        <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                                        Database kosong. Silahkan lakukan sinkronisasi.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>