<?php
/**
 * Import Cases from CSV
 * Bulk import cases from CSV file
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$error = '';
$success = '';
$importedCount = 0;

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['csv_file'])) {
    $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) {
            $header = fgetcsv($handle); // Skip header
            
            beginTransaction();
            try {
                while (($data = fgetcsv($handle)) !== false) {
                    $patientName = trim($data[0] ?? '');
                    $patientMobile = trim($data[1] ?? '');
                    $chiefComplaint = trim($data[2] ?? '');
                    $caseHistory = trim($data[3] ?? '');
                    $physicalGenerals = trim($data[4] ?? '');
                    $mentalEmotional = trim($data[5] ?? '');
                    $modalities = trim($data[6] ?? '');
                    
                    if (empty($patientName) || empty($patientMobile)) {
                        continue;
                    }
                    
                    $stmt = $pdo->prepare("INSERT INTO cases (user_id, patient_name, patient_mobile, chief_complaint, 
                                          case_history, physical_generals, mental_emotional, modalities, status) 
                                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active')");
                    $stmt->execute([$userId, $patientName, $patientMobile, $chiefComplaint, 
                                   $caseHistory, $physicalGenerals, $mentalEmotional, $modalities]);
                    $importedCount++;
                }
                commitTransaction();
                $success = "Import completed! $importedCount cases imported.";
            } catch (Exception $e) {
                rollbackTransaction();
                $error = "Import failed: " . $e->getMessage();
            }
            fclose($handle);
        }
    }
}

if (isset($_GET['template'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="cases_template.csv"');
    $output = fopen('php://output', 'w');
    fputcsv($output, ['patient_name', 'mobile', 'chief_complaint', 'case_history', 'physical_generals', 'mental_emotional', 'modalities']);
    fputcsv($output, ['John Doe', '9876543210', 'Headache since 2 days', 'History of migraines', 'Thermal: Hot', 'Irritable', 'Worse: Light, Better: Dark']);
    fclose($output);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head><title>Import Cases</title><link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<div class="container mt-5"><div class="row"><div class="col-md-8 mx-auto"><div class="card"><div class="card-header bg-info text-white"><h4>Import Cases from CSV</h4></div>
<div class="card-body">
<?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; ?>
<form method="POST" enctype="multipart/form-data"><div class="mb-3"><label>CSV File</label><input type="file" name="csv_file" class="form-control" accept=".csv" required></div>
<button type="submit" class="btn btn-primary">Import Cases</button><a href="?template=1" class="btn btn-info">Download Template</a><a href="list.php" class="btn btn-secondary">Cancel</a></form>
<hr><div class="alert alert-info"><strong>CSV Format:</strong> patient_name, mobile, chief_complaint, case_history, physical_generals, mental_emotional, modalities</div>
</div></div></div></div></div>
</body>
</html>