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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
    exit;
}

if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'error' => 'Greška prilikom upload-a fajla']);
    exit;
}

$csvFile = $_FILES['csv_file']['tmp_name'];
$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;
}

$handle = fopen($csvFile, 'r');
if ($handle === false) {
    echo json_encode(['success' => false, 'error' => 'Greška prilikom čitanja fajla']);
    exit;
}

$header = fgetcsv($handle, 0, ',', '"', '\\');
if ($header === false) {
    fclose($handle);
    echo json_encode(['success' => false, 'error' => 'Greška prilikom čitanja header-a']);
    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);
        
        if (!$datum || !$vreme || empty($od) || empty($do) || empty($ime) || empty($vozilo)) {
            $errors[] = "Red $rowNum: Nedostaju obavezna polja";
            $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);
    
    echo json_encode([
        'success' => true,
        'imported' => $imported,
        'skipped' => $skipped,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    fclose($handle);
    echo json_encode([
        'success' => false,
        'error' => 'Greška prilikom importa: ' . $e->getMessage()
    ]);
}
