<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/email_helper.php";
require_once __DIR__ . "/settings_helper.php";

$tomorrow = date('Y-m-d', strtotime('+1 day'));
$today = date('Y-m-d');

$sql = "SELECT v.*, u.name as vozac_ime, u.email as vozac_email, k.naziv as komitent_naziv
        FROM voznje v
        LEFT JOIN users u ON v.vozac_id = u.id
        LEFT JOIN komitenti k ON v.komitent_id = k.id
        WHERE v.datum = ? 
        AND v.vozac_id IS NOT NULL
        AND v.status IN ('Predstoji', 'Nerasporedjeno')
        ORDER BY v.vozac_id, v.vreme ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $tomorrow);
$stmt->execute();
$result = $stmt->get_result();

$vozaci_rides = [];

while ($row = $result->fetch_assoc()) {
    $vozac_id = $row['vozac_id'];
    if (!isset($vozaci_rides[$vozac_id])) {
        $vozaci_rides[$vozac_id] = [
            'vozac_ime' => $row['vozac_ime'],
            'vozac_email' => $row['vozac_email'],
            'rides' => []
        ];
    }
    $vozaci_rides[$vozac_id]['rides'][] = $row;
}

$emails_sent = 0;
$emails_failed = 0;

foreach ($vozaci_rides as $vozac_id => $data) {
    if (empty($data['vozac_email'])) {
        error_log("Vozač ID {$vozac_id} ({$data['vozac_ime']}) nema email adresu.");
        $emails_failed++;
        continue;
    }
    
    $vozac_ime = $data['vozac_ime'];
    $vozac_email = $data['vozac_email'];
    $rides = $data['rides'];
    
    $subject = "Vožnje za sutra (" . date('d.m.Y', strtotime($tomorrow)) . ") - Royal Transport";
    
    $ridesHtml = '';
    foreach ($rides as $index => $ride) {
        $tip_usluge = $ride['tip_usluge'] ?? 'transfer_od_do_adrese';
        
        $ridesHtml .= '
        <div style="background-color: #ffffff; border: 1px solid #dee2e6; border-radius: 6px; padding: 20px; margin-bottom: 15px;">
            <h3 style="margin-top: 0; color: #007bff; font-size: 16px; border-bottom: 2px solid #007bff; padding-bottom: 10px;">
                Vožnja #' . ($index + 1);
        if (!empty($ride['broj_leta'])) {
            $ridesHtml .= ' - ' . htmlspecialchars($ride['broj_leta']);
        }
        $ridesHtml .= '
            </h3>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; width: 120px; color: #555;">Vreme:</td>
                    <td style="padding: 6px 0; font-size: 16px; font-weight: bold; color: #007bff;">' . date('H:i', strtotime($ride['vreme'])) . '</td>
                </tr>
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555;">Klijent:</td>
                    <td style="padding: 6px 0;">' . htmlspecialchars($ride['ime_klijenta']) . '</td>
                </tr>';
        
        if ($tip_usluge === 'transfer_od_do_adrese') {
            $ridesHtml .= '
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555; vertical-align: top;">Polazak:</td>
                    <td style="padding: 6px 0;">' . htmlspecialchars($ride['polazna_adresa']) . '</td>
                </tr>
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555; vertical-align: top;">Destinacija:</td>
                    <td style="padding: 6px 0;">' . htmlspecialchars($ride['dolazna_adresa']) . '</td>
                </tr>';
        } else {
            $ridesHtml .= '
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555;">Tip usluge:</td>
                    <td style="padding: 6px 0;">Na sat';
            if (!empty($ride['broj_sati'])) {
                $ridesHtml .= ' (' . $ride['broj_sati'] . 'h)';
            }
            $ridesHtml .= '</td>
                </tr>';
        }
        
        $ridesHtml .= '
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555;">Vozilo:</td>
                    <td style="padding: 6px 0;">' . htmlspecialchars($ride['vrsta_vozila']) . '</td>
                </tr>';
        
        if (!empty($ride['komitent_naziv'])) {
            $ridesHtml .= '
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555;">Naručilac:</td>
                    <td style="padding: 6px 0;">' . htmlspecialchars($ride['komitent_naziv']) . '</td>
                </tr>';
        }
        
        if (!empty($ride['napomena'])) {
            $ridesHtml .= '
                <tr>
                    <td style="padding: 6px 0; font-weight: bold; color: #555; vertical-align: top;">Napomena:</td>
                    <td style="padding: 6px 0; font-style: italic; color: #666;">' . htmlspecialchars($ride['napomena']) . '</td>
                </tr>';
        }
        
        $ridesHtml .= '
            </table>
        </div>';
    }
    
    $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;">Vaše vožnje za sutra</p>
        </div>
        
        <div style="padding: 30px;">
            <p style="font-size: 16px; margin-top: 0;">Poštovani/a <strong>' . htmlspecialchars($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;">
                    Imate <strong>' . count($rides) . '</strong> vožnji za sutra (' . date('d.m.Y', strtotime($tomorrow)) . ')
                </p>
            </div>
            
            ' . $ridesHtml . '
            
            <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 (shouldSendEmail('email_driver_daily_reminder') && sendEmail($vozac_email, $subject, $body, true)) {
        $emails_sent++;
        error_log("Email poslat vozaču {$vozac_ime} ({$vozac_email}) sa " . count($rides) . " vožnjama za sutra.");
    } else {
        if (!shouldSendEmail('email_driver_daily_reminder')) {
            error_log("Email obaveštenja za vozače su onemogućena u podešavanjima.");
        } else {
            $emails_failed++;
            error_log("Greška pri slanju emaila vozaču {$vozac_ime} ({$vozac_email}).");
        }
    }
}

$log_message = "Cron job završen: " . date('Y-m-d H:i:s') . " - Poslato: {$emails_sent}, Neuspešno: {$emails_failed}";
error_log($log_message);

if (php_sapi_name() !== 'cli') {
    echo $log_message;
}
?>
