<?php
// reset_color_data.php
session_start();
require_once "../config/connection.php";

// Redirect if not IT user
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

$it_id = $_SESSION['user_id'];
$page_title = "Reset Color Data System";

// Handle form submission BEFORE including header
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_reset'])) {
    $confirmation_code = $_POST['confirmation_code'];
    $secret_code = $_POST['secret_code'];
    
    if ($confirmation_code === 'RESET2025' && $secret_code === '4444') {
        try {
            // Start transaction
            $conn->begin_transaction();
            
            // Disable foreign key checks
            $conn->query("SET FOREIGN_KEY_CHECKS = 0");
            
            $deleted_counts = [];
            
            // Delete in proper order to respect foreign key constraints
            
            // 1. Delete transaction_items first (has FK to stock_transactions and color_stock_items)
            $result = $conn->query("DELETE FROM transaction_items");
            $deleted_counts['transaction_items'] = $conn->affected_rows;
            $conn->query("ALTER TABLE transaction_items AUTO_INCREMENT = 1");
            
            // 2. Delete stock_transactions (has FK to borrower_users and collections)
            $result = $conn->query("DELETE FROM stock_transactions");
            $deleted_counts['stock_transactions'] = $conn->affected_rows;
            $conn->query("ALTER TABLE stock_transactions AUTO_INCREMENT = 1");
            
            // 3. Delete approval_history (has FK to color_approvals)
            $result = $conn->query("DELETE FROM approval_history");
            $deleted_counts['approval_history'] = $conn->affected_rows;
            $conn->query("ALTER TABLE approval_history AUTO_INCREMENT = 1");
            
            // 4. Delete color_approvals (has FK to color_stock_items, master_color_panel, components, approval_users)
            $result = $conn->query("DELETE FROM color_approvals");
            $deleted_counts['color_approvals'] = $conn->affected_rows;
            $conn->query("ALTER TABLE color_approvals AUTO_INCREMENT = 1");
            
            // 5. Delete expired_code_history (has FK to master_color_panel and color_components)
            $result = $conn->query("DELETE FROM expired_code_history");
            $deleted_counts['expired_code_history'] = $conn->affected_rows;
            $conn->query("ALTER TABLE expired_code_history AUTO_INCREMENT = 1");
            
            // 6. Delete renew_code_history (has FK to master_color_panel and color_components)
            $result = $conn->query("DELETE FROM renew_code_history");
            $deleted_counts['renew_code_history'] = $conn->affected_rows;
            $conn->query("ALTER TABLE renew_code_history AUTO_INCREMENT = 1");
            
            // 7. Delete color_stock_items (has FK to master_color and master_color_panel via color_id, and color_components)
            $result = $conn->query("DELETE FROM color_stock_items");
            $deleted_counts['color_stock_items'] = $conn->affected_rows;
            $conn->query("ALTER TABLE color_stock_items AUTO_INCREMENT = 1");
            
            // 8. Delete color_panel_components (has FK to master_color_panel and color_components)
            $result = $conn->query("DELETE FROM color_panel_components");
            $deleted_counts['color_panel_components'] = $conn->affected_rows;
            $conn->query("ALTER TABLE color_panel_components AUTO_INCREMENT = 1");
            
            // 9. Delete master_color_panel (has FK to master_color, buyers, collections)
            $result = $conn->query("DELETE FROM master_color_panel");
            $deleted_counts['master_color_panel'] = $conn->affected_rows;
            $conn->query("ALTER TABLE master_color_panel AUTO_INCREMENT = 1");
            
            // 10. Delete master_color (has FK to buyers and collections)
            $result = $conn->query("DELETE FROM master_color");
            $deleted_counts['master_color'] = $conn->affected_rows;
            $conn->query("ALTER TABLE master_color AUTO_INCREMENT = 1");
            
            // Enable foreign key checks
            $conn->query("SET FOREIGN_KEY_CHECKS = 1");
            
            // Commit transaction
            $conn->commit();
            
            // Log the activity with detailed information
            $details = "IT user successfully reset all color data system with dual authentication. " . 
                      "Confirmation code: RESET2025, Secret code verified. " .
                      "Deleted counts: " . json_encode($deleted_counts);
            create_audit_log($conn, 'System Reset - Complete', $it_id, 'it', $details);
            
            $_SESSION['reset_success'] = true;
            $_SESSION['deleted_counts'] = $deleted_counts;
            
            // Redirect to avoid form resubmission
            header("Location: reset_color_data.php");
            exit();
            
        } catch (Exception $e) {
            $conn->rollback();
            $conn->query("SET FOREIGN_KEY_CHECKS = 1");
            
            // Log the failed attempt
            create_audit_log($conn, 'System Reset - Failed', $it_id, 'it', "Reset failed with error: " . $e->getMessage());
            
            $_SESSION['error_message'] = "Error saat reset: " . $e->getMessage();
            header("Location: reset_color_data.php");
            exit();
        }
    } else {
        // Log the failed authentication attempt
        $failed_reason = "";
        if ($confirmation_code !== 'RESET2025') {
            $failed_reason .= "Invalid confirmation code. ";
        }
        if ($secret_code !== '4444') {
            $failed_reason .= "Invalid secret code. ";
        }
        
        create_audit_log($conn, 'System Reset - Auth Failed', $it_id, 'it', 
            "Reset attempt failed: " . $failed_reason . "Entered codes: '" . $confirmation_code . "' and '" . $secret_code . "'");
        
        $_SESSION['error_message'] = "Kode konfirmasi atau kode rahasia salah! Silakan coba lagi.";
        header("Location: reset_color_data.php");
        exit();
    }
}

// Check if reset was successful
$reset_success = isset($_SESSION['reset_success']) ? $_SESSION['reset_success'] : false;
$deleted_counts = isset($_SESSION['deleted_counts']) ? $_SESSION['deleted_counts'] : [];
$error_message = isset($_SESSION['error_message']) ? $_SESSION['error_message'] : '';

// Clear session messages
unset($_SESSION['reset_success']);
unset($_SESSION['deleted_counts']);
unset($_SESSION['error_message']);

// NOW include header after all processing is done
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-red-100 via-orange-100 to-yellow-100">
    
    <?php if ($reset_success): ?>
    <!-- Success Message -->
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded shadow-md mb-6">
        <div class="flex items-center">
            <i class="fas fa-check-circle text-2xl mr-3"></i>
            <div>
                <h3 class="font-bold text-lg">Reset Berhasil!</h3>
                <p>Semua data color system telah dihapus dan AUTO_INCREMENT direset ke 1.</p>
                <p class="text-sm mt-1">Reset dilakukan dengan verifikasi ganda untuk keamanan.</p>
            </div>
        </div>
        
        <div class="mt-4 bg-white p-4 rounded">
            <h4 class="font-semibold mb-2">Data yang dihapus:</h4>
            <div class="grid grid-cols-2 gap-2 text-sm">
                <?php foreach ($deleted_counts as $table => $count): ?>
                <div class="flex justify-between border-b pb-1">
                    <span class="font-medium"><?php echo htmlspecialchars($table); ?>:</span>
                    <span class="text-blue-600"><?php echo number_format($count); ?> rows</span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="mt-4 flex space-x-3">
            <a href="new_data_it.php" class="inline-block px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition">
                <i class="fas fa-plus mr-2"></i>Mulai Input Data Baru
            </a>
            <a href="dashboard_it.php" class="inline-block px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition">
                <i class="fas fa-home mr-2"></i>Kembali ke Dashboard
            </a>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($error_message)): ?>
    <!-- Error Message -->
    <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded shadow-md mb-6">
        <div class="flex items-center">
            <i class="fas fa-exclamation-circle text-2xl mr-3"></i>
            <div>
                <h3 class="font-bold text-lg">Error!</h3>
                <p><?php echo htmlspecialchars($error_message); ?></p>
                <p class="text-sm mt-1">Pastikan kedua kode dimasukkan dengan benar.</p>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Warning Header -->
    <div class="bg-red-600 text-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex items-center">
            <i class="fas fa-exclamation-triangle text-4xl mr-4"></i>
            <div>
                <h2 class="text-3xl font-bold mb-2">⚠️ PERINGATAN - RESET SYSTEM</h2>
                <p class="text-lg">Halaman ini akan menghapus SEMUA data color system dan mereset ke kondisi awal!</p>
                <p class="text-sm mt-2 opacity-90">Memerlukan verifikasi ganda untuk keamanan maksimal</p>
            </div>
        </div>
    </div>
    
    <!-- Information Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 class="text-xl font-bold text-red-600 mb-4">
            <i class="fas fa-info-circle mr-2"></i>Informasi Penting
        </h3>
        
        <div class="space-y-4">
            <div class="border-l-4 border-yellow-500 bg-yellow-50 p-4">
                <h4 class="font-bold text-yellow-800 mb-2">Data yang AKAN DIHAPUS:</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                    <ul class="list-disc list-inside space-y-1 text-sm text-yellow-800">
                        <li>Semua Master Color</li>
                        <li>Semua Master Color Panel (Copy Panel)</li>
                        <li>Semua Color Panel Components</li>
                        <li>Semua Color Stock Items (Kode Barang)</li>
                        <li>Semua Color Approvals</li>
                    </ul>
                    <ul class="list-disc list-inside space-y-1 text-sm text-yellow-800">
                        <li>Semua Approval History</li>
                        <li>Semua Stock Transactions</li>
                        <li>Semua Transaction Items</li>
                        <li>Semua Expired Code History</li>
                        <li>Semua Renew Code History</li>
                    </ul>
                </div>
            </div>
            
            <div class="border-l-4 border-green-500 bg-green-50 p-4">
                <h4 class="font-bold text-green-800 mb-2">Data yang TIDAK AKAN DIHAPUS:</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                    <ul class="list-disc list-inside space-y-1 text-sm text-green-800">
                        <li>Master Buyers (Pembeli)</li>
                        <li>Master Collections (Koleksi)</li>
                        <li>Master Color Components (Daftar Komponen)</li>
                    </ul>
                    <ul class="list-disc list-inside space-y-1 text-sm text-green-800">
                        <li>User Accounts (Admin, IT, Approval, Borrower)</li>
                        <li>Audit Logs & System Logs</li>
                        <li>Konfigurasi System</li>
                    </ul>
                </div>
            </div>
            
            <div class="border-l-4 border-blue-500 bg-blue-50 p-4">
                <h4 class="font-bold text-blue-800 mb-2">Setelah Reset:</h4>
                <ul class="list-disc list-inside space-y-1 text-sm text-blue-800">
                    <li>ID akan dimulai dari: <strong>1</strong></li>
                    <li>Kode Color akan dimulai dari: <strong>00001</strong></li>
                    <li>AUTO_INCREMENT semua tabel direset ke 1</li>
                    <li>Sistem siap untuk input data baru dari awal</li>
                    <li>Semua relasi foreign key akan bersih</li>
                </ul>
            </div>
        </div>
    </div>
    
    <!-- Reset Form -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">
            <i class="fas fa-key mr-2"></i>Konfirmasi Reset - Verifikasi Ganda
        </h3>
        
        <form method="POST" id="resetForm" onsubmit="return confirmReset()">
            <div class="space-y-6">
                
                <!-- Step 1: Confirmation Code -->
                <div class="border-2 border-orange-200 rounded-lg p-4 bg-orange-50">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-shield-alt mr-1"></i>
                        Step 1 - Masukkan Kode Konfirmasi: <span class="text-red-600 font-bold">RESET2025</span>
                    </label>
                    <input type="text" 
                           name="confirmation_code" 
                           id="confirmation_code"
                           class="w-full md:w-1/2 px-4 py-2 border-2 border-orange-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                           placeholder="Ketik: RESET2025"
                           autocomplete="off"
                           required>
                    <p class="text-xs text-gray-500 mt-1">Ketik kode konfirmasi dengan huruf kapital semua</p>
                </div>

                <!-- Step 2: Secret Code -->
                <div class="border-2 border-red-200 rounded-lg p-4 bg-red-50">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock mr-1"></i>
                        Step 2 - Masukkan Kode Rahasia IT
                    </label>
                    <input type="password" 
                           name="secret_code" 
                           id="secret_code"
                           class="w-full md:w-1/2 px-4 py-2 border-2 border-red-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
                           placeholder="Masukkan kode rahasia IT"
                           autocomplete="off"
                           maxlength="4"
                           required>
                    <p class="text-xs text-gray-500 mt-1">Masukkan 4 digit kode rahasia yang hanya diketahui IT</p>
                </div>
                
                <!-- Understanding Checkbox -->
                <div class="flex items-start">
                    <input type="checkbox" 
                           id="understand_checkbox" 
                           class="mt-1 mr-3 w-5 h-5"
                           required>
                    <label for="understand_checkbox" class="text-sm text-gray-700">
                        Saya memahami bahwa tindakan ini akan <strong class="text-red-600">MENGHAPUS SEMUA DATA</strong> 
                        color system dan <strong class="text-red-600">TIDAK DAPAT DIBATALKAN</strong>. 
                        Saya telah melakukan backup database jika diperlukan dan memiliki akses kode rahasia IT yang valid.
                    </label>
                </div>
                
                <!-- Action Buttons -->
                <div class="flex space-x-3 pt-4">
                    <button type="submit" 
                            name="confirm_reset"
                            class="px-6 py-3 bg-red-600 text-white font-bold rounded-md hover:bg-red-700 transition-colors flex items-center">
                        <i class="fas fa-exclamation-triangle mr-2"></i>RESET SYSTEM SEKARANG
                    </button>
                    
                    <a href="dashboard_it.php" 
                       class="px-6 py-3 bg-gray-600 text-white font-bold rounded-md hover:bg-gray-700 transition-colors flex items-center">
                        <i class="fas fa-times mr-2"></i>Batal
                    </a>
                </div>
            </div>
        </form>
    </div>
    
    <!-- Current Data Statistics -->
    <div class="bg-white rounded-lg shadow-md p-6 mt-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">
            <i class="fas fa-chart-bar mr-2"></i>Statistik Data Saat Ini
        </h3>
        
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
            <?php
            $tables = [
                'master_color' => 'Master Color',
                'master_color_panel' => 'Color Panel', 
                'color_stock_items' => 'Stock Items',
                'stock_transactions' => 'Transactions',
                'color_approvals' => 'Approvals'
            ];
            
            foreach ($tables as $table => $label) {
                $result = $conn->query("SELECT COUNT(*) as count FROM $table");
                $count = $result ? $result->fetch_assoc()['count'] : 0;
                echo "<div class='bg-blue-50 p-4 rounded text-center border border-blue-200'>
                        <div class='text-3xl font-bold text-blue-600'>" . number_format($count) . "</div>
                        <div class='text-sm text-gray-600'>$label</div>
                      </div>";
            }
            ?>
        </div>
        
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mt-4">
            <?php
            $more_tables = [
                'color_panel_components' => 'Panel Components',
                'transaction_items' => 'Transaction Items',
                'approval_history' => 'Approval History',
                'expired_code_history' => 'Expired History',
                'renew_code_history' => 'Renew History'
            ];
            
            foreach ($more_tables as $table => $label) {
                $result = $conn->query("SELECT COUNT(*) as count FROM $table");
                $count = $result ? $result->fetch_assoc()['count'] : 0;
                echo "<div class='bg-gray-50 p-4 rounded text-center border border-gray-200'>
                        <div class='text-2xl font-bold text-gray-600'>" . number_format($count) . "</div>
                        <div class='text-xs text-gray-500'>$label</div>
                      </div>";
            }
            ?>
        </div>
    </div>
    
</main>

<script>
function confirmReset() {
    var confirmCode = document.getElementById('confirmation_code').value;
    var secretCode = document.getElementById('secret_code').value;
    var checkbox = document.getElementById('understand_checkbox').checked;
    
    // Validation checks
    if (confirmCode !== 'RESET2025') {
        alert('Kode konfirmasi salah! Harus: RESET2025');
        document.getElementById('confirmation_code').focus();
        return false;
    }
    
    if (secretCode !== '4444') {
        alert('Kode rahasia salah! Silakan masukkan kode yang benar.');
        document.getElementById('secret_code').focus();
        return false;
    }
    
    if (!checkbox) {
        alert('Anda harus mencentang checkbox konfirmasi!');
        return false;
    }
    
    // Final confirmation dialogs
    var finalConfirm = confirm(
        '⚠️ KONFIRMASI TERAKHIR ⚠️\n\n' +
        'Anda akan menghapus SEMUA DATA color system!\n\n' +
        'Verifikasi ganda telah berhasil:\n' +
        '✓ Kode Konfirmasi: RESET2025\n' +
        '✓ Kode Rahasia IT: Verified\n\n' +
        'Tindakan ini TIDAK DAPAT DIBATALKAN!\n\n' +
        'Apakah Anda yakin ingin melanjutkan?'
    );
    
    if (finalConfirm) {
        var doubleConfirm = confirm(
            'KONFIRMASI TERAKHIR!\n\n' +
            'Semua data akan hilang:\n' +
            '• Master Color\n' +
            '• Color Panels\n' +
            '• Stock Items\n' +
            '• Transactions\n' +
            '• Approvals\n' +
            '• History Data\n\n' +
            'Klik OK untuk MENGHAPUS SEMUA DATA.\n' +
            'Klik Cancel untuk membatalkan.'
        );
        
        if (doubleConfirm) {
            // Show loading state
            var submitBtn = document.querySelector('button[name="confirm_reset"]');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>PROCESSING...';
            submitBtn.disabled = true;
            
            return true;
        }
    }
    
    return false;
}

// Security measures
document.getElementById('confirmation_code').addEventListener('paste', function(e) {
    e.preventDefault();
    alert('Copy-paste tidak diperbolehkan untuk kode konfirmasi. Silakan ketik manual untuk keamanan.');
});

document.getElementById('secret_code').addEventListener('paste', function(e) {
    e.preventDefault();
    alert('Copy-paste tidak diperbolehkan untuk kode rahasia. Silakan ketik manual untuk keamanan.');
});

// Numeric only for secret code
document.getElementById('secret_code').addEventListener('input', function(e) {
    this.value = this.value.replace(/[^0-9]/g, '');
});

// Auto-focus next field when confirmation code is correct
document.getElementById('confirmation_code').addEventListener('blur', function() {
    if (this.value === 'RESET2025') {
        document.getElementById('secret_code').focus();
    }
});
</script>

<?php include '../template_it/footer.php'; ?>