<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$pageTitle = 'Podaci o nalogu';
$pageSubtitle = 'Profilna fotografija, kontakt podaci i bezbednost naloga';
$passwordErrors = [];
$photoErrors = [];

function avatar_upload_extension_from_image_type(int $imageType): ?string
{
    if ($imageType === IMAGETYPE_JPEG) {
        return 'jpg';
    }
    if ($imageType === IMAGETYPE_PNG) {
        return 'png';
    }
    return null;
}

function save_avatar_bytes(int $userId, string $bytes, string $extension, array $user): array
{
    $uploadDir = __DIR__ . '/uploads/avatars';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        return [false, 'Folder za fotografije nije moguće kreirati. Proverite dozvole na hostingu.'];
    }
    if (!is_writable($uploadDir)) {
        return [false, 'Folder za fotografije nije upisiv. Proverite dozvole za uploads/avatars.'];
    }

    $filename = 'user-' . $userId . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
    $relativePath = 'uploads/avatars/' . $filename;
    $targetPath = $uploadDir . '/' . $filename;

    if (file_put_contents($targetPath, $bytes, LOCK_EX) === false) {
        return [false, 'Fotografija nije mogla biti sačuvana. Proverite upload podešavanja na hostingu.'];
    }
    @chmod($targetPath, 0644);

    $oldPhoto = trim((string)($user['profile_photo'] ?? ''));
    try {
        $stmt = db()->prepare('UPDATE users SET profile_photo = ?, updated_at = ? WHERE id = ?');
        $stmt->execute([$relativePath, now_app_datetime_sql(), $userId]);
    } catch (PDOException $e) {
        if (is_file($targetPath)) {
            @unlink($targetPath);
        }
        return [false, 'Baza nije ažurirana. Importujte poslednju upgrade SQL migraciju, pa pokušajte ponovo.'];
    }

    if ($oldPhoto !== '' && $oldPhoto !== $relativePath) {
        $oldPath = profile_photo_storage_path($oldPhoto);
        if ($oldPath !== null) {
            @unlink($oldPath);
        }
    }

    return [true, $relativePath];
}

if (is_post()) {
    validate_csrf();
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'change_password') {
        $oldPassword = (string)($_POST['old_password'] ?? '');
        $newPassword = (string)($_POST['new_password'] ?? '');
        $confirmPassword = (string)($_POST['confirm_password'] ?? '');

        $stmt = db()->prepare('SELECT password_hash FROM users WHERE id = ? LIMIT 1');
        $stmt->execute([(int)$user['id']]);
        $row = $stmt->fetch();

        if (!$row || !password_verify($oldPassword, (string)$row['password_hash'])) {
            $passwordErrors[] = 'Stara lozinka nije ispravna.';
        }
        if (strlen($newPassword) < 10) {
            $passwordErrors[] = 'Nova lozinka mora imati najmanje 10 karaktera.';
        }
        if ($newPassword !== $confirmPassword) {
            $passwordErrors[] = 'Nova lozinka i ponovljena nova lozinka nisu iste.';
        }
        if ($oldPassword !== '' && $newPassword !== '' && $oldPassword === $newPassword) {
            $passwordErrors[] = 'Nova lozinka mora biti drugačija od stare lozinke.';
        }

        if (!$passwordErrors) {
            $update = db()->prepare('UPDATE users SET password_hash = ?, must_change_password = 0, updated_at = ? WHERE id = ?');
            $update->execute([password_hash($newPassword, PASSWORD_DEFAULT), now_app_datetime_sql(), (int)$user['id']]);
            session_regenerate_id(true);
            unset($_SESSION['csrf_token']);
            notify_user((int)$user['id'], 'Lozinka je promenjena', 'Lozinka za vaš nalog je uspešno promenjena.', 'account.php#password');
            flash('success', 'Lozinka je uspešno promenjena.');
            redirect('account.php#password');
        }
    }

    if ($action === 'delete_photo') {
        $oldPhoto = trim((string)($user['profile_photo'] ?? ''));
        try {
            $stmt = db()->prepare('UPDATE users SET profile_photo = NULL, updated_at = ? WHERE id = ?');
            $stmt->execute([now_app_datetime_sql(), (int)$user['id']]);
        } catch (PDOException $e) {
            $photoErrors[] = 'Baza nije ažurirana. Importujte poslednju upgrade SQL migraciju, pa pokušajte ponovo.';
        }
        if (!$photoErrors && $oldPhoto !== '') {
            $oldPath = profile_photo_storage_path($oldPhoto);
            if ($oldPath !== null) {
                @unlink($oldPath);
            }
        }
        if (!$photoErrors) {
            flash('success', 'Profilna fotografija je uklonjena.');
            redirect('account.php#photo');
        }
    }

    if ($action === 'upload_photo') {
        if (!isset($_FILES['profile_photo']) || !is_array($_FILES['profile_photo'])) {
            $photoErrors[] = 'Niste izabrali fotografiju za upload.';
        } else {
            $file = $_FILES['profile_photo'];
            if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                $photoErrors[] = 'Upload fotografije nije uspeo. Proverite fajl i pokušajte ponovo.';
            } elseif ((int)($file['size'] ?? 0) <= 0) {
                $photoErrors[] = 'Izabrani fajl je prazan.';
            } elseif ((int)$file['size'] > profile_photo_max_size_bytes()) {
                $photoErrors[] = 'Fotografija može imati maksimalno 2 MB.';
            } else {
                $tmpPath = (string)($file['tmp_name'] ?? '');
                $originalInfo = @getimagesize($tmpPath);
                $originalExtension = is_array($originalInfo) ? avatar_upload_extension_from_image_type((int)($originalInfo[2] ?? 0)) : null;

                if ($originalExtension === null) {
                    $photoErrors[] = 'Dozvoljeni formati su JPG i PNG.';
                } else {
                    $croppedData = trim((string)($_POST['cropped_photo_data'] ?? ''));
                    $bytes = '';
                    $extension = $originalExtension;

                    if ($croppedData !== '') {
                        if (!preg_match('#^data:image/(jpeg|png);base64,([a-zA-Z0-9+/=\r\n]+)$#', $croppedData, $matches)) {
                            $photoErrors[] = 'Preview fotografije nije validan. Izaberite sliku ponovo i pokušajte opet.';
                        } else {
                            $decoded = base64_decode(preg_replace('/\s+/', '', $matches[2]), true);
                            if ($decoded === false || $decoded === '') {
                                $photoErrors[] = 'Preview fotografije nije moguće obraditi. Izaberite sliku ponovo i pokušajte opet.';
                            } elseif (strlen($decoded) > profile_photo_max_size_bytes()) {
                                $photoErrors[] = 'Obrađena fotografija može imati maksimalno 2 MB.';
                            } else {
                                $croppedInfo = @getimagesizefromstring($decoded);
                                $croppedExtension = is_array($croppedInfo) ? avatar_upload_extension_from_image_type((int)($croppedInfo[2] ?? 0)) : null;
                                if ($croppedExtension === null) {
                                    $photoErrors[] = 'Obrađena fotografija mora biti JPG ili PNG.';
                                } else {
                                    $bytes = $decoded;
                                    $extension = $croppedExtension;
                                }
                            }
                        }
                    } else {
                        $raw = @file_get_contents($tmpPath);
                        if ($raw === false || $raw === '') {
                            $photoErrors[] = 'Fotografiju nije moguće pročitati. Pokušajte sa drugom slikom.';
                        } else {
                            $bytes = $raw;
                        }
                    }

                    if (!$photoErrors) {
                        [$saved, $result] = save_avatar_bytes((int)$user['id'], $bytes, $extension, $user);
                        if (!$saved) {
                            $photoErrors[] = $result;
                        } else {
                            flash('success', 'Profilna fotografija je uspešno sačuvana.');
                            redirect('account.php#photo');
                        }
                    }
                }
            }
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<section class="account-layout">
    <article class="card card-pad account-summary">
        <div class="section-heading">
            <div>
                <span class="badge">Korisnički nalog</span>
                <h2>Podaci o nalogu</h2>
                <p>Osnovni podaci koje sistem koristi za prikaz profila, obaveštenja i komunikaciju.</p>
            </div>
        </div>
        <div class="profile-photo-preview account-preview">
            <?= user_avatar_html($user, 'employee-avatar') ?>
            <div>
                <strong><?= e($user['name']) ?></strong>
                <span><?= e(user_roles_summary($user)) ?> · <?= e(employee_value($user['job_title'] ?? null)) ?></span>
                <small><?= e($user['email']) ?></small>
            </div>
        </div>
        <div class="employee-info-grid account-info-grid">
            <div class="employee-info-item">
                <span class="info-icon">📍</span>
                <div><small>Lokacija</small><strong><?= e(employee_value($user['location'] ?? null)) ?></strong></div>
            </div>
            <div class="employee-info-item">
                <span class="info-icon info-navy">▦</span>
                <div><small>Sektor</small><strong><?= e(employee_value($user['department'] ?? null)) ?></strong></div>
            </div>
            <div class="employee-info-item">
                <span class="info-icon info-red">👤</span>
                <div><small>Nadređeni</small><strong><?= e(employee_value($user['manager_name'] ?? null)) ?></strong></div>
            </div>
            <div class="employee-info-item copy-item">
                <span class="info-icon info-green">✉</span>
                <div><small>E-pošta</small><strong><?= e($user['email']) ?></strong></div>
                <button type="button" class="copy-button" data-copy-value="<?= e($user['email']) ?>">Kopiraj</button>
            </div>
            <div class="employee-info-item copy-item">
                <span class="info-icon info-purple">☎</span>
                <div><small>Telefon</small><strong><?= e(employee_value($user['phone'] ?? null)) ?></strong></div>
                <?php if (!empty($user['phone'])): ?><button type="button" class="copy-button" data-copy-value="<?= e($user['phone']) ?>">Kopiraj</button><?php endif; ?>
            </div>
            <div class="employee-info-item">
                <span class="info-icon info-orange">◷</span>
                <div><small>Poslednja prijava</small><strong><?= e(format_datetime($user['last_login_at'] ?? null)) ?></strong></div>
            </div>
        </div>
    </article>

    <div class="account-action-grid" aria-label="Podešavanja naloga">
    <article class="card card-pad profile-photo-card account-option-card" id="photo">
        <div class="section-heading">
            <div>
                <span class="badge">Fotografija</span>
                <h2>Profilna fotografija</h2>
                <p>Izaberite JPG ili PNG fotografiju do 2 MB, podesite kadar i sačuvajte prikaz za panel i korisnički meni.</p>
            </div>
        </div>

        <?php foreach ($photoErrors as $error): ?>
            <div class="alert alert-danger"><?= e($error) ?></div>
        <?php endforeach; ?>

        <form method="post" enctype="multipart/form-data" class="stacked-form profile-photo-form" id="profilePhotoForm">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="upload_photo">
            <input type="hidden" name="cropped_photo_data" id="croppedPhotoData" value="">

            <div class="profile-upload-field">
                <span class="form-label">Izaberite novu fotografiju</span>
                <label class="file-dropzone" id="profilePhotoDropzone" for="profilePhotoInput">
                    <input id="profilePhotoInput" class="file-drop-input" type="file" name="profile_photo" accept="image/jpeg,image/png,.jpg,.jpeg,.png" required>
                    <span class="file-drop-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24" width="26" height="26" focusable="false"><path d="M12 3.5a5.2 5.2 0 0 1 5.1 4.2A4.8 4.8 0 0 1 17 17.3h-3.2v-2H17a2.8 2.8 0 0 0 .1-5.6l-1.5-.1-.3-1.5a3.4 3.4 0 0 0-6.6-.5l-.4 1.2-1.2.2a3.1 3.1 0 0 0 .4 6.2h2.8v2H7.5A5.1 5.1 0 0 1 6.9 7 5.4 5.4 0 0 1 12 3.5Zm0 6.1 3.1 3.1-1.4 1.4-1.7-1.7v6.1h-2v-6.1l-1.7 1.7-1.4-1.4L12 9.6Z" fill="currentColor"/></svg>
                    </span>
                    <span class="file-drop-copy">
                        <strong>Kliknite za izbor fotografije</strong>
                        <small>ili prevucite JPG/PNG fotografiju ovde · maksimalno 2 MB</small>
                    </span>
                    <span class="file-drop-name" id="profilePhotoFileName">Nije izabrana fotografija</span>
                </label>
            </div>

            <div class="photo-cropper" id="profileCropper" hidden>
                <div class="photo-cropper-grid">
                    <div>
                        <div class="cropper-stage" id="profileCropStage" aria-label="Preview i izbor kadra fotografije">
                            <img id="profileCropImage" alt="Izabrana profilna fotografija">
                            <span class="cropper-frame" aria-hidden="true"></span>
                        </div>
                        <p class="cropper-help">Prevucite fotografiju i podesite uvećanje. Vidljivi kvadrat biće sačuvan kao profilna fotografija.</p>
                        <label class="range-label">Uvećanje
                            <input id="profileCropZoom" type="range" min="1" max="3" step="0.01" value="1">
                        </label>
                    </div>
                    <div class="cropper-result">
                        <span>Pregled</span>
                        <img id="profileCropResult" alt="Pregled odabranog kadra">
                    </div>
                </div>
            </div>

            <div class="inline-actions">
                <button class="button button-primary" type="submit">Sačuvaj fotografiju</button>
                <?php if (trim((string)($user['profile_photo'] ?? '')) !== ''): ?>
                    <button class="button button-light" type="submit" form="deletePhotoForm">Ukloni fotografiju</button>
                <?php endif; ?>
            </div>
        </form>
        <?php if (trim((string)($user['profile_photo'] ?? '')) !== ''): ?>
            <form id="deletePhotoForm" method="post" class="profile-photo-delete" data-confirm="Da li želite da uklonite profilnu fotografiju?">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="delete_photo">
            </form>
        <?php endif; ?>
    </article>

    <article class="card card-pad narrow-card account-option-card" id="password">
        <div class="section-heading">
            <div>
                <span class="badge">Bezbednost</span>
                <h2>Promena lozinke</h2>
                <p>Unesite staru lozinku, zatim novu lozinku i potvrdu nove lozinke.</p>
            </div>
        </div>

        <?php foreach ($passwordErrors as $error): ?>
            <div class="alert alert-danger"><?= e($error) ?></div>
        <?php endforeach; ?>

        <form method="post" class="stacked-form password-form" autocomplete="off">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="change_password">
            <label>Stara lozinka
                <div class="polje-lozinka">
                    <input id="old_password" type="password" name="old_password" required autocomplete="current-password">
                    <button class="password-toggle" type="button" data-toggle-password="old_password" aria-label="Prikaži lozinku" title="Prikaži lozinku"><span aria-hidden="true" class="eye-icon"><svg viewBox="0 0 24 24" width="20" height="20" focusable="false"><path d="M12 5C6.7 5 3.1 8.5 1.8 12c1.3 3.5 4.9 7 10.2 7s8.9-3.5 10.2-7C20.9 8.5 17.3 5 12 5Zm0 11a4 4 0 1 1 0-8 4 4 0 0 1 0 8Zm0-2.2a1.8 1.8 0 1 0 0-3.6 1.8 1.8 0 0 0 0 3.6Z" fill="currentColor"/></svg></span></button>
                </div>
            </label>
            <label>Nova lozinka
                <div class="polje-lozinka">
                    <input id="new_password" type="password" name="new_password" required minlength="10" autocomplete="new-password">
                    <button class="password-toggle" type="button" data-toggle-password="new_password" aria-label="Prikaži lozinku" title="Prikaži lozinku"><span aria-hidden="true" class="eye-icon"><svg viewBox="0 0 24 24" width="20" height="20" focusable="false"><path d="M12 5C6.7 5 3.1 8.5 1.8 12c1.3 3.5 4.9 7 10.2 7s8.9-3.5 10.2-7C20.9 8.5 17.3 5 12 5Zm0 11a4 4 0 1 1 0-8 4 4 0 0 1 0 8Zm0-2.2a1.8 1.8 0 1 0 0-3.6 1.8 1.8 0 0 0 0 3.6Z" fill="currentColor"/></svg></span></button>
                </div>
            </label>
            <label>Ponovite novu lozinku
                <div class="polje-lozinka">
                    <input id="confirm_password" type="password" name="confirm_password" required minlength="10" autocomplete="new-password">
                    <button class="password-toggle" type="button" data-toggle-password="confirm_password" aria-label="Prikaži lozinku" title="Prikaži lozinku"><span aria-hidden="true" class="eye-icon"><svg viewBox="0 0 24 24" width="20" height="20" focusable="false"><path d="M12 5C6.7 5 3.1 8.5 1.8 12c1.3 3.5 4.9 7 10.2 7s8.9-3.5 10.2-7C20.9 8.5 17.3 5 12 5Zm0 11a4 4 0 1 1 0-8 4 4 0 0 1 0 8Zm0-2.2a1.8 1.8 0 1 0 0-3.6 1.8 1.8 0 0 0 0 3.6Z" fill="currentColor"/></svg></span></button>
                </div>
            </label>
            <div class="inline-actions">
                <button class="button button-primary" type="submit">Sačuvaj novu lozinku</button>
            </div>
        </form>
    </article>
    </div>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
