<?php
/**
 * Bulk Import Remedies
 * Import multiple remedies from CSV file
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';
$importedCount = 0;
$skippedCount = 0;

// Handle file upload and import
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['csv_file'])) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $file = $_FILES['csv_file'];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $error = "File upload failed.";
        } elseif ($file['type'] != 'text/csv' && pathinfo($file['name'], PATHINFO_EXTENSION) != 'csv') {
            $error = "Please upload a valid CSV file";
        } else {
            $handle = fopen($file['tmp_name'], 'r');
            if ($handle !== false) {
                // Get header row
                $header = fgetcsv($handle);
                
                // Expected headers: name, abbreviation, materia_medica, clinical_indications, better_modalities, worse_modalities
                beginTransaction();
                
                try {
                    while (($data = fgetcsv($handle)) !== false) {
                        $name = trim($data[0] ?? '');
                        $abbreviation = trim($data[1] ?? '');
                        $materiaMedica = trim($data[2] ?? '');
                        $clinicalIndications = trim($data[3] ?? '');
                        $betterModalities = array_filter(array_map('trim', explode(';', $data[4] ?? '')));
                        $worseModalities = array_filter(array_map('trim', explode(';', $data[5] ?? '')));
                        
                        if (empty($name)) {
                            $skippedCount++;
                            continue;
                        }
                        
                        // Check if remedy already exists
                        $stmt = $pdo->prepare("SELECT id FROM remedies WHERE name = ?");
                        $stmt->execute([$name]);
                        if ($stmt->fetch()) {
                            $skippedCount++;
                            continue;
                        }
                        
                        $modalities = json_encode([
                            'better' => array_values($betterModalities),
                            'worse' => array_values($worseModalities)
                        ]);
                        
                        $stmt = $pdo->prepare("INSERT INTO remedies (name, abbreviation, materia_medica_text, clinical_indications, modalities) 
                                              VALUES (?, ?, ?, ?, ?)");
                        $stmt->execute([$name, $abbreviation, $materiaMedica, $clinicalIndications, $modalities]);
                        $importedCount++;
                    }
                    
                    commitTransaction();
                    $success = "Import completed! $importedCount remedies imported, $skippedCount skipped.";
                    
                } catch (Exception $e) {
                    rollbackTransaction();
                    $error = "Import failed: " . $e->getMessage();
                }
                
                fclose($handle);
            }
        }
    }
}

// Generate sample CSV template
if (isset($_GET['template'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="remedies_template.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['name', 'abbreviation', 'materia_medica', 'clinical_indications', 'better_modalities', 'worse_modalities']);
    fputcsv($output, ['Sulphur', 'Sulph', 'Great remedy for chronic diseases...', 'Skin affections, burning', 'Open air; Cold drinks', 'Warmth; Bathing; Night']);
    fputcsv($output, ['Lycopodium', 'Lyc', 'Digestive complaints...', 'Bloating, right-sided', 'Warm food; Uncovering', '4-8 PM; Cold drinks']);
    fclose($output);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bulk Import Remedies - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .drop-zone {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .drop-zone:hover {
            border-color: #3498db;
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">Dashboard</a>
                    <a class="nav-link" href="../doctors/index.php">Doctors</a>
                    <a class="nav-link" href="../subscriptions/index.php">Subscriptions</a>
                    <a class="nav-link" href="../rubrics/index.php">Rubrics</a>
                    <a class="nav-link active" href="index.php">Remedies</a>
                    <a class="nav-link" href="../../logout.php">Logout</a>
                </nav>
            </div>
            
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <h4 class="mb-0">Bulk Import Remedies</h4>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data">
                                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                        
                                        <div class="drop-zone" id="dropZone">
                                            <i class="fas fa-cloud-upload-alt fa-3x mb-3"></i>
                                            <p>Drag & drop CSV file here or click to browse</p>
                                            <input type="file" name="csv_file" id="csvFile" accept=".csv" style="display: none;">
                                            <button type="button" class="btn btn-primary" onclick="document.getElementById('csvFile').click()">
                                                Browse Files
                                            </button>
                                        </div>
                                        
                                        <div class="mt-3">
                                            <button type="submit" class="btn btn-primary">Start Import</button>
                                            <a href="?template=1" class="btn btn-info">Download Template</a>
                                            <a href="index.php" class="btn btn-secondary">Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">CSV Format Guide</div>
                                <div class="card-body">
                                    <p><strong>Columns:</strong></p>
                                    <ol>
                                        <li>name (required)</li>
                                        <li>abbreviation</li>
                                        <li>materia_medica</li>
                                        <li>clinical_indications</li>
                                        <li>better_modalities (semicolon-separated)</li>
                                        <li>worse_modalities (semicolon-separated)</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('csvFile');
        
        dropZone.addEventListener('click', () => fileInput.click());
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('border-primary');
        });
        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('border-primary');
        });
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('border-primary');
            fileInput.files = e.dataTransfer.files;
        });
    </script>
</body>
</html>