<?php
require_once "config.php";
require_once "auth.php";
requireLogin();
requireAdmin();

$eurToDinRate = 117.5;

function parseNaplata($naplata) {
    global $eurToDinRate;
    
    if (empty(trim($naplata))) {
        return ['cena' => null, 'placanje' => null, 'napomena' => null];
    }
    
    $naplata = trim($naplata);
    $original = $naplata;
    $cena = null;
    $placanje = null;
    $napomena = null;
    
    if (preg_match('/\b(\d+)\s*pax\b/i', $naplata)) {
        $napomena = $original;
        return [
            'cena' => null,
            'placanje' => null,
            'napomena' => $napomena
        ];
    }
    
    $isEur = preg_match('/\b(e|evra|eur|euro|euros)\b/i', $naplata);
    $isDin = preg_match('/\b(din|dinara|dinari|rsd)\b/i', $naplata);
    $isKes = preg_match('/\b(kes|gotovina|cash)\b/i', $naplata);
    $isRacun = preg_match('/\b(na\s+racun|racun|faktura|invoice)\b/i', $naplata);
    
    if (preg_match('/(\d+(?:[.,]\d+)?)\s*(?:hiljada|hilj|k|thousand)/i', $naplata, $matches)) {
        $amount = floatval(str_replace(',', '.', $matches[1])) * 1000;
        
        if ($isEur) {
            $cena = $amount * $eurToDinRate;
        } else {
            $cena = $amount;
        }
        $napomena = $original;
    } elseif (preg_match('/(\d+(?:[.,]\d+)?)/', $naplata, $matches)) {
        $amount = floatval(str_replace(',', '.', $matches[1]));
        
        if ($isEur) {
            $cena = $amount * $eurToDinRate;
        } else {
            $cena = $amount;
        }
        $napomena = $original;
    } else {
        $napomena = $original;
    }
    
    if ($isKes) {
        $placanje = 'Gotovina';
    } elseif ($isRacun) {
        $placanje = 'Faktura';
    } elseif ($cena !== null) {
        $placanje = 'Gotovina';
    }
    
    return [
        'cena' => $cena !== null ? number_format($cena, 2, '.', '') : null,
        'placanje' => $placanje,
        'napomena' => $napomena
    ];
}

function findKomitent($naziv, $conn) {
    if (empty(trim($naziv))) {
        return null;
    }
    
    $naziv = trim($naziv);
    $stmt = $conn->prepare("SELECT id, naziv FROM komitenti WHERE LOWER(TRIM(naziv)) = LOWER(TRIM(?))");
    $stmt->bind_param("s", $naziv);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return $row;
    }
    
    return null;
}

function findVozac($ime, $conn) {
    if (empty(trim($ime))) {
        return null;
    }
    
    $ime = trim($ime);
    $stmt = $conn->prepare("SELECT id, name FROM users WHERE role = 'vozac' AND LOWER(TRIM(name)) = LOWER(TRIM(?))");
    $stmt->bind_param("s", $ime);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return $row;
    }
    
    return null;
}

function parseDate($dateStr, $mesecGodina = null) {
    if (empty(trim($dateStr))) {
        return null;
    }
    
    $dateStr = trim($dateStr);
    
    if (preg_match('/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/', $dateStr, $matches)) {
        $dan = $matches[1];
        $mesec = $matches[2];
        $godina = $matches[3];
        return sprintf('%04d-%02d-%02d', $godina, $mesec, $dan);
    }
    
    return null;
}

function parseTime($timeStr) {
    if (empty(trim($timeStr))) {
        return null;
    }
    
    $timeStr = trim($timeStr);
    
    if (preg_match('/^(\d{1,2}):(\d{2})$/', $timeStr, $matches)) {
        return sprintf('%02d:%02d:00', $matches[1], $matches[2]);
    }
    
    return null;
}

$error = null;
$previewData = null;

if (isset($_SESSION['import_error'])) {
    $error = $_SESSION['import_error'];
    unset($_SESSION['import_error']);
}

if (isset($_GET['success']) && isset($_SESSION['import_success'])) {
    $imported = $_SESSION['import_imported'] ?? 0;
    $skipped = $_SESSION['import_skipped'] ?? 0;
    $importErrors = $_SESSION['import_errors'] ?? [];
    unset($_SESSION['import_success'], $_SESSION['import_imported'], $_SESSION['import_skipped'], $_SESSION['import_errors']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    if ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Greška prilikom upload-a fajla';
    } else {
        $csvFile = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($csvFile, 'r');
        
        if ($handle === false) {
            $error = 'Greška prilikom čitanja fajla';
        } else {
            $header = fgetcsv($handle, 0, ',', '"', '\\');
            if ($header === false) {
                $error = 'Greška prilikom čitanja header-a';
                fclose($handle);
            } else {
                $headerMap = [];
                foreach ($header as $index => $col) {
                    $col = trim($col);
                    if (stripos($col, 'Mesec') !== false || stripos($col, 'Godina') !== false) {
                        $headerMap['mesec_godina'] = $index;
                    } elseif (stripos($col, 'Datum') !== false) {
                        $headerMap['datum'] = $index;
                    } elseif (stripos($col, 'Vreme') !== false) {
                        $headerMap['vreme'] = $index;
                    } elseif (stripos($col, 'Broj leta') !== false || stripos($col, 'Broj_leta') !== false) {
                        $headerMap['broj_leta'] = $index;
                    } elseif (stripos($col, 'Od') !== false) {
                        $headerMap['od'] = $index;
                    } elseif (stripos($col, 'Do') !== false) {
                        $headerMap['do'] = $index;
                    } elseif (stripos($col, 'Ime') !== false) {
                        $headerMap['ime'] = $index;
                    } elseif (stripos($col, 'Vozilo') !== false) {
                        $headerMap['vozilo'] = $index;
                    } elseif (stripos($col, 'Komitent') !== false) {
                        $headerMap['komitent'] = $index;
                    } elseif (stripos($col, 'Vozac') !== false) {
                        $headerMap['vozac'] = $index;
                    } elseif (stripos($col, 'Naplata') !== false) {
                        $headerMap['naplata'] = $index;
                    }
                }
                
                $voznje = [];
                $komitentiFound = [];
                $komitentiToCreate = [];
                $vozaciFound = [];
                $vozaciToCreate = [];
                $errors = [];
                
                $rowNum = 1;
                while (($row = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
                    $rowNum++;
                    
                    if (count($row) < 5) {
                        continue;
                    }
                    
                    $mesecGodina = isset($headerMap['mesec_godina']) && isset($row[$headerMap['mesec_godina']]) ? trim($row[$headerMap['mesec_godina']]) : null;
                    $datumStr = isset($headerMap['datum']) && isset($row[$headerMap['datum']]) ? trim($row[$headerMap['datum']]) : '';
                    $vremeStr = isset($headerMap['vreme']) && isset($row[$headerMap['vreme']]) ? trim($row[$headerMap['vreme']]) : '';
                    $broj_leta = isset($headerMap['broj_leta']) && isset($row[$headerMap['broj_leta']]) ? trim($row[$headerMap['broj_leta']]) : null;
                    $od = isset($headerMap['od']) && isset($row[$headerMap['od']]) ? trim($row[$headerMap['od']]) : '';
                    $do = isset($headerMap['do']) && isset($row[$headerMap['do']]) ? trim($row[$headerMap['do']]) : '';
                    $ime = isset($headerMap['ime']) && isset($row[$headerMap['ime']]) ? trim($row[$headerMap['ime']]) : '';
                    $vozilo = isset($headerMap['vozilo']) && isset($row[$headerMap['vozilo']]) ? trim($row[$headerMap['vozilo']]) : '';
                    $komitentNaziv = isset($headerMap['komitent']) && isset($row[$headerMap['komitent']]) ? trim($row[$headerMap['komitent']]) : '';
                    $vozacIme = isset($headerMap['vozac']) && isset($row[$headerMap['vozac']]) ? trim($row[$headerMap['vozac']]) : '';
                    $naplataStr = isset($headerMap['naplata']) && isset($row[$headerMap['naplata']]) ? trim($row[$headerMap['naplata']]) : '';
                    
                    if (empty($datumStr) && empty($vremeStr) && empty($od) && empty($do) && empty($ime)) {
                        continue;
                    }
                    
                    $datum = parseDate($datumStr, $mesecGodina);
                    $vreme = parseTime($vremeStr);
                    
                    $missingFields = [];
                    if (!$datum) $missingFields[] = 'Datum';
                    if (!$vreme) $missingFields[] = 'Vreme';
                    if (empty($od)) $missingFields[] = 'Od';
                    if (empty($do)) $missingFields[] = 'Do';
                    if (empty($ime)) $missingFields[] = 'Ime';
                    if (empty($vozilo)) $missingFields[] = 'Vozilo';
                    
                    if (count($missingFields) > 0) {
                        $errors[] = "Red $rowNum: Nedostaju obavezna polja: " . implode(', ', $missingFields);
                        continue;
                    }
                    
                    $komitent = null;
                    $komitent_id = null;
                    if (!empty($komitentNaziv)) {
                        $komitent = findKomitent($komitentNaziv, $conn);
                        if ($komitent) {
                            $komitent_id = $komitent['id'];
                            if (!isset($komitentiFound[$komitentNaziv])) {
                                $komitentiFound[$komitentNaziv] = $komitent;
                            }
                        } else {
                            if (!isset($komitentiToCreate[$komitentNaziv])) {
                                $komitentiToCreate[$komitentNaziv] = true;
                            }
                        }
                    }
                    
                    $vozac = null;
                    $vozac_id = null;
                    if (!empty($vozacIme)) {
                        $vozac = findVozac($vozacIme, $conn);
                        if ($vozac) {
                            $vozac_id = $vozac['id'];
                            if (!isset($vozaciFound[$vozacIme])) {
                                $vozaciFound[$vozacIme] = $vozac;
                            }
                        } else {
                            if (!isset($vozaciToCreate[$vozacIme])) {
                                $vozaciToCreate[$vozacIme] = true;
                            }
                        }
                    }
                    
                    $naplataData = parseNaplata($naplataStr);
                    $status = $vozac_id ? 'Predstoji' : 'Nerasporedjeno';
                    
                    $voznje[] = [
                        'row_num' => $rowNum,
                        'datum' => $datum,
                        'vreme' => $vreme,
                        'broj_leta' => $broj_leta,
                        'od' => $od,
                        'do' => $do,
                        'ime' => $ime,
                        'vozilo' => $vozilo,
                        'komitent_naziv' => $komitentNaziv,
                        'komitent_id' => $komitent_id,
                        'vozac_ime' => $vozacIme,
                        'vozac_id' => $vozac_id,
                        'cena' => $naplataData['cena'],
                        'placanje' => $naplataData['placanje'],
                        'napomena' => $naplataData['napomena'],
                        'status' => $status
                    ];
                }
                
                fclose($handle);
                
                $previewData = [
                    'voznje' => $voznje,
                    'komitenti_found' => $komitentiFound,
                    'komitenti_to_create' => array_keys($komitentiToCreate),
                    'vozaci_found' => $vozaciFound,
                    'vozaci_to_create' => array_keys($vozaciToCreate),
                    'errors' => $errors,
                    'csv_content' => file_get_contents($csvFile)
                ];
            }
        }
    }
}
?>

<?php include "header.php"; ?>

<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <h2 class="mb-0"><i class="bi bi-upload me-2"></i>Import vožnji iz CSV</h2>
        </div>
        <div class="card-body">
            <?php if (isset($imported)): ?>
                <div class="alert alert-success">
                    <h5><i class="bi bi-check-circle me-2"></i>Import uspešno završen!</h5>
                    <p class="mb-2"><strong>Importovano vožnji:</strong> <?php echo $imported; ?></p>
                    <p class="mb-2"><strong>Preskočeno:</strong> <?php echo $skipped; ?></p>
                    <?php if (count($importErrors) > 0): ?>
                        <hr>
                        <strong>Greške:</strong>
                        <ul class="mb-0">
                            <?php foreach ($importErrors as $err): ?>
                                <li><?php echo htmlspecialchars($err); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
                <div class="d-flex justify-content-between">
                    <a href="podesavanja.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad</a>
                    <a href="index.php" class="btn btn-primary"><i class="bi bi-list-ul me-1"></i>Pregled vožnji</a>
                </div>
            <?php elseif ($error): ?>
                <div class="alert alert-danger">
                    <?php echo htmlspecialchars($error); ?>
                </div>
                <a href="podesavanja.php" class="btn btn-secondary">Nazad</a>
            <?php elseif ($previewData): ?>
                <div class="alert alert-info">
                    <h5><i class="bi bi-info-circle me-2"></i>Preview importa</h5>
                    <p>Pregledajte podatke pre nego što izvršite import. Proverite da li su sve informacije tačne.</p>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0"><i class="bi bi-check-circle me-2"></i>Pronađeni komitenti</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($previewData['komitenti_found']) > 0): ?>
                                    <ul class="list-group">
                                        <?php foreach ($previewData['komitenti_found'] as $naziv => $komitent): ?>
                                            <li class="list-group-item"><?php echo htmlspecialchars($naziv); ?> (ID: <?php echo $komitent['id']; ?>)</li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-muted mb-0">Nema pronađenih komitenata</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>Komitenti koji će biti kreirani</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($previewData['komitenti_to_create']) > 0): ?>
                                    <ul class="list-group">
                                        <?php foreach ($previewData['komitenti_to_create'] as $naziv): ?>
                                            <li class="list-group-item"><?php echo htmlspecialchars($naziv); ?> <span class="badge bg-secondary">Novi</span></li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-muted mb-0">Nema komitenata za kreiranje</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0"><i class="bi bi-check-circle me-2"></i>Pronađeni vozači</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($previewData['vozaci_found']) > 0): ?>
                                    <ul class="list-group">
                                        <?php foreach ($previewData['vozaci_found'] as $ime => $vozac): ?>
                                            <li class="list-group-item"><?php echo htmlspecialchars($ime); ?> (ID: <?php echo $vozac['id']; ?>)</li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php else: ?>
                                    <p class="text-muted mb-0">Nema pronađenih vozača</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0"><i class="bi bi-exclamation-triangle me-2"></i>Vozači koji ne postoje</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($previewData['vozaci_to_create']) > 0): ?>
                                    <ul class="list-group">
                                        <?php foreach ($previewData['vozaci_to_create'] as $ime): ?>
                                            <li class="list-group-item"><?php echo htmlspecialchars($ime); ?> <span class="badge bg-warning">Neće biti dodeljen</span></li>
                                        <?php endforeach; ?>
                                    </ul>
                                    <div class="alert alert-warning mt-2 mb-0">
                                        <small>Vozači se ne kreiraju automatski. Vožnje će biti importovane bez vozača (status: Nerasporedjeno).</small>
                                    </div>
                                <?php else: ?>
                                    <p class="text-muted mb-0">Svi vozači postoje u sistemu</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if (count($previewData['errors']) > 0): ?>
                    <div class="alert alert-danger">
                        <h5><i class="bi bi-exclamation-triangle me-2"></i>Greške</h5>
                        <ul class="mb-0">
                            <?php foreach ($previewData['errors'] as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
                
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i>Vožnje koje će biti importovane (<?php echo count($previewData['voznje']); ?>)</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>Red</th>
                                        <th>Datum</th>
                                        <th>Vreme</th>
                                        <th>Broj leta</th>
                                        <th>Od</th>
                                        <th>Do</th>
                                        <th>Ime</th>
                                        <th>Vozilo</th>
                                        <th>Komitent</th>
                                        <th>Vozač</th>
                                        <th>Cena</th>
                                        <th>Plaćanje</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($previewData['voznje'] as $voznja): ?>
                                        <tr>
                                            <td><?php echo $voznja['row_num']; ?></td>
                                            <td><?php echo htmlspecialchars($voznja['datum']); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['vreme']); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['broj_leta'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['od']); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['do']); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['ime']); ?></td>
                                            <td><?php echo htmlspecialchars($voznja['vozilo']); ?></td>
                                            <td>
                                                <?php if ($voznja['komitent_id']): ?>
                                                    <?php echo htmlspecialchars($voznja['komitent_naziv']); ?>
                                                <?php elseif (!empty($voznja['komitent_naziv'])): ?>
                                                    <span class="badge bg-warning"><?php echo htmlspecialchars($voznja['komitent_naziv']); ?> (novi)</span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($voznja['vozac_id']): ?>
                                                    <?php echo htmlspecialchars($voznja['vozac_ime']); ?>
                                                <?php elseif (!empty($voznja['vozac_ime'])): ?>
                                                    <span class="badge bg-warning"><?php echo htmlspecialchars($voznja['vozac_ime']); ?> (ne postoji)</span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $voznja['cena'] ? number_format($voznja['cena'], 2) . ' RSD' : '-'; ?></td>
                                            <td><?php echo htmlspecialchars($voznja['placanje'] ?? '-'); ?></td>
                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($voznja['status']); ?></span></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <form method="POST" action="import_process.php">
                    <input type="hidden" name="csv_content" value="<?php echo htmlspecialchars(base64_encode($previewData['csv_content'])); ?>">
                    <div class="d-flex justify-content-between">
                        <a href="podesavanja.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad</a>
                        <button type="submit" class="btn btn-success"><i class="bi bi-check-circle me-1"></i>Potvrdi i importuj</button>
                    </div>
                </form>
            <?php else: ?>
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="csv_file" class="form-label">
                            <strong>Izaberi CSV fajl</strong>
                        </label>
                        <input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
                        <div class="form-text">
                            Upload CSV fajla sa vožnjama. Sistem će prikazati preview pre importa.
                        </div>
                    </div>
                    <div class="d-flex justify-content-between">
                        <a href="podesavanja.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad</a>
                        <button type="submit" class="btn btn-primary"><i class="bi bi-eye me-1"></i>Pregledaj</button>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include "footer.php"; ?>
