<?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 findOrCreateKomitent($naziv, $conn) {
    if (empty(trim($naziv))) {
        return null;
    }
    
    $naziv = trim($naziv);
    
    $stmt = $conn->prepare("SELECT id 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['id'];
    }
    
    $grad = 'Beograd';
    $stmt = $conn->prepare("INSERT INTO komitenti (naziv, grad) VALUES (?, ?)");
    $stmt->bind_param("ss", $naziv, $grad);
    
    if ($stmt->execute()) {
        return $conn->insert_id;
    }
    
    return null;
}

function findVozacByName($ime, $conn) {
    if (empty(trim($ime))) {
        return null;
    }
    
    $ime = trim($ime);
    
    $stmt = $conn->prepare("SELECT id 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['id'];
    }
    
    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;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['csv_content'])) {
    header('Location: import_preview.php');
    exit;
}

$csvContent = base64_decode($_POST['csv_content']);
$tempFile = tmpfile();
fwrite($tempFile, $csvContent);
$csvFile = stream_get_meta_data($tempFile)['uri'];

$handle = fopen($csvFile, 'r');
if ($handle === false) {
    $_SESSION['import_error'] = 'Greška prilikom čitanja fajla';
    header('Location: import_preview.php');
    exit;
}

$header = fgetcsv($handle, 0, ',', '"', '\\');
if ($header === false) {
    fclose($handle);
    $_SESSION['import_error'] = 'Greška prilikom čitanja header-a';
    header('Location: import_preview.php');
    exit;
}

$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;
    }
}

$imported = 0;
$skipped = 0;
$errors = [];

$conn->begin_transaction();

try {
    $rowNum = 1;
    while (($row = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
        $rowNum++;
        
        if (count($row) < 5) {
            $skipped++;
            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)) {
            $skipped++;
            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);
            $skipped++;
            continue;
        }
        
        $komitent_id = findOrCreateKomitent($komitentNaziv, $conn);
        if (!$komitent_id && !empty($komitentNaziv)) {
            $errors[] = "Red $rowNum: Greška pri kreiranju komitenta: $komitentNaziv";
            $skipped++;
            continue;
        }
        
        $vozac_id = findVozacByName($vozacIme, $conn);
        
        $naplataData = parseNaplata($naplataStr);
        
        $status = $vozac_id ? 'Predstoji' : 'Nerasporedjeno';
        
        $stmt = $conn->prepare("INSERT INTO voznje (datum, vreme, broj_leta, polazna_adresa, dolazna_adresa, ime_klijenta, vrsta_vozila, komitent_id, vozac_id, cena, placanje, napomena, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $cena = $naplataData['cena'];
        $placanje = $naplataData['placanje'];
        $napomena = $naplataData['napomena'];
        
        $stmt->bind_param("sssssssiissss", 
            $datum,
            $vreme,
            $broj_leta,
            $od,
            $do,
            $ime,
            $vozilo,
            $komitent_id,
            $vozac_id,
            $cena,
            $placanje,
            $napomena,
            $status
        );
        
        if ($stmt->execute()) {
            $imported++;
        } else {
            $errors[] = "Red $rowNum: " . $stmt->error;
            $skipped++;
        }
    }
    
    $conn->commit();
    fclose($handle);
    fclose($tempFile);
    
    $_SESSION['import_success'] = true;
    $_SESSION['import_imported'] = $imported;
    $_SESSION['import_skipped'] = $skipped;
    $_SESSION['import_errors'] = $errors;
    
    header('Location: import_preview.php?success=1');
    exit;
    
} catch (Exception $e) {
    $conn->rollback();
    fclose($handle);
    fclose($tempFile);
    
    $_SESSION['import_error'] = 'Greška prilikom importa: ' . $e->getMessage();
    header('Location: import_preview.php');
    exit;
}
