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

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

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

$voznja_id = isset($_POST['voznja_id']) ? (int)$_POST['voznja_id'] : 0;
$novi_vozac_id = isset($_POST['vozac_id']) && $_POST['vozac_id'] !== '' ? (int)$_POST['vozac_id'] : null;
$email_napomena = isset($_POST['email_napomena']) ? trim($_POST['email_napomena']) : '';

if (!$voznja_id) {
    echo json_encode(['success' => false, 'message' => 'ID vožnje nije prosleđen']);
    exit();
}

// Učitaj trenutne podatke vožnje
$stmt = $conn->prepare("SELECT v.*, k.naziv as komitent_naziv, u.name as stari_vozac_ime, u.email as stari_vozac_email 
                        FROM voznje v 
                        LEFT JOIN komitenti k ON v.komitent_id = k.id 
                        LEFT JOIN users u ON v.vozac_id = u.id 
                        WHERE v.id = ?");
$stmt->bind_param("i", $voznja_id);
$stmt->execute();
$result = $stmt->get_result();
$voznja = $result->fetch_assoc();

if (!$voznja) {
    echo json_encode(['success' => false, 'message' => 'Vožnja nije pronađena']);
    exit();
}

$stari_vozac_id = $voznja['vozac_id'];
$stari_status = $voznja['status'];
$novi_status = $stari_status;

// Logika za status
if ($novi_vozac_id && ($stari_status === 'Nerasporedjeno' || $stari_status === 'Na čekanju')) {
    $novi_status = 'Predstoji';
} elseif (!$novi_vozac_id && $stari_status === 'Predstoji') {
    $novi_status = 'Nerasporedjeno';
}

// Ažuriraj vožnju
$stmt = $conn->prepare("UPDATE voznje SET vozac_id = ?, status = ? WHERE id = ?");
$stmt->bind_param("isi", $novi_vozac_id, $novi_status, $voznja_id);

if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Greška pri ažuriranju vožnje']);
    exit();
}

$tip_usluge = $voznja['tip_usluge'] ?? 'transfer_od_do_adrese';
$tip_usluge_text = $tip_usluge === 'na_sat' ? 'Na sat' . (!empty($voznja['broj_sati']) ? ' (' . $voznja['broj_sati'] . 'h)' : '') : 'Transfer od-do adrese';

// Email starom vozaču (ako je promenjen)
if ($stari_vozac_id && $stari_vozac_id != $novi_vozac_id && !empty($voznja['stari_vozac_email'])) {
    $subject = "Vožnja otkazana - " . date('d.m.Y', strtotime($voznja['datum'])) . " " . date('H:i', strtotime($voznja['vreme']));
    
    $body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f4f4f4; margin: 0; padding: 0;">
    <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <div style="background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); padding: 30px; text-align: center;">
            <img src="https://transfers.inf.rs/app/logo.png" alt="Royal Transport" style="max-width: 340px; height: auto; margin-bottom: 10px;">
            <h1 style="color: #ffffff; margin: 0; font-size: 24px;">Royal Transport</h1>
            <p style="color: #cccccc; margin: 10px 0 0 0; font-size: 14px;">Vožnja otkazana</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani/a <strong>' . htmlspecialchars($voznja['stari_vozac_ime']) . '</strong>,</p>
            
            <div style="background-color: #f8d7da; border-left: 4px solid #dc3545; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 16px; font-weight: bold; color: #721c24;">
                    Vožnja koja vam je bila dodeljena za <strong>' . date('d.m.Y', strtotime($voznja['datum'])) . '</strong> u <strong>' . date('H:i', strtotime($voznja['vreme'])) . '</strong> je otkazana.
                </p>
            </div>
            
            <div style="background-color: #f8f9fa; border-left: 4px solid #6c757d; padding: 20px; margin: 20px 0; border-radius: 4px;">
                <h2 style="margin-top: 0; color: #6c757d; font-size: 18px;">Detalji vožnje</h2>
                
                <table style="width: 100%; border-collapse: collapse;">';
                
                if (!empty($voznja['broj_leta'])) {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; width: 140px; color: #555;">Broj leta:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['broj_leta']) . '</td>
                    </tr>';
                }
                
                $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Datum:</td>
                        <td style="padding: 8px 0;">' . date('d.m.Y', strtotime($voznja['datum'])) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vreme:</td>
                        <td style="padding: 8px 0;">' . date('H:i', strtotime($voznja['vreme'])) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Klijent:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['ime_klijenta']) . '</td>
                    </tr>';
                    
                if ($tip_usluge === 'transfer_od_do_adrese') {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Polazak:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['polazna_adresa']) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Destinacija:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['dolazna_adresa']) . '</td>
                    </tr>';
                }
                
                $body .= '
                </table>
            </div>
            
            <p style="color: #666; font-size: 14px; margin-top: 30px; margin-bottom: 0;">Hvala vam na razumevanju!</p>
        </div>
        
        <div style="background-color: #f8f9fa; padding: 20px; text-align: center; border-top: 1px solid #dee2e6;">
            <p style="margin: 0; color: #6c757d; font-size: 12px;">Royal Transport &copy; ' . date('Y') . '</p>
        </div>
    </div>
</body>
</html>';
    
    if (sendEmail($voznja['stari_vozac_email'], $subject, $body, true)) {
        error_log("Email poslat starom vozaču {$voznja['stari_vozac_ime']} ({$voznja['stari_vozac_email']}) - vožnja otkazana ID: {$voznja_id}");
    } else {
        error_log("Greška pri slanju emaila starom vozaču {$voznja['stari_vozac_ime']} ({$voznja['stari_vozac_email']})");
    }
}

// Email novom vozaču (ako je dodeljen novi ili promenjen)
if ($novi_vozac_id && $novi_vozac_id != $stari_vozac_id) {
    $stmt = $conn->prepare("SELECT name, email FROM users WHERE id = ? AND role = 'vozac'");
    $stmt->bind_param("i", $novi_vozac_id);
    $stmt->execute();
    $novi_vozac_result = $stmt->get_result();
    
    if ($novi_vozac = $novi_vozac_result->fetch_assoc()) {
        $novi_vozac_ime = $novi_vozac['name'];
        $novi_vozac_email = $novi_vozac['email'];
        
        if (!empty($novi_vozac_email)) {
            $subject = "Nova vožnja vam je dodeljena - " . date('d.m.Y', strtotime($voznja['datum'])) . " " . date('H:i', strtotime($voznja['vreme']));
            
            $body = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f4f4f4; margin: 0; padding: 0;">
    <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <div style="background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%); padding: 30px; text-align: center;">
            <img src="https://transfers.inf.rs/app/logo.png" alt="Royal Transport" style="max-width: 340px; height: auto; margin-bottom: 10px;">
            <h1 style="color: #ffffff; margin: 0; font-size: 24px;">Royal Transport</h1>
            <p style="color: #cccccc; margin: 10px 0 0 0; font-size: 14px;">Nova vožnja vam je dodeljena</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani/a <strong>' . htmlspecialchars($novi_vozac_ime) . '</strong>,</p>
            
            <div style="background-color: #e7f3ff; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 16px; font-weight: bold; color: #007bff;">
                    Nova vožnja vam je dodeljena za <strong>' . date('d.m.Y', strtotime($voznja['datum'])) . '</strong> u <strong>' . date('H:i', strtotime($voznja['vreme'])) . '</strong>
                </p>
            </div>';
            
            if (!empty($email_napomena)) {
                $body .= '
            <div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 14px; font-weight: bold; color: #856404;">Napomena od administratora:</p>
                <p style="margin: 5px 0 0 0; color: #856404;">' . nl2br(htmlspecialchars($email_napomena)) . '</p>
            </div>';
            }
            
            $body .= '
            <div style="background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 20px; margin: 20px 0; border-radius: 4px;">
                <h2 style="margin-top: 0; color: #007bff; font-size: 18px;">Detalji vožnje</h2>
                
                <table style="width: 100%; border-collapse: collapse;">';
                
                if (!empty($voznja['broj_leta'])) {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; width: 140px; color: #555;">Broj leta:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['broj_leta']) . '</td>
                    </tr>';
                }
                
                $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Datum:</td>
                        <td style="padding: 8px 0; font-size: 16px; font-weight: bold; color: #007bff;">' . date('d.m.Y', strtotime($voznja['datum'])) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vreme:</td>
                        <td style="padding: 8px 0; font-size: 16px; font-weight: bold; color: #007bff;">' . date('H:i', strtotime($voznja['vreme'])) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Klijent:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['ime_klijenta']) . '</td>
                    </tr>';
                    
                if ($tip_usluge === 'transfer_od_do_adrese') {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Polazak:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['polazna_adresa']) . '</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Destinacija:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['dolazna_adresa']) . '</td>
                    </tr>';
                } else {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Tip usluge:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($tip_usluge_text) . '</td>
                    </tr>';
                }
                
                $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Vozilo:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['vrsta_vozila']) . '</td>
                    </tr>';
                    
                if (!empty($voznja['dodaci_vozilo'])) {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555;">Dodaci:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['dodaci_vozilo']) . '</td>
                    </tr>';
                }
                
                if (!empty($voznja['napomena'])) {
                    $body .= '
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Napomena:</td>
                        <td style="padding: 8px 0; font-style: italic; color: #666;">' . htmlspecialchars($voznja['napomena']) . '</td>
                    </tr>';
                }
                
                $body .= '
                </table>
            </div>
            
            <p style="color: #666; font-size: 14px; margin-top: 30px; margin-bottom: 0;">Hvala vam na pažnji!</p>
        </div>
        
        <div style="background-color: #f8f9fa; padding: 20px; text-align: center; border-top: 1px solid #dee2e6;">
            <p style="margin: 0; color: #6c757d; font-size: 12px;">Royal Transport &copy; ' . date('Y') . '</p>
        </div>
    </div>
</body>
</html>';
            
            if (sendEmail($novi_vozac_email, $subject, $body, true)) {
                error_log("Email poslat novom vozaču {$novi_vozac_ime} ({$novi_vozac_email}) - nova vožnja ID: {$voznja_id}");
            } else {
                error_log("Greška pri slanju emaila novom vozaču {$novi_vozac_ime} ({$novi_vozac_email})");
            }
        }
    }
}

// Vrati informacije o vozaču za ažuriranje UI-a
$vozac_info = null;
if ($novi_vozac_id) {
    $stmt = $conn->prepare("SELECT name, telefon FROM users WHERE id = ?");
    $stmt->bind_param("i", $novi_vozac_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($vozac = $result->fetch_assoc()) {
        $vozac_info = [
            'ime' => $vozac['name'],
            'telefon' => $vozac['telefon']
        ];
    }
}

echo json_encode([
    'success' => true, 
    'message' => 'Vozač uspešno dodeljen',
    'vozac_info' => $vozac_info,
    'status' => $novi_status
]);
