<?php
session_start();

// Security: Check if user is logged in
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    if (isset($_POST['action']) || isset($_GET['preview'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }
    header("Location: ../../index.html?error=session");
    exit;
}

require_once __DIR__ . '/../../DataBase/koneksi.php';

if (!$conn) {
    if (isset($_POST['action']) || isset($_GET['preview'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Database connection failed']);
        exit;
    }
    die("Koneksi database gagal!");
}

// Get user role
$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
$backPage = ($userRole === 'A') ? '../admin/home_admin.php' : (($userRole === 'M') ? '../manager/home_manager.php' : '../staff/home_staff.php');

/**
 * ASSET CODE GENERATOR CLASS - FIXED VERSION
 * Auto-generate kode saat data baru diinput + regenerate untuk data lama
 */
class AssetCodeGenerator {
    private $conn;
    
    // MAPPING KODE KANTOR
    private $kode_kantor = [
        'Pusat' => 'PST',
        'Cabang Jakarta' => 'CJK',
        'Cabang Bandung' => 'CBD',
        'Cabang Surabaya' => 'CSB',
        'Cabang Medan' => 'CMD',
        'Cabang Yogyakarta' => 'CYK',
        'Cabang Semarang' => 'CSM',
        'Cabang Bali' => 'CBA',
        'Kantor Pusat' => 'PST',
        'Jakarta' => 'JKT',
        'Bandung' => 'BDG',
        'Surabaya' => 'SBY',
        'Medan' => 'MDN',
        'Yogyakarta' => 'YGK',
        'Semarang' => 'SMG',
        'Bali' => 'BAL',
    ];
    
    // MAPPING KODE KATEGORI
    private $kode_kategori = [
        'Elektronik' => 'ELK',
        'Furniture' => 'FRN',
        'Kendaraan' => 'KDN',
        'Komputer' => 'KMP',
        'Alat Tulis' => 'ATK',
        'Peralatan Kantor' => 'PKT',
        'Bangunan' => 'BGN',
        'Peralatan Teknologi' => 'TEK',
        'Alat Kesehatan' => 'KSH',
        'Peralatan Olahraga' => 'OLG',
        'Perlengkapan' => 'PLG',
        'Mesin' => 'MSN',
        'Perangkat' => 'PRG',
    ];
    
    // MAPPING KODE SUMBER DANA
    private $kode_sumber_dana = [
        'BOS' => 'BOS',
        'Hibah' => 'HBH',
        'Yayasan' => 'YYS',
        'APBN' => 'ABN',
        'APBD' => 'ABD',
        'Swadaya' => 'SWD',
        'Dana Desa' => 'DDS',
        'CSR' => 'CSR',
        'Donasi' => 'DNS',
        'Pembelian' => 'BLI',
        'Bantuan' => 'BTN',
    ];
    
    public function __construct($connection) {
        $this->conn = $connection;
    }
    
    private function getKodeKantor($nama_kantor) {
        if (isset($this->kode_kantor[$nama_kantor])) {
            return $this->kode_kantor[$nama_kantor];
        }
        
        $words = explode(' ', $nama_kantor);
        if (count($words) >= 2) {
            $kode = '';
            foreach (array_slice($words, 0, 3) as $word) {
                if (!empty($word)) {
                    $kode .= strtoupper(substr($word, 0, 1));
                }
            }
            return str_pad($kode, 3, 'X');
        }
        
        return strtoupper(substr($nama_kantor, 0, 3));
    }
    
    private function getKodeKategori($nama_kategori) {
        if (isset($this->kode_kategori[$nama_kategori])) {
            return $this->kode_kategori[$nama_kategori];
        }
        
        $words = explode(' ', $nama_kategori);
        if (count($words) >= 2) {
            $kode = '';
            foreach (array_slice($words, 0, 3) as $word) {
                if (!empty($word)) {
                    $kode .= strtoupper(substr($word, 0, 1));
                }
            }
            return str_pad($kode, 3, 'X');
        }
        
        return strtoupper(substr($nama_kategori, 0, 3));
    }
    
    private function getKodeSumberDana($nama_sumber) {
        if (isset($this->kode_sumber_dana[$nama_sumber])) {
            return $this->kode_sumber_dana[$nama_sumber];
        }
        
        return strtoupper(substr($nama_sumber, 0, 3));
    }
    
    private function getKodeBarang($kantor, $kategori, $tahun = null) {
        if (!$tahun) {
            $tahun = date('Y');
        }
        
        $sql = "SELECT COUNT(*) as total FROM inventory 
                WHERE kantor = ? 
                AND kategori = ? 
                AND YEAR(tanggal_perolehan) = ?
                AND status = 'aktif'";
        
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt) {
            return '001';
        }
        
        $stmt->bind_param("sss", $kantor, $kategori, $tahun);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result && $row = $result->fetch_assoc()) {
            $counter = $row['total'] + 1;
        } else {
            $counter = 1;
        }
        
        $stmt->close();
        
        return str_pad($counter, 3, '0', STR_PAD_LEFT);
    }
    
    public function generate($id_inventory = null, $data = null) {
        if (!$data && $id_inventory) {
            $sql = "SELECT * FROM inventory WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            
            if (!$stmt) return null;
            
            $stmt->bind_param("i", $id_inventory);
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_assoc();
            $stmt->close();
            
            if (!$data) return null;
        }
        
        if (empty($data['kantor']) || empty($data['kategori']) || empty($data['sumber_dana'])) {
            return null;
        }
        
        $kode_k = $this->getKodeKantor($data['kantor']);
        $kode_kat = $this->getKodeKategori($data['kategori']);
        
        $tahun = isset($data['tanggal_perolehan']) ? date('Y', strtotime($data['tanggal_perolehan'])) : date('Y');
        $kode_brg = $this->getKodeBarang($data['kantor'], $data['kategori'], $tahun);
        
        $kode_sd = $this->getKodeSumberDana($data['sumber_dana']);
        
        $kode_asset = "{$kode_k}.{$kode_kat}.{$kode_brg}.{$kode_sd}";
        
        if ($id_inventory) {
            $sql_update = "UPDATE inventory SET kode_aset_auto = ? WHERE id = ?";
            $stmt_update = $this->conn->prepare($sql_update);
            
            if (!$stmt_update) return null;
            
            $stmt_update->bind_param("si", $kode_asset, $id_inventory);
            $success = $stmt_update->execute();
            $stmt_update->close();
            
            return $success ? $kode_asset : null;
        }
        
        return $kode_asset;
    }
    
    public function regenerateAll() {
        // PENTING: Order by tanggal_perolehan dan ID untuk urutan yang konsisten
        $sql = "SELECT id FROM inventory 
                WHERE (kode_aset_auto IS NULL OR kode_aset_auto = '') 
                AND kantor IS NOT NULL 
                AND kategori IS NOT NULL 
                AND sumber_dana IS NOT NULL 
                AND status = 'aktif'
                ORDER BY tanggal_perolehan ASC, id ASC";
        $result = $this->conn->query($sql);
        
        if (!$result) {
            return ['success' => 0, 'failed' => 0, 'total' => 0];
        }
        
        $success = 0;
        $failed = 0;
        
        while ($row = $result->fetch_assoc()) {
            $kode = $this->generate($row['id']);
            if ($kode) {
                $success++;
            } else {
                $failed++;
            }
        }
        
        return [
            'success' => $success,
            'failed' => $failed,
            'total' => $success + $failed
        ];
    }
}

// ==========================================
// HANDLE AJAX REQUEST
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'regenerate_all') {
        $generator = new AssetCodeGenerator($conn);
        $result = $generator->regenerateAll();
        
        echo json_encode([
            'success' => true,
            'message' => "Generate selesai! Berhasil: {$result['success']}, Gagal: {$result['failed']}",
            'data' => $result
        ]);
        $conn->close();
        exit;
    }
    
    // AJAX untuk get updated stats
    if ($_POST['action'] === 'get_stats') {
        $check_missing = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE (kode_aset_auto IS NULL OR kode_aset_auto = '') AND status='aktif'");
        $missing_count = $check_missing->fetch_assoc()['total'];
        
        $check_complete = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE kode_aset_auto IS NOT NULL AND kode_aset_auto != '' AND status='aktif'");
        $complete_count = $check_complete->fetch_assoc()['total'];
        
        $total_items = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'];
        
        echo json_encode([
            'success' => true,
            'missing' => $missing_count,
            'complete' => $complete_count,
            'total' => $total_items
        ]);
        $conn->close();
        exit;
    }
}

// ==========================================
// GET STATISTICS
// ==========================================
$check_missing = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE (kode_aset_auto IS NULL OR kode_aset_auto = '') AND status='aktif'");
$missing_count = $check_missing->fetch_assoc()['total'];

$check_complete = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE kode_aset_auto IS NOT NULL AND kode_aset_auto != '' AND status='aktif'");
$complete_count = $check_complete->fetch_assoc()['total'];

$total_items = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'];

// Get items without code
$sql_missing = "SELECT id, jenis_barang, kantor, kategori, sumber_dana FROM inventory 
                WHERE (kode_aset_auto IS NULL OR kode_aset_auto = '') 
                AND status='aktif'
                ORDER BY id DESC LIMIT 20";
$result_missing = $conn->query($sql_missing);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Kode Asset - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --bg-light: #f8fafc;
            --text-dark: #1e293b;
            --text-medium: #475569;
            --text-light: #64748b;
            --border-color: #e2e8f0;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body { 
            font-family: 'Inter', sans-serif; 
            background: linear-gradient(135deg, var(--lightest-mint) 0%, var(--light-mint) 100%);
            padding: 25px; 
            color: var(--text-dark); 
            min-height: 100vh;
        }
        
        .container { max-width: 1200px; margin: 0 auto; }
        
        .header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 30px; 
            background: white; 
            padding: 24px 28px; 
            border-radius: 16px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
            border-left: 5px solid var(--primary-teal);
        }
        
        .header h2 { 
            display: flex; 
            align-items: center; 
            font-size: 26px;
            font-weight: 800;
            gap: 12px;
        }
        
        .header h2 i { 
            color: var(--primary-teal); 
        }
        
        .btn-back { 
            text-decoration: none; 
            padding: 11px 20px;
            border-radius: 12px;
            background: white;
            border: 2px solid var(--border-color);
            color: var(--text-dark);
            font-weight: 700;
            font-size: 13px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }
        
        .btn-back:hover { 
            background: var(--bg-light);
            border-color: var(--primary-teal);
        }
        
        .stats-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); 
            gap: 20px; 
            margin-bottom: 30px; 
        }
        
        .stat-card { 
            background: white; 
            padding: 28px; 
            border-radius: 16px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.04);
            border: 1px solid var(--border-color);
            transition: all 0.3s ease;
        }

        .stat-card.updating {
            animation: pulse 1s ease-in-out;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.02); }
        }
        
        .stat-card .icon { 
            width: 56px; 
            height: 56px; 
            border-radius: 14px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 26px; 
            margin-bottom: 16px; 
        }
        
        .stat-card.missing .icon { background: #fff7ed; color: #ea580c; }
        .stat-card.complete .icon { background: #dcfce7; color: #16a34a; }
        .stat-card.total .icon { background: #e0f2f1; color: var(--primary-teal); }
        
        .stat-card .number { font-size: 36px; font-weight: 800; margin-bottom: 6px; }
        .stat-card .label { font-size: 14px; color: var(--text-light); font-weight: 600; }
        
        .main-card { 
            background: white; 
            padding: 40px; 
            border-radius: 16px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.04);
            margin-bottom: 30px; 
            text-align: center;
            border: 1px solid var(--border-color);
        }
        
        .main-card h3 { 
            font-size: 22px; 
            margin-bottom: 12px; 
            color: var(--text-dark);
            font-weight: 700;
        }
        
        .main-card p { 
            color: var(--text-light); 
            margin-bottom: 28px; 
            line-height: 1.6;
        }
        
        .btn-generate { 
            background: var(--primary-teal); 
            color: white; 
            border: none; 
            padding: 16px 40px; 
            border-radius: 12px; 
            font-weight: 700; 
            font-size: 16px; 
            cursor: pointer; 
            transition: all 0.3s ease; 
            display: inline-flex; 
            align-items: center; 
            gap: 10px; 
        }
        
        .btn-generate:hover { 
            background: var(--secondary-teal); 
            transform: translateY(-2px); 
            box-shadow: 0 8px 20px rgba(122, 178, 178, 0.3); 
        }
        
        .btn-generate:disabled { 
            background: #cbd5e1; 
            cursor: not-allowed; 
            transform: none; 
        }
        
        .preview-section { 
            background: white; 
            padding: 30px; 
            border-radius: 16px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.04);
            border: 1px solid var(--border-color);
        }
        
        .preview-section h4 { 
            margin-bottom: 24px; 
            display: flex; 
            align-items: center; 
            gap: 10px;
            font-size: 18px;
            font-weight: 700;
            color: var(--text-dark);
        }
        
        .preview-table { 
            width: 100%; 
            border-collapse: collapse; 
        }
        
        .preview-table th { 
            background: var(--bg-light); 
            padding: 14px 16px; 
            text-align: left; 
            font-size: 11px; 
            font-weight: 700; 
            color: var(--text-medium); 
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .preview-table td { 
            padding: 16px; 
            border-bottom: 1px solid var(--border-color); 
            font-size: 14px;
        }
        
        .preview-table tbody tr:hover { background: var(--lightest-mint); }
        .preview-table tbody tr:last-child td { border-bottom: none; }
        
        .badge { 
            display: inline-block; 
            padding: 6px 12px; 
            border-radius: 8px; 
            font-size: 12px; 
            font-weight: 700; 
        }
        
        .badge.warning { background: #fff7ed; color: #c2410c; }
        
        .alert { 
            padding: 20px 24px; 
            border-radius: 12px; 
            margin-bottom: 25px; 
            display: flex; 
            align-items: center; 
            gap: 16px;
            font-weight: 600;
        }
        
        .alert.success { 
            background: #dcfce7; 
            border: 2px solid #16a34a; 
            color: #166534; 
        }
        
        .alert.error { 
            background: #fee2e2; 
            border: 2px solid #dc2626; 
            color: #991b1b; 
        }
        
        .alert i { font-size: 24px; }
        
        .loading { 
            display: none; 
            align-items: center; 
            justify-content: center; 
            gap: 12px; 
            margin-top: 20px; 
            color: var(--primary-teal);
            font-weight: 600;
        }
        
        .loading.show { display: flex; }
        
        .spinner { 
            border: 3px solid #f3f4f6; 
            border-top: 3px solid var(--primary-teal); 
            border-radius: 50%; 
            width: 24px; 
            height: 24px; 
            animation: spin 1s linear infinite; 
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .empty-state { 
            text-align: center; 
            padding: 60px 20px; 
            color: var(--text-light); 
        }
        
        .empty-state i { 
            font-size: 56px; 
            margin-bottom: 16px; 
            color: #16a34a;
        }
        
        .empty-state p {
            font-size: 16px;
            font-weight: 600;
        }

        .info-box {
            background: var(--lightest-mint);
            border-left: 4px solid var(--primary-teal);
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
        }

        .info-box h4 {
            color: var(--secondary-teal);
            margin-bottom: 12px;
            font-size: 16px;
            font-weight: 700;
        }

        .info-box ul {
            margin-left: 20px;
            color: var(--text-medium);
            line-height: 1.8;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e2e8f0;
            border-radius: 10px;
            margin-top: 20px;
            overflow: hidden;
            display: none;
        }

        .progress-bar.show {
            display: block;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--secondary-teal), var(--primary-teal));
            width: 0%;
            transition: width 0.3s ease;
            border-radius: 10px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h2><i class="fas fa-cog"></i> Generate Kode Asset</h2>
        <a href="<?= $backPage ?>" class="btn-back"><i class="fas fa-arrow-left"></i> Kembali</a>
    </div>

    <div class="info-box">
        <h4><i class="fas fa-info-circle"></i> Informasi Penting</h4>
        <ul>
            <li><strong>Kode Otomatis:</strong> Setiap data baru yang diinput akan langsung mendapat kode asset otomatis</li>
            <li><strong>Format Kode:</strong> KANTOR.KATEGORI.URUT.SUMBER_DANA (contoh: PST.KMP.001.BOS)</li>
            <li><strong>Sinkronisasi:</strong> Kode asset akan otomatis terlihat di semua role (Admin, Manager, Staff)</li>
            <li><strong>Regenerate:</strong> Gunakan tombol di bawah untuk generate kode pada data lama yang belum punya kode</li>
        </ul>
    </div>

    <div class="stats-grid">
        <div class="stat-card missing" id="statMissing">
            <div class="icon"><i class="fas fa-exclamation-triangle"></i></div>
            <div class="number" id="missingCount"><?= $missing_count ?></div>
            <div class="label">Belum Ada Kode</div>
        </div>
        <div class="stat-card complete" id="statComplete">
            <div class="icon"><i class="fas fa-check-circle"></i></div>
            <div class="number" id="completeCount"><?= $complete_count ?></div>
            <div class="label">Sudah Ada Kode</div>
        </div>
        <div class="stat-card total" id="statTotal">
            <div class="icon"><i class="fas fa-database"></i></div>
            <div class="number" id="totalCount"><?= $total_items ?></div>
            <div class="label">Total Asset</div>
        </div>
    </div>

    <div id="alertContainer"></div>

    <div class="main-card">
        <h3><i class="fas fa-bolt"></i> Generate Kode Asset Otomatis</h3>
        <p>Generate kode asset untuk data lama yang belum memiliki kode. Data baru akan otomatis mendapat kode saat input.</p>
        
        <button class="btn-generate" onclick="generateAll()" id="btnGenerate" <?= $missing_count == 0 ? 'disabled' : '' ?>>
            <i class="fas fa-magic"></i>
            <span id="btnText"><?= $missing_count > 0 ? "Generate $missing_count Item" : "Semua Sudah Lengkap" ?></span>
        </button>
        
        <div class="loading" id="loadingIndicator">
            <div class="spinner"></div>
            <span>Sedang memproses...</span>
        </div>

        <div class="progress-bar" id="progressBar">
            <div class="progress-fill" id="progressFill"></div>
        </div>
    </div>

    <?php if ($result_missing && $result_missing->num_rows > 0): ?>
    <div class="preview-section" id="previewSection">
        <h4><i class="fas fa-list"></i> Preview Item Tanpa Kode (20 Teratas)</h4>
        <table class="preview-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Barang</th>
                    <th>Kantor</th>
                    <th>Kategori</th>
                    <th>Sumber Dana</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody id="previewTableBody">
                <?php while($row = $result_missing->fetch_assoc()): ?>
                <tr>
                    <td>#<?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['jenis_barang']) ?></td>
                    <td><?= htmlspecialchars($row['kantor']) ?></td>
                    <td><?= htmlspecialchars($row['kategori']) ?></td>
                    <td><?= htmlspecialchars($row['sumber_dana']) ?></td>
                    <td><span class="badge warning">Belum Ada Kode</span></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="preview-section" id="previewSection">
        <div class="empty-state">
            <i class="fas fa-check-circle"></i>
            <p>Semua item sudah memiliki kode asset!</p>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Update stats secara real-time
function updateStats() {
    fetch(window.location.href, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=get_stats'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update dengan animasi
            document.getElementById('missingCount').textContent = data.missing;
            document.getElementById('completeCount').textContent = data.complete;
            document.getElementById('totalCount').textContent = data.total;
            
            // Trigger pulse animation
            document.getElementById('statMissing').classList.add('updating');
            document.getElementById('statComplete').classList.add('updating');
            document.getElementById('statTotal').classList.add('updating');
            
            setTimeout(() => {
                document.getElementById('statMissing').classList.remove('updating');
                document.getElementById('statComplete').classList.remove('updating');
                document.getElementById('statTotal').classList.remove('updating');
            }, 1000);
            
            // Update button
            const btn = document.getElementById('btnGenerate');
            const btnText = document.getElementById('btnText');
            if (data.missing === 0) {
                btn.disabled = true;
                btnText.textContent = 'Semua Sudah Lengkap';
            } else {
                btn.disabled = false;
                btnText.textContent = `Generate ${data.missing} Item`;
            }
        }
    })
    .catch(error => console.error('Error updating stats:', error));
}

function generateAll() {
    const btn = document.getElementById('btnGenerate');
    const loading = document.getElementById('loadingIndicator');
    const alertContainer = document.getElementById('alertContainer');
    const progressBar = document.getElementById('progressBar');
    const progressFill = document.getElementById('progressFill');
    
    btn.disabled = true;
    loading.classList.add('show');
    progressBar.classList.add('show');
    alertContainer.innerHTML = '';
    progressFill.style.width = '0%';
    
    // Simulate progress
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += 5;
        if (progress <= 90) {
            progressFill.style.width = progress + '%';
        }
    }, 100);
    
    fetch(window.location.href, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'action=regenerate_all'
    })
    .then(response => response.json())
    .then(data => {
        clearInterval(progressInterval);
        progressFill.style.width = '100%';
        
        setTimeout(() => {
            loading.classList.remove('show');
            progressBar.classList.remove('show');
            
            if (data.success) {
                alertContainer.innerHTML = `
                    <div class="alert success">
                        <i class="fas fa-check-circle"></i>
                        <div>
                            <strong>Berhasil!</strong><br>
                            ${data.message}<br>
                            <small>Data akan otomatis muncul di Inventory List</small>
                        </div>
                    </div>
                `;
                
                // Update stats immediately
                updateStats();
                
                // Reload setelah 2 detik
                setTimeout(() => {
                    location.reload();
                }, 2000);
            } else {
                alertContainer.innerHTML = `
                    <div class="alert error">
                        <i class="fas fa-times-circle"></i>
                        <div>
                            <strong>Gagal!</strong><br>
                            Terjadi kesalahan saat generate kode.
                        </div>
                    </div>
                `;
                btn.disabled = false;
            }
        }, 500);
    })
    .catch(error => {
        clearInterval(progressInterval);
        loading.classList.remove('show');
        progressBar.classList.remove('show');
        alertContainer.innerHTML = `
            <div class="alert error">
                <i class="fas fa-times-circle"></i>
                <div>
                    <strong>Error!</strong><br>
                    ${error.message}
                </div>
            </div>
        `;
        btn.disabled = false;
    });
}

// Auto-update stats setiap 10 detik (optional)
// setInterval(updateStats, 10000);
</script>

</body>
</html>
<?php
$conn->close();
?>