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

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $action = $_POST['action'];
    
    if ($action === 'approve' || $action === 'reject') {
        $stmt = $conn->prepare("SELECT * FROM voznje WHERE id = ? AND status = 'Na čekanju'");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $voznja = $result->fetch_assoc();
        
        if ($voznja) {
            if ($action === 'approve') {
                $newStatus = 'Nerasporedjeno';
                $stmt = $conn->prepare("UPDATE voznje SET status = ? WHERE id = ?");
                $stmt->bind_param("si", $newStatus, $id);
                $stmt->execute();
                
                $message = "Vožnja je prihvaćena.";
            } else {
                $newStatus = 'Odbijeno';
                $stmt = $conn->prepare("UPDATE voznje SET status = ? WHERE id = ?");
                $stmt->bind_param("si", $newStatus, $id);
                $stmt->execute();
                
                $message = "Vožnja je odbijena.";
            }
            
            $stmt = $conn->prepare("SELECT email FROM users WHERE komitent_id = ? LIMIT 1");
            $stmt->bind_param("i", $voznja['komitent_id']);
            $stmt->execute();
            $emailResult = $stmt->get_result();
            if ($emailRow = $emailResult->fetch_assoc()) {
                $komitentEmail = $emailRow['email'];
                
                $userName = '';
                $stmt = $conn->prepare("SELECT name FROM users WHERE komitent_id = ? LIMIT 1");
                $stmt->bind_param("i", $voznja['komitent_id']);
                $stmt->execute();
                $userResult = $stmt->get_result();
                if ($userRow = $userResult->fetch_assoc()) {
                    $userName = $userRow['name'];
                }
                
                $statusText = $action === 'approve' ? 'prihvaćena' : 'odbijena';
                $statusColor = $action === 'approve' ? '#28a745' : '#dc3545';
                $statusBg = $action === 'approve' ? '#d4edda' : '#f8d7da';
                
                $emailSetting = $action === 'approve' ? 'email_komitent_approved' : 'email_komitent_rejected';
                
                if (shouldSendEmail($emailSetting)) {
                    $subject = "Obaveštenje o vožnji - " . htmlspecialchars($userName ?: 'N/A') . " - " . htmlspecialchars($voznja['broj_leta'] ?? 'N/A');
                
                $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;">Obaveštenje o vožnji</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani,</p>
            
            <div style="background-color: ' . $statusBg . '; border-left: 4px solid ' . $statusColor . '; padding: 15px; margin: 20px 0; border-radius: 4px;">
                <p style="margin: 0; font-size: 16px; font-weight: bold; color: ' . $statusColor . ';">
                    Vaša vožnja je <strong>' . $statusText . '</strong>.
                </p>
            </div>
            
            <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;">
                    <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'] ?? 'N/A') . '</td>
                    </tr>
                    <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>
                    <tr>
                        <td style="padding: 8px 0; font-weight: bold; color: #555; vertical-align: top;">Polazna adresa:</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;">Dolazna adresa:</td>
                        <td style="padding: 8px 0;">' . htmlspecialchars($voznja['dolazna_adresa']) . '</td>
                    </tr>
                </table>
            </div>
            
            <p style="color: #666; font-size: 14px; 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 (shouldSendEmail($emailSetting)) {
                        sendEmail($komitentEmail, $subject, $body, true);
                    }
                }
            }
            
            header("Location: pending_rides.php?message=" . urlencode($message));
            exit();
        }
    }
}

$sql = "SELECT v.*, k.naziv as komitent_naziv 
        FROM voznje v 
        LEFT JOIN komitenti k ON v.komitent_id = k.id 
        WHERE v.status = 'Na čekanju' 
        ORDER BY v.datum ASC, v.vreme ASC";

$result = $conn->query($sql);
?>

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

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Vožnje na čekanju</h2>
        <a href="index.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad na listu</a>
    </div>

    <?php if (isset($_GET['message'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['message']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($result->num_rows === 0): ?>
        <div class="alert alert-info">
            Trenutno nema vožnji na čekanju.
        </div>
    <?php else: ?>
        <div class="row g-4">
            <?php while ($row = $result->fetch_assoc()): ?>
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                Vožnja #<?php echo htmlspecialchars($row['broj_leta'] ?? 'N/A'); ?>
                            </h5>
                            <span class="badge bg-warning text-dark">Na čekanju</span>
                        </div>
                        <div class="card-body">
                            <div class="mb-2">
                                <strong>Datum i vreme:</strong> 
                                <?php echo date('d.m.Y', strtotime($row['datum'])); ?> 
                                <?php echo date('H:i', strtotime($row['vreme'])); ?>
                            </div>
                            <div class="mb-2">
                                <strong>Naručilac:</strong> <?php echo htmlspecialchars($row['komitent_naziv'] ?? ''); ?>
                            </div>
                            <div class="mb-2">
                                <strong>Klijent:</strong> <?php echo htmlspecialchars($row['ime_klijenta']); ?>
                            </div>
                            <div class="mb-2">
                                <strong>Vozilo:</strong> <?php echo htmlspecialchars($row['vrsta_vozila']); ?>
                            </div>
                            <div class="mb-2">
                                <strong>Polazna adresa:</strong> <?php echo htmlspecialchars($row['polazna_adresa']); ?>
                            </div>
                            <div class="mb-2">
                                <strong>Dolazna adresa:</strong> <?php echo htmlspecialchars($row['dolazna_adresa']); ?>
                            </div>
                            <?php if (!empty($row['napomena'])): ?>
                                <div class="mb-2">
                                    <strong>Napomena:</strong> <?php echo htmlspecialchars($row['napomena']); ?>
                                </div>
                            <?php endif; ?>
                            <?php if (!empty($row['cena'])): ?>
                                <div class="mb-2">
                                    <strong>Cena:</strong> <?php echo number_format(floatval($row['cena']), 2, ',', '.'); ?> RSD
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="card-footer bg-transparent">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                <input type="hidden" name="action" value="approve">
                                <button type="submit" class="btn btn-success me-2" 
                                        onclick="return confirm('Da li ste sigurni da želite da prihvatite ovu vožnju?')">
                                    <i class="bi bi-check-circle me-1"></i>Prihvati
                                </button>
                            </form>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                <input type="hidden" name="action" value="reject">
                                <button type="submit" class="btn btn-danger" 
                                        onclick="return confirm('Da li ste sigurni da želite da odbijete ovu vožnju?')">
                                    <i class="bi bi-x-circle me-1"></i>Odbij
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php endif; ?>
</div>

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

