<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Formularz kontaktowy (PHPMailer)
 */

require_once __DIR__ . '/../inc/smtp.php';

$podmiot_id = (int)($_SESSION['podmiot'] ?? 0);
$firma = vbk_read_firma($podmiot_id);
$client_name = $_SESSION['nazwisko'] ?? '';
$client_id = $_SESSION['client_id'] ?? '';
$msg_sent = false;
$msg_error = '';

// Prefill z URL (np. z info.php → zgłoszenie nieaktualnych danych)
$prefill_subject = '';
$prefill_message = '';
if (isset($_GET['subject']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    if ($_GET['subject'] === 'data_update') {
        $prefill_subject = __('contact.subject_data');
        $prefill_message = __('info.report_outdated_message', ['client_id' => nr_klienta($client_id), 'name' => $client_name]);
    } elseif ($_GET['subject'] === 'tariff_change') {
        require_once __DIR__ . '/../inc/tariff_offers.php';
        $tc_config = tariff_offers_load();
        $tc_offers = $tc_config['offers'] ?? [];
        $tc_index = (int)($_GET['offer'] ?? -1);
        if (isset($tc_offers[$tc_index])) {
            $tc_offer = $tc_offers[$tc_index];
            $tc_clients = vbk_read_klienci();
            $tc_client = $tc_clients[$client_id] ?? null;
            $tc_current = ($tc_client['dl_dzien'] ?? '') . ' / ' . ($tc_client['ul_dzien'] ?? '');
            $tc_requested = $tc_offer['name'] . ' (' . $tc_offer['dl'] . ' / ' . $tc_offer['ul'];
            if (!empty($tc_offer['price'])) {
                $tc_requested .= ', ' . $tc_offer['price'];
            }
            $tc_requested .= ')';
            $prefill_subject = __('contact.subject_tariff');
            $prefill_message = __('tariff_change.prefill_message', [
                'client_id' => nr_klienta($client_id),
                'name' => $client_name,
                'current' => $tc_current,
                'requested' => $tc_requested,
            ]);
        }
    }
}

// Obsługa wysłania formularza
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_contact'])) {
    if (ibok_is_demo()) {
        $msg_error = __('demo.feature_blocked');
    } elseif (!csrf_validate()) {
        $msg_error = __('login.error_csrf');
    } else {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $subject = trim($_POST['subject'] ?? '');
        $message = trim($_POST['message'] ?? '');

        if (empty($name) || empty($email) || empty($subject) || empty($message)) {
            $msg_error = __('contact.error_fields');
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $msg_error = __('contact.error_fields');
        } else {
            // Adres odbiorcy (admin/firma)
            $to = $GLOBALS['admin_email'] ?? '';
            if (empty($to)) {
                $to = trim($firma['email'] ?? '');
            }

            if (!empty($to)) {
                $body = "i-BOK - " . __('contact.title') . "\n";
                $body .= "---\n";
                $body .= __('contact.your_name') . ": {$name}\n";
                $body .= __('contact.your_email') . ": {$email}\n";
                $body .= __('dashboard.client_id') . ": {$client_id}\n";
                $body .= "---\n\n";
                $body .= $message;

                $result = smtp_send_mail($to, "i-BOK: " . $subject, $body, $email, $name);

                if ($result['success']) {
                    $msg_sent = true;
                    ibok_log("Email kontaktowy wysłany przez klienta {$client_id} do {$to}", 'info');
                } else {
                    // Zapisz do pliku jako backup
                    $log_msg = date('Y-m-d H:i:s') . " | Od: {$name} <{$email}> | Klient: {$client_id} | Temat: {$subject} | {$message}\n";
                    @file_put_contents(IBOK_LOGS_DIR . '/contact_messages.log', $log_msg, FILE_APPEND | LOCK_EX);
                    $msg_error = __('contact.error_send');
                    ibok_log("Email nie wysłany ({$result['error']}), zapisano do pliku. Klient: {$client_id}", 'warning');
                }
            } else {
                $msg_error = __('contact.error_send');
            }
        }
    }
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-envelope me-2"></i> <?= __('contact.title') ?>
    </h4>

    <?= ibok_help_section('kontakt', __('help.show_help'), __('help.kontakt_section_content')) ?>

    <div class="row g-4">
        <!-- Formularz -->
        <div class="col-lg-7">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-send me-1"></i> <?= __('contact.btn_send') ?>
                </div>
                <div class="card-body">
                    <?php if ($msg_sent): ?>
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle me-1"></i> <?= __('contact.success') ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($msg_error): ?>
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle me-1"></i> <?= e($msg_error) ?>
                        </div>
                    <?php endif; ?>

                    <form method="post" action="index.php?page=kontakt">
                        <?= csrf_field() ?>
                        <input type="hidden" name="send_contact" value="1">

                        <div class="mb-3">
                            <label for="name" class="form-label"><?= __('contact.your_name') ?></label>
                            <input type="text" class="form-control" id="name" name="name"
                                   value="<?= e($_POST['name'] ?? $client_name) ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="email" class="form-label"><?= __('contact.your_email') ?></label>
                            <input type="email" class="form-control" id="email" name="email"
                                   value="<?= e($_POST['email'] ?? '') ?>" required>
                        </div>

                        <div class="mb-3">
                            <label for="subject_select" class="form-label"><?= __('contact.subject') ?><?= ibok_tooltip(__('help.tooltip_subject')) ?></label>
                            <select class="form-select" id="subject_select">
                                <option value=""><?= __('contact.subject_select') ?></option>
                                <option value="<?= e(__('contact.subject_failure')) ?>"><?= __('contact.subject_failure') ?></option>
                                <option value="<?= e(__('contact.subject_tariff')) ?>"><?= __('contact.subject_tariff') ?></option>
                                <option value="<?= e(__('contact.subject_invoice')) ?>"><?= __('contact.subject_invoice') ?></option>
                                <option value="<?= e(__('contact.subject_contract')) ?>"><?= __('contact.subject_contract') ?></option>
                                <option value="<?= e(__('contact.subject_data')) ?>"><?= __('contact.subject_data') ?></option>
                                <option value="__other__"><?= __('contact.subject_other') ?></option>
                            </select>
                            <input type="text" class="form-control mt-2 d-none" id="subject_custom" name="subject"
                                   value="<?= e($_POST['subject'] ?? $prefill_subject) ?>" placeholder="<?= __('contact.subject') ?>">
                        </div>

                        <div class="mb-3">
                            <label for="message" class="form-label"><?= __('contact.message') ?><?= ibok_tooltip(__('help.tooltip_message')) ?></label>
                            <textarea class="form-control" id="message" name="message" rows="6" required><?= e($_POST['message'] ?? $prefill_message) ?></textarea>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-send me-1"></i> <?= __('contact.btn_send') ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Dane kontaktowe firmy -->
        <div class="col-lg-5">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-building me-1"></i> <?= __('dashboard.company_info') ?>
                </div>
                <div class="card-body">
                    <h5 class="fw-bold mb-3"><?= e($firma['nazwa'] ?? '') ?></h5>

                    <?php if (!empty($firma['adres1']) || !empty($firma['adres2'])): ?>
                    <div class="mb-3">
                        <h6 class="text-muted small text-uppercase"><?= __('contact.address') ?></h6>
                        <p class="mb-0">
                            <?= e($firma['adres1'] ?? '') ?><br>
                            <?= e($firma['adres2'] ?? '') ?>
                        </p>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty(trim($firma['telefon'] ?? ''))): ?>
                    <div class="mb-3">
                        <h6 class="text-muted small text-uppercase"><?= __('contact.phone') ?></h6>
                        <p class="mb-0">
                            <i class="bi bi-telephone me-1"></i>
                            <a href="tel:<?= e(trim($firma['telefon'])) ?>"><?= e(trim($firma['telefon'])) ?></a>
                        </p>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty(trim($firma['email'] ?? ''))): ?>
                    <div class="mb-3">
                        <h6 class="text-muted small text-uppercase"><?= __('contact.email') ?></h6>
                        <p class="mb-0">
                            <i class="bi bi-envelope me-1"></i>
                            <a href="mailto:<?= e(trim($firma['email'])) ?>"><?= e(trim($firma['email'])) ?></a>
                        </p>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty(trim($firma['www'] ?? ''))): ?>
                    <div class="mb-3">
                        <h6 class="text-muted small text-uppercase"><?= __('contact.www') ?></h6>
                        <p class="mb-0">
                            <i class="bi bi-globe me-1"></i>
                            <a href="http://<?= e(trim($firma['www'])) ?>" target="_blank"><?= e(trim($firma['www'])) ?></a>
                        </p>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($firma['nip'])): ?>
                    <div class="mb-3">
                        <h6 class="text-muted small text-uppercase">NIP</h6>
                        <p class="mb-0"><?= e($firma['nip']) ?></p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php
            $stopka = read_admin_text('stopka.txt');
            if (!empty($stopka)):
            ?>
            <div class="card mt-3">
                <div class="card-body">
                    <?= $stopka ?>
                </div>
            </div>
            <?php endif; ?>

        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
(function() {
    var sel = document.getElementById('subject_select');
    var inp = document.getElementById('subject_custom');
    if (!sel || !inp) return;

    sel.addEventListener('change', function() {
        if (this.value === '__other__') {
            inp.classList.remove('d-none');
            inp.required = true;
            inp.value = '';
            inp.focus();
        } else if (this.value === '') {
            inp.classList.add('d-none');
            inp.required = true;
            inp.value = '';
        } else {
            inp.classList.add('d-none');
            inp.required = false;
            inp.value = this.value;
        }
    });

    // Restore state on page load (after POST with errors)
    var current = inp.value;
    if (current) {
        var found = false;
        for (var i = 0; i < sel.options.length; i++) {
            if (sel.options[i].value === current) {
                sel.selectedIndex = i;
                found = true;
                break;
            }
        }
        if (!found) {
            sel.value = '__other__';
            inp.classList.remove('d-none');
            inp.required = true;
        }
    }

    // On form submit, ensure subject is set
    var form = sel.closest('form');
    if (form) {
        form.addEventListener('submit', function() {
            if (sel.value && sel.value !== '__other__' && sel.value !== '') {
                inp.value = sel.value;
            }
        });
    }
})();
</script>
