<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SESSION['role_id'] != 1) {
    $_SESSION['error'] = 'Only Super Admin can access demo data management.';
    header('Location: ' . getRedirectUrl());
    exit;
}

$pdo = getDB();

// Get demo data counts
$counts = [];
$tables = [
    'customers' => 'Demo Customers',
    'suppliers' => 'Demo Suppliers',
    'categories' => 'Demo Categories',
    'brands' => 'Demo Brands',
    'products' => 'Demo Products',
    'product_imei' => 'Demo IMEI Records',
    'purchases' => 'Demo Purchases',
    'sales_invoices' => 'Demo Sales Invoices',
    'repair_jobs' => 'Demo Repair Jobs',
    'payments' => 'Demo Payments'
];

foreach ($tables as $table => $label) {
    $stmt = $pdo->query("SELECT COUNT(*) FROM $table WHERE is_demo = 1");
    $counts[$table] = ['label' => $label, 'count' => (int)$stmt->fetchColumn()];
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <h4 class="page-title"><i class="fas fa-database me-2"></i>Demo Data Management</h4>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>Warning:</strong> Demo data is for testing only. Removing demo data will delete only records marked as demo. Real business data will not be affected.
        </div>

        <div class="row mb-4">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header"><i class="fas fa-chart-simple me-2"></i>Current Demo Data Summary</div>
                    <div class="card-body">
                        <div class="row">
                            <?php foreach ($counts as $table => $info): ?>
                            <div class="col-md-4 col-sm-6 mb-3">
                                <div class="d-flex justify-content-between align-items-center p-3 border rounded">
                                    <span><?= htmlspecialchars($info['label']) ?></span>
                                    <span class="badge bg-<?= $info['count'] > 0 ? 'primary' : 'secondary' ?> fs-6"><?= $info['count'] ?></span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card mb-3">
                    <div class="card-header bg-success text-white"><i class="fas fa-plus-circle me-2"></i>Add Demo Data</div>
                    <div class="card-body text-center">
                        <p class="text-muted">Insert sample demo data for testing all modules.</p>
                        <button type="button" class="btn btn-success btn-lg w-100" data-bs-toggle="modal" data-bs-target="#addDemoModal">
                            <i class="fas fa-plus me-2"></i>Add Demo Data
                        </button>
                    </div>
                </div>
                <div class="card">
                    <div class="card-header bg-danger text-white"><i class="fas fa-trash-alt me-2"></i>Remove Demo Data</div>
                    <div class="card-body text-center">
                        <p class="text-muted">Remove all records marked as demo data.</p>
                        <button type="button" class="btn btn-danger btn-lg w-100" data-bs-toggle="modal" data-bs-target="#removeDemoModal">
                            <i class="fas fa-trash-alt me-2"></i>Remove All Demo Data
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Demo Data Confirmation Modal -->
<div class="modal fade" id="addDemoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Add Demo Data</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>This will insert sample demo data including:</p>
                <ul>
                    <li>Categories (Mobile Phones, Accessories, Spare Parts)</li>
                    <li>Brands (Apple, Samsung, Xiaomi, Oppo, Vivo, JBL, Baseus)</li>
                    <li>Suppliers (3 demo suppliers)</li>
                    <li>Customers (5 demo customers)</li>
                    <li>Products (16 demo products with IMEI records)</li>
                    <li>Purchases (3 demo purchase orders)</li>
                    <li>Repair Jobs (5 demo repair jobs)</li>
                    <li>Payments (4 demo payment records)</li>
                </ul>
                <p class="fw-bold text-success">All demo data will be marked and can be safely removed later.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="confirmAddDemo"><i class="fas fa-plus me-1"></i>Add Demo Data</button>
            </div>
        </div>
    </div>
</div>

<!-- Remove Demo Data Confirmation Modal -->
<div class="modal fade" id="removeDemoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-trash-alt me-2"></i>Remove All Demo Data</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Warning:</strong> This action cannot be undone!
                </div>
                <p>Are you sure you want to remove all demo data? This will delete only records marked as demo. Real data will not be removed.</p>
                <div class="form-check mb-3">
                    <input type="checkbox" class="form-check-input" id="confirmRemoveCheck">
                    <label class="form-check-label" for="confirmRemoveCheck">
                        I understand this will remove all demo data.
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmRemoveDemo" disabled><i class="fas fa-trash-alt me-1"></i>Remove All Demo Data</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#confirmRemoveCheck').on('change', function() {
        $('#confirmRemoveDemo').prop('disabled', !this.checked);
    });

    $('#confirmAddDemo').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Adding...');
        $.ajax({
            url: 'add_demo_data.php',
            type: 'POST',
            dataType: 'json',
            success: function(resp) {
                if (resp.success) {
                    $('#addDemoModal').modal('hide');
                    location.reload();
                } else {
                    alert(resp.message || 'Failed to add demo data.');
                    btn.prop('disabled', false).html('<i class="fas fa-plus me-1"></i>Add Demo Data');
                }
            },
            error: function() {
                alert('An error occurred while adding demo data.');
                btn.prop('disabled', false).html('<i class="fas fa-plus me-1"></i>Add Demo Data');
            }
        });
    });

    $('#confirmRemoveDemo').on('click', function() {
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Removing...');
        $.ajax({
            url: 'remove_demo_data.php',
            type: 'POST',
            dataType: 'json',
            success: function(resp) {
                if (resp.success) {
                    $('#removeDemoModal').modal('hide');
                    location.reload();
                } else {
                    alert(resp.message || 'Failed to remove demo data.');
                    btn.prop('disabled', false).html('<i class="fas fa-trash-alt me-1"></i>Remove All Demo Data');
                    $('#confirmRemoveCheck').prop('checked', false);
                }
            },
            error: function() {
                alert('An error occurred while removing demo data.');
                btn.prop('disabled', false).html('<i class="fas fa-trash-alt me-1"></i>Remove All Demo Data');
                $('#confirmRemoveCheck').prop('checked', false);
            }
        });
    });
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
