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

$success = false;
$error = null;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email_settings = [
        'emails_enabled' => isset($_POST['emails_enabled']) ? '1' : '0',
        'email_admin_new_ride' => isset($_POST['email_admin_new_ride']) ? '1' : '0',
        'email_admin_ride_modified' => isset($_POST['email_admin_ride_modified']) ? '1' : '0',
        'email_komitent_approved' => isset($_POST['email_komitent_approved']) ? '1' : '0',
        'email_komitent_rejected' => isset($_POST['email_komitent_rejected']) ? '1' : '0',
        'email_driver_daily_reminder' => isset($_POST['email_driver_daily_reminder']) ? '1' : '0',
    ];
    
    $display_settings = [
        'items_per_page' => isset($_POST['items_per_page']) ? $_POST['items_per_page'] : '25',
        'compact_view' => isset($_POST['compact_view']) ? '1' : '0',
    ];
    
    $valid_items_per_page = ['10', '25', '50', '100'];
    if (!in_array($display_settings['items_per_page'], $valid_items_per_page)) {
        $display_settings['items_per_page'] = '25';
    }
    
    $general_settings = [
        'default_ride_status' => isset($_POST['default_ride_status']) ? $_POST['default_ride_status'] : 'Na čekanju',
    ];
    
    $valid_statuses = ['Na čekanju', 'Nerasporedjeno'];
    if (!in_array($general_settings['default_ride_status'], $valid_statuses)) {
        $general_settings['default_ride_status'] = 'Na čekanju';
    }
    
    $conn->begin_transaction();
    
    try {
        foreach ($email_settings as $key => $value) {
            $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value, category) VALUES (?, ?, 'email') ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("sss", $key, $value, $value);
            $stmt->execute();
        }
        
        foreach ($display_settings as $key => $value) {
            $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value, category) VALUES (?, ?, 'display') ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("sss", $key, $value, $value);
            $stmt->execute();
        }
        
        foreach ($general_settings as $key => $value) {
            $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value, category) VALUES (?, ?, 'general') ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->bind_param("sss", $key, $value, $value);
            $stmt->execute();
        }
        
        $conn->commit();
        $success = true;
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Greška prilikom čuvanja podešavanja: " . $e->getMessage();
    }
}

$stmt = $conn->prepare("SELECT setting_key, setting_value, category FROM settings");
$stmt->execute();
$result = $stmt->get_result();
$current_settings = [];
while ($row = $result->fetch_assoc()) {
    $current_settings[$row['setting_key']] = $row['setting_value'];
}

$default_settings = [
    'emails_enabled' => '1',
    'email_admin_new_ride' => '1',
    'email_admin_ride_modified' => '1',
    'email_komitent_approved' => '1',
    'email_komitent_rejected' => '1',
    'email_driver_daily_reminder' => '1',
    'items_per_page' => '25',
    'compact_view' => '0',
    'default_ride_status' => 'Na čekanju',
];

foreach ($default_settings as $key => $default_value) {
    if (!isset($current_settings[$key])) {
        $current_settings[$key] = $default_value;
    }
}
?>

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

<div class="container mt-4">
    <div class="card">
        <div class="card-header">
            <h2 class="mb-0"><i class="bi bi-gear me-2"></i>Podešavanja</h2>
        </div>
        <div class="card-body">
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    Podešavanja su uspešno sačuvana.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="post">
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="bi bi-envelope me-2"></i>Email obaveštenja</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="emails_enabled" name="emails_enabled" <?php echo $current_settings['emails_enabled'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="emails_enabled">
                                    <strong>Uključi email obaveštenja</strong>
                                </label>
                                <div class="form-text">Glavni prekidač za sva email obaveštenja. Ako je isključeno, nijedan email se neće slati.</div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <h6 class="mb-3">Uslovi za slanje email obaveštenja:</h6>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="email_admin_new_ride" name="email_admin_new_ride" <?php echo $current_settings['email_admin_new_ride'] ? 'checked' : ''; ?> <?php echo !$current_settings['emails_enabled'] ? 'disabled' : ''; ?>>
                                <label class="form-check-label" for="email_admin_new_ride">
                                    <strong>Obaveštenje administratoru kada komitent kreira novu vožnju</strong>
                                </label>
                                <div class="form-text">Administrator dobija email kada komitent kreira novu vožnju koja čeka na odobrenje.</div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="email_admin_ride_modified" name="email_admin_ride_modified" <?php echo $current_settings['email_admin_ride_modified'] ? 'checked' : ''; ?> <?php echo !$current_settings['emails_enabled'] ? 'disabled' : ''; ?>>
                                <label class="form-check-label" for="email_admin_ride_modified">
                                    <strong>Obaveštenje administratoru kada komitent menja odobrenu vožnju</strong>
                                </label>
                                <div class="form-text">Administrator dobija email kada komitent izmeni vožnju koja je već odobrena. Status se vraća na "Na čekanju".</div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="email_komitent_approved" name="email_komitent_approved" <?php echo $current_settings['email_komitent_approved'] ? 'checked' : ''; ?> <?php echo !$current_settings['emails_enabled'] ? 'disabled' : ''; ?>>
                                <label class="form-check-label" for="email_komitent_approved">
                                    <strong>Obaveštenje komitentu kada administrator odobri vožnju</strong>
                                </label>
                                <div class="form-text">Komitent dobija email kada administrator odobri njegovu vožnju.</div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="email_komitent_rejected" name="email_komitent_rejected" <?php echo $current_settings['email_komitent_rejected'] ? 'checked' : ''; ?> <?php echo !$current_settings['emails_enabled'] ? 'disabled' : ''; ?>>
                                <label class="form-check-label" for="email_komitent_rejected">
                                    <strong>Obaveštenje komitentu kada administrator odbije vožnju</strong>
                                </label>
                                <div class="form-text">Komitent dobija email kada administrator odbije njegovu vožnju.</div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="email_driver_daily_reminder" name="email_driver_daily_reminder" <?php echo $current_settings['email_driver_daily_reminder'] == '1' ? 'checked' : ''; ?> <?php echo $current_settings['emails_enabled'] != '1' ? 'disabled' : ''; ?>>
                                <label class="form-check-label" for="email_driver_daily_reminder">
                                    <strong>Dnevno obaveštenje vozaču o vožnjama za sutra</strong>
                                </label>
                                <div class="form-text">Vozač dobija email svakog dana u 18:00 sa pregledom svih vožnji za sutra. Zahteva podešen cron job.</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="bi bi-display me-2"></i>Podešavanja prikaza</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="items_per_page" class="form-label">
                                <strong>Broj stavki po stranici</strong>
                            </label>
                            <select class="form-select" id="items_per_page" name="items_per_page">
                                <option value="10" <?php echo $current_settings['items_per_page'] == '10' ? 'selected' : ''; ?>>10</option>
                                <option value="25" <?php echo $current_settings['items_per_page'] == '25' ? 'selected' : ''; ?>>25</option>
                                <option value="50" <?php echo $current_settings['items_per_page'] == '50' ? 'selected' : ''; ?>>50</option>
                                <option value="100" <?php echo $current_settings['items_per_page'] == '100' ? 'selected' : ''; ?>>100</option>
                            </select>
                            <div class="form-text">Broj vožnji koji se prikazuje po stranici u tabeli.</div>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="compact_view" name="compact_view" <?php echo $current_settings['compact_view'] == '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="compact_view">
                                    <strong>Kompaktan prikaz tabele</strong>
                                </label>
                                <div class="form-text">Smanjuje razmake i fontove u tabeli za kompaktniji prikaz.</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="bi bi-gear-wide me-2"></i>Opšta podešavanja</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="default_ride_status" class="form-label">
                                <strong>Podrazumevani status nove vožnje</strong>
                            </label>
                            <select class="form-select" id="default_ride_status" name="default_ride_status">
                                <option value="Na čekanju" <?php echo $current_settings['default_ride_status'] == 'Na čekanju' ? 'selected' : ''; ?>>Na čekanju</option>
                                <option value="Nerasporedjeno" <?php echo $current_settings['default_ride_status'] == 'Nerasporedjeno' ? 'selected' : ''; ?>>Nerasporedjeno</option>
                            </select>
                            <div class="form-text">Status koji će automatski biti dodeljen novoj vožnji kada je kreira administrator.</div>
                        </div>
                    </div>
                </div>
                
                <div class="card mb-4">
                    <div class="card-header bg-warning text-dark">
                        <h5 class="mb-0"><i class="bi bi-upload me-2"></i>Import vožnji iz CSV</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <p>Importujte vožnje iz CSV fajla. Sistem će prikazati preview pre importa sa detaljnim izveštajem.</p>
                            <a href="import_preview.php" class="btn btn-warning">
                                <i class="bi bi-upload me-1"></i>Otvorite stranicu za import
                            </a>
                        </div>
                        <div class="form-text">
                            Sistem će automatski parsirati naplatu (EUR/DIN, kes/na račun), 
                            pronaći ili kreirati komitente po nazivu, i mapirati vozače po imenu.
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between">
                    <a href="index.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i>Nazad</a>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-floppy me-1"></i>Sačuvaj podešavanja</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const emailsEnabled = document.getElementById('emails_enabled');
    const checkboxes = [
        'email_admin_new_ride',
        'email_admin_ride_modified',
        'email_komitent_approved',
        'email_komitent_rejected',
        'email_driver_daily_reminder'
    ];
    
    function toggleCheckboxes() {
        const enabled = emailsEnabled.checked;
        checkboxes.forEach(function(id) {
            const checkbox = document.getElementById(id);
            checkbox.disabled = !enabled;
            if (!enabled) {
                checkbox.checked = false;
            }
        });
    }
    
    emailsEnabled.addEventListener('change', toggleCheckboxes);
    
    const compactView = document.getElementById('compact_view');
    if (compactView && compactView.checked) {
        document.body.classList.add('compact-view');
    }
    
    compactView.addEventListener('change', function() {
        if (this.checked) {
            document.body.classList.add('compact-view');
        } else {
            document.body.classList.remove('compact-view');
        }
    });
});
</script>

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