<?php
session_start();

// Check authentication first
if (!isset($_SESSION['username'], $_SESSION['database'], $_SESSION['userid']) ||
    empty($_SESSION['username']) || empty($_SESSION['database']) || empty($_SESSION['userid'])) {
    header("Location: login.html");
    exit();
}

require_once 'connection.php';
$stmt = $pdo->prepare("SELECT userid FROM USERS WHERE userid = ? AND username = ? AND databasename = ?");
$stmt->execute([$_SESSION['userid'], $_SESSION['username'], $_SESSION['database']]);

if (!$stmt->fetch()) {
    header("Location: login.html");
    exit();
}

// ⭐ CHECK ROLE BEFORE INCLUDING CONFIG
if ($_SESSION['role'] != 'Admin') {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Access Denied</title>
      <script>
        window.onload = function () {
          alert("You do not have permissions to edit. Ask your admin for uploading the data.");
          let countdown = 3;
          const timerElement = document.getElementById("timer");
          timerElement.innerText = countdown;
          const interval = setInterval(() => {
            countdown--;
            timerElement.innerText = countdown;
            if (countdown === 0) {
              clearInterval(interval);
              window.location.href = "landing.php";
            }
          }, 1000);
        }
      </script>
    </head>
    <body>
      <h2>You will be redirected in <span id="timer">3</span> seconds...</h2>
    </body>
    </html>
    <?php
    exit(); // ⭐ STOP HERE - Don't load config or continue
}

// Load dashboard configurations from external file (only for Admin)
$dashboardConfigs = include 'dashboard_config.php';

// Get dashboard type from URL parameter
$dashboardType = isset($_GET['type']) ? $_GET['type'] : 'finance';

// Validate dashboard type
if (!isset($dashboardConfigs[$dashboardType])) {
    $dashboardType = 'finance';
}

$config = $dashboardConfigs[$dashboardType];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="<?php echo $config['favicon'] ?>" type="image/x-icon">
    <title><?php echo $config['title']; ?></title>
    <link rel="stylesheet" href="main.css">
</head>

<body class="uploaderphp" onclick="hideNavigation()">
    <?php include "navigation.html" ?>
    <button class="menuButton" id="menu" title="Menu" onclick="event.stopPropagation(); toggleNavigation()">☰</button>

    <button class="back-btn" onclick="window.history.back()">← Back</button>

    <div class="container">
        <div class="header">
            <h1><?php echo $config['dashboardTitle']; ?></h1>
            <p><?php echo $config['description']; ?></p>
        </div>

        <div class="content">
            <!-- Dashboard Statistics -->
            <div class="stats-section">
                <h3>📊 Dashboard Overview</h3>
                <div class="stats-grid">
                    <div class="stat-item">
                        <span class="stat-number"><?php echo count($config['columns']); ?></span>
                        <span class="stat-label">Total Columns</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number"><?php echo count(array_filter($config['columns'], function ($col) {
                                                        return $col['required'];
                                                    })); ?></span>
                        <span class="stat-label">Required Fields</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number"><?php echo ucfirst($dashboardType); ?></span>
                        <span class="stat-label">Active Dashboard</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number"><?php echo $config['table']; ?></span>
                        <span class="stat-label">Target Table</span>
                    </div>
                </div>
            </div>

            <!-- Dashboard Selector -->
            <div class="dashboard-selector">
                <h3>📂 Select Dashboard Type</h3>
                <p>Choose the type of data you want to upload:</p>
                <div class="dashboard-tabs">
                    <?php foreach ($dashboardConfigs as $key => $dashConfig): ?>
                        <a href="?type=<?php echo $key; ?>"
                            class="dashboard-tab <?php echo ($key === $dashboardType) ? 'active' : ''; ?>">
                            <?php echo preg_replace('/[^\w\s]/', '', $dashConfig['title']); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Template Information -->
            <div class="template-section">
                <h3>📋 Column Requirements for <?php echo ucfirst($dashboardType); ?> Dashboard</h3>
                <p>Your Excel/CSV file must contain the following columns in this exact order: &nbsp;&nbsp;&nbsp;<span onclick="window.location.href='<?php echo $config['sampleFileLocation'] ?? '#' ?>';">Sample Data Here</span></p>
                <div class="template-columns">
                    <?php foreach ($config['columns'] as $column => $details): ?>
                        <div class="column-item <?php echo $details['required'] ? 'required' : ''; ?>">
                            <div class="column-name"><?php echo $details['display']; ?></div>
                            <div class="column-details">Column: <code><?php echo $column; ?></code></div>
                            <div class="column-details">
                                <span class="column-type"><?php echo strtoupper($details['type']); ?></span>
                                <?php if ($details['required']): ?>
                                    <span style="color: #dc3545; font-weight: 600;">• Required</span>
                                <?php else: ?>
                                    <span style="color: #28a745;">• Optional</span>
                                <?php endif; ?>
                            </div>
                            <?php if (isset($details['validation'])): ?>
                                <div class="column-details" style="color: #0066cc;">
                                    Validation:
                                    <?php if (isset($details['validation']['min'])): ?>
                                        Min: <?php echo $details['validation']['min']; ?>
                                    <?php endif; ?>
                                    <?php if (isset($details['validation']['max'])): ?>
                                        Max: <?php echo $details['validation']['max']; ?>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            <?php if (isset($details['default'])): ?>
                                <div class="column-details" style="color: #666;">
                                    Default: <?php echo $details['default']; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="legend">
                    <div class="legend-item">
                        <div class="legend-color required-color"></div>
                        <span>Required Fields (Must have data)</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color optional-color"></div>
                        <span>Optional Fields (Can be empty)</span>
                    </div>
                </div>
                <p style="margin-top: 15px;"><strong>📝 Important:</strong> The first row should contain column headers. Data should start from row 2. Make sure column names match exactly as shown above.</p>
            </div>

            <!-- Upload Section -->
            <div class="upload-section">
                <div class="upload-box" id="uploadBox" onclick="document.getElementById('fileInput').click()">
                    <div class="upload-icon">📤</div>
                    <div class="upload-text">Click to select files</div>
                    <div class="upload-subtext">or drag and drop your files here</div>
                    <div class="supported-formats">📄 Supported formats: .csv</div>
                </div>

                <input type="file" id="fileInput" class="file-input" accept=".csv" multiple>

                <div class="file-info" id="fileInfo">
                    <h4>📁 Selected Files</h4>
                    <ul class="file-list" id="fileDetails"></ul>
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    <button class="btn" id="uploadBtn" onclick="uploadFiles()">🚀 Upload Files</button>
                </div>
            </div>

            <!-- Alerts -->
            <div class="alert alert-success" id="successAlert"></div>
            <div class="alert alert-error" id="errorAlert"></div>
        </div>
    </div>

    <script>
        let selectedFiles = [];
        const dashboardType = '<?php echo $dashboardType; ?>';

        // File input change handler
        document.getElementById('fileInput').addEventListener('change', function(e) {
            handleFiles(e.target.files);
        });

        // Drag and drop handlers
        const uploadBox = document.getElementById('uploadBox');

        uploadBox.addEventListener('dragover', function(e) {
            e.preventDefault();
            uploadBox.classList.add('dragover');
        });

        uploadBox.addEventListener('dragleave', function(e) {
            e.preventDefault();
            uploadBox.classList.remove('dragover');
        });

        uploadBox.addEventListener('drop', function(e) {
            e.preventDefault();
            uploadBox.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });

        function handleFiles(files) {
            selectedFiles = Array.from(files).filter(file =>
                file.name.endsWith('.xlsx') || file.name.endsWith('.xls') || file.name.endsWith('.csv')
            );

            if (selectedFiles.length === 0) {
                showAlert('error', 'Please select valid Excel or CSV files (.xlsx, .xls, or .csv)');
                return;
            }

            const fileDetails = document.getElementById('fileDetails');
            const fileInfo = document.getElementById('fileInfo');

            fileDetails.innerHTML = '';
            selectedFiles.forEach(file => {
                const li = document.createElement('li');
                li.innerHTML = `
                <span>${file.name}</span>
                <span class="file-size">${(file.size / 1024 / 1024).toFixed(2)} MB</span>
            `;
                fileDetails.appendChild(li);
            });

            fileInfo.style.display = 'block';
        }

        function uploadFiles() {
            if (selectedFiles.length === 0) {
                showAlert('error', 'Please select files first');
                return;
            }

            const uploadBtn = document.getElementById('uploadBtn');
            const progressFill = document.getElementById('progressFill');

            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '⏳ Uploading...';

            const formData = new FormData();
            selectedFiles.forEach((file, index) => {
                formData.append(`files[${index}]`, file);
            });

            // Add dashboard type to form data
            formData.append('dashboard_type', dashboardType);

            fetch('process_universal_upload.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAlert('success', `🎉 Success! Uploaded ${data.recordsInserted} records from ${data.filesProcessed} files to ${data.dashboardType} dashboard.`);
                        resetUpload();
                    } else {
                        showAlert('error', '❌ ' + (data.message || 'Upload failed'));
                        if (data.warnings && data.warnings.length > 0) {
                            console.log('Warnings:', data.warnings);
                        }
                    }
                })
                .catch(error => {
                    showAlert('error', '❌ Upload failed: ' + error.message);
                })
                .finally(() => {
                    uploadBtn.disabled = false;
                    uploadBtn.innerHTML = '🚀 Upload Files';
                    progressFill.style.width = '0%';
                });

            // Simulate progress with animation
            animateProgress();
        }

        function animateProgress() {
            const progressFill = document.getElementById('progressFill');
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 15 + 5;
                if (progress >= 95) {
                    progress = 95;
                    clearInterval(progressInterval);
                }
                progressFill.style.width = progress + '%';
            }, 300);
        }

        function showAlert(type, message) {
            const alertId = type === 'success' ? 'successAlert' : 'errorAlert';
            const alert = document.getElementById(alertId);

            // Hide other alerts
            document.getElementById('successAlert').style.display = 'none';
            document.getElementById('errorAlert').style.display = 'none';

            alert.innerHTML = message;
            alert.style.display = 'block';

            // Auto hide after 8 seconds
            setTimeout(() => {
                alert.style.display = 'none';
            }, 8000);
        }

        function resetUpload() {
            selectedFiles = [];
            document.getElementById('fileInput').value = '';
            document.getElementById('fileInfo').style.display = 'none';
            document.getElementById('progressFill').style.width = '0%';
        }

        // Add some interactive animations
        document.addEventListener('DOMContentLoaded', function() {
            // Animate stats on page load
            const statNumbers = document.querySelectorAll('.stat-number');
            statNumbers.forEach((stat, index) => {
                setTimeout(() => {
                    stat.style.transform = 'scale(1.1)';
                    setTimeout(() => {
                        stat.style.transform = 'scale(1)';
                    }, 200);
                }, index * 100);
            });
        });
    </script>
</body>

</html>