<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/guvenlik_kontrol.php';

$sayfa_baslik = __("add_new_user");
$aktif_sirket_id = $_SESSION['aktif_sirket_id'] ?? 0;

// Yetki kontrolü - Sadece admin ve yönetici erişebilir
if (!isset($_SESSION['yetki_seviyesi']) || !in_array($_SESSION['yetki_seviyesi'], ['admin', 'yonetici'])) {
    $_SESSION['hata'] = __("no_permission_to_access_this_page");
    header("Location: index.php");
    exit();
}

// Şirket kontrolü
if (empty($aktif_sirket_id)) {
    $_SESSION['hata'] = __("company_selection_required_for_adding_user");
    header("Location: index.php");
    exit();
}

$hata = '';
$form_verileri = [
    'kullanici_adi' => '',
    'ad_soyad' => '',
    'email' => '',
    'yetki_seviyesi' => 'kullanici',
    'aktif' => 1,
    'aciklama' => ''
];

// Form gönderildi
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $form_verileri = [
        'kullanici_adi' => trim($_POST['kullanici_adi'] ?? ''),
        'ad_soyad' => trim($_POST['ad_soyad'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'sifre' => $_POST['sifre'] ?? '',
        'sifre_tekrar' => $_POST['sifre_tekrar'] ?? '',
        'yetki_seviyesi' => $_POST['yetki_seviyesi'] ?? 'kullanici',
        'aktif' => isset($_POST['aktif']) ? 1 : 0,
        'aciklama' => trim($_POST['aciklama'] ?? '')
    ];
    
    // Veri doğrulama
    if (empty($form_verileri['kullanici_adi'])) {
        $hata = __("username_required");
    } elseif (strlen($form_verileri['kullanici_adi']) < 3) {
        $hata = __("username_min_length");
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $form_verileri['kullanici_adi'])) {
        $hata = __("username_invalid_chars");
    } elseif (empty($form_verileri['ad_soyad'])) {
        $hata = __("full_name_required");
    } elseif (!empty($form_verileri['email']) && !filter_var($form_verileri['email'], FILTER_VALIDATE_EMAIL)) {
        $hata = __("invalid_email_format");
    } elseif (empty($form_verileri['sifre'])) {
        $hata = __("password_required");
    } elseif (strlen($form_verileri['sifre']) < 8) {
        $hata = __("password_strength_requirement");
    } elseif (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&+])[A-Za-z\d@$!%*?&+]{8,}$/', $form_verileri['sifre'])) {
        $hata = __("password_strength_requirement");
    } elseif ($form_verileri['sifre'] !== $form_verileri['sifre_tekrar']) {
        $hata = __("passwords_do_not_match");
    } elseif (!in_array($form_verileri['yetki_seviyesi'], ['admin', 'yonetici', 'kullanici', 'misafir'])) {
        $hata = __("invalid_permission_level");
    }
    
    // Yetki kontrolü - Yönetici admin oluşturamaz
    if ($_SESSION['yetki_seviyesi'] === 'yonetici' && $form_verileri['yetki_seviyesi'] === 'admin') {
        $hata = __("no_permission_to_create_admin");
    }
    
    if (empty($hata)) {
        try {
            // Varsayılan yetkileri ayarla
            $yetkiler = [];
            switch ($form_verileri['yetki_seviyesi']) {
                case 'admin':
                    $yetkiler = ['tum_yetkiler' => true];
                    break;
                case 'yonetici':
                    $yetkiler = [
                        'stok_yonetimi' => true,
                        'satis_islemleri' => true,
                        'alis_islemleri' => true,
                        'cari_yonetimi' => true,
                        'hesap_yonetimi' => true,
                        'raporlar' => true,
                        'faturalar' => true
                    ];
                    break;
                case 'kullanici':
                    $yetkiler = [
                        'satis_islemleri' => true,
                        'stok_goruntuleme' => true,
                        'cari_goruntuleme' => true,
                        'faturalar' => true
                    ];
                    break;
                case 'misafir':
                    $yetkiler = [
                        'stok_goruntuleme' => true,
                        'raporlar' => true
                    ];
                    break;
            }
            
            $form_verileri['yetkiler'] = $yetkiler;
            
            $kullanici_id = kullanici_ekle($db, $form_verileri);
            
            if ($kullanici_id) {
                $_SESSION['mesaj'] = __("user_added_successfully");
                header("Location: kullanicilar.php");
                exit();
            } else {
                $hata = __("error_adding_user");
            }
        } catch (Exception $e) {
            $hata = $e->getMessage();
        }
    }
}

// Yetki seviyeleri
$yetki_seviyeleri = [
    'kullanici' => __("user"),
    'misafir' => __("guest")
];

// Admin sadece admin oluşturabilir
if ($_SESSION['yetki_seviyesi'] === 'admin') {
    $yetki_seviyeleri['yonetici'] = __("manager");
    $yetki_seviyeleri['admin'] = __("admin");
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= __("odjoo_management") ?> - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="main-content">
        <div class="container mt-4 mb-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-person-plus"></i> <?= temizle($sayfa_baslik) ?></h2>
            <a href="kullanicilar.php" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> <?= __("go_back") ?>
            </a>
        </div>

        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-person-fill"></i> <?= __("user_information") ?></h5>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($hata)): ?>
                            <div class="alert alert-danger">
                                <i class="bi bi-exclamation-triangle"></i> <?= temizle($hata) ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="kullanici_adi" class="form-label"><?= __("username") ?> <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="kullanici_adi" name="kullanici_adi" 
                                               value="<?= temizle($form_verileri['kullanici_adi']) ?>" required>
                                        <div class="form-text"><?= __("username_allowed_chars") ?></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="ad_soyad" class="form-label"><?= __("full_name") ?> <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="ad_soyad" name="ad_soyad" 
                                               value="<?= temizle($form_verileri['ad_soyad']) ?>" required>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="email" class="form-label"><?= __("email") ?></label>
                                        <input type="email" class="form-control" id="email" name="email" 
                                               value="<?= temizle($form_verileri['email']) ?>">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label"><?= __("permission_levels") ?> <span class="text-danger">*</span></label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="yetki_seviyesi" id="yetki_admin" value="admin" 
                                                <?= ($form_verileri['yetki_seviyesi'] == 'admin') ? 'checked' : '' ?> 
                                                <?= ($_SESSION['yetki_seviyesi'] !== 'admin') ? 'disabled' : '' ?> >
                                            <label class="form-check-label" for="yetki_admin">
                                                <span class="badge bg-danger"><?= __("admin") ?></span>
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="yetki_seviyesi" id="yetki_yonetici" value="yonetici"
                                                <?= ($form_verileri['yetki_seviyesi'] == 'yonetici') ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="yetki_yonetici">
                                                <span class="badge bg-warning"><?= __("manager") ?></span>
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="yetki_seviyesi" id="yetki_kullanici" value="kullanici"
                                                <?= ($form_verileri['yetki_seviyesi'] == 'kullanici' || empty($form_verileri['yetki_seviyesi'])) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="yetki_kullanici">
                                                <span class="badge bg-primary"><?= __("user") ?></span>
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="yetki_seviyesi" id="yetki_misafir" value="misafir"
                                                <?= ($form_verileri['yetki_seviyesi'] == 'misafir') ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="yetki_misafir">
                                                <span class="badge bg-secondary"><?= __("guest") ?></span>
                                            </label>
                                        </div>
                                        <div class="mt-2">
                                            <a href="#permission-details" class="small text-decoration-none" data-bs-toggle="collapse">
                                                <i class="bi bi-info-circle"></i> <?= __("view_permission_details") ?>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="sifre" class="form-label"><?= __("password") ?> <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="sifre" name="sifre" required>
                                        <ul class="list-unstyled mt-2" id="password-validator">
                                            <li id="pv-length" style="color: #888;"><i class="bi bi-dot"></i> En az 8 karakter</li>
                                            <li id="pv-upper" style="color: #888;"><i class="bi bi-dot"></i> Büyük harf</li>
                                            <li id="pv-lower" style="color: #888;"><i class="bi bi-dot"></i> Küçük harf</li>
                                            <li id="pv-digit" style="color: #888;"><i class="bi bi-dot"></i> Rakam</li>
                                            <li id="pv-special" style="color: #888;"><i class="bi bi-dot"></i> Özel karakter (@$!%*?&+)</li>
                                        </ul>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="sifre_tekrar" class="form-label"><?= __("confirm_password") ?> <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="sifre_tekrar" name="sifre_tekrar" required>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="aciklama" class="form-label"><?= __("description") ?></label>
                                <textarea class="form-control" id="aciklama" name="aciklama" rows="3"><?= temizle($form_verileri['aciklama']) ?></textarea>
                            </div>

                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="aktif" name="aktif" 
                                           <?= $form_verileri['aktif'] ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="aktif">
                                        <?= __("user_active") ?>
                                    </label>
                                </div>
                            </div>

                            <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                                <a href="kullanicilar.php" class="btn btn-secondary me-md-2">
                                    <i class="bi bi-x-circle"></i> <?= __("cancel") ?>
                                </a>
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-save"></i> <?= __("save") ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Yetki Açıklamaları -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-info-circle"></i> <?= __("permission_level_descriptions") ?></h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6><span class="badge bg-danger"><?= __("admin") ?></span></h6>
                                <ul class="small">
                                    <li><?= __("can_do_all_operations") ?></li>
                                    <li><?= __("user_management") ?></li>
                                    <li><?= __("system_settings") ?></li>
                                    <li><?= __("log_records") ?></li>
                                </ul>
                                
                                <h6><span class="badge bg-warning"><?= __("manager") ?></span></h6>
                                <ul class="small">
                                    <li><?= __("stock_management") ?></li>
                                    <li><?= __("sales_purchase_operations") ?></li>
                                    <li><?= __("current_account_management") ?></li>
                                    <li><?= __("account_management") ?></li>
                                    <li><?= __("reports_and_invoices") ?></li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h6><span class="badge bg-primary"><?= __("user") ?></span></h6>
                                <ul class="small">
                                    <li><?= __("sales_operations") ?></li>
                                    <li><?= __("view_stock") ?></li>
                                    <li><?= __("view_current_account") ?></li>
                                    <li><?= __("invoice_operations") ?></li>
                                </ul>
                                
                                <h6><span class="badge bg-secondary"><?= __("guest") ?></span></h6>
                                <ul class="small">
                                    <li><?= __("only_view_stock") ?></li>
                                    <li><?= __("view_reports") ?></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.querySelector('.sidebar');
            const mainContent = document.querySelector('.main-content');
            
            if (sidebarToggle && sidebar && mainContent) {
                sidebarToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    sidebar.classList.toggle('show');
                    mainContent.classList.toggle('sidebar-collapsed');
                });
            }
        });
    </script>
    <?php include __DIR__ . '/../includes/footer.php'; ?>
    <script>
        // Şifre eşleşme kontrolü
        document.getElementById('sifre_tekrar').addEventListener('input', function() {
            const sifre = document.getElementById('sifre').value;
            const sifreTekrar = this.value;
            
            if (sifre !== sifreTekrar) {
                this.setCustomValidity('<?= __("passwords_do_not_match") ?>');
            } else {
                this.setCustomValidity('');
            }
        });

        // Şifre güçlü mü kontrolü ve anlık validator
        const sifreInput = document.getElementById('sifre');
        const pvLength = document.getElementById('pv-length');
        const pvUpper = document.getElementById('pv-upper');
        const pvLower = document.getElementById('pv-lower');
        const pvDigit = document.getElementById('pv-digit');
        const pvSpecial = document.getElementById('pv-special');

        sifreInput.addEventListener('input', function() {
            const sifre = this.value;
            // Kontroller
            const hasLength = sifre.length >= 8;
            const hasUpper = /[A-Z]/.test(sifre);
            const hasLower = /[a-z]/.test(sifre);
            const hasDigit = /\d/.test(sifre);
            const hasSpecial = /[@$!%*?&+]/.test(sifre);

            // Güncelle
            pvLength.style.color = hasLength ? 'green' : '#888';
            pvLength.innerHTML = (hasLength ? '<i class="bi bi-check-circle-fill"></i>' : '<i class="bi bi-dot"></i>') + ' En az 8 karakter';

            pvUpper.style.color = hasUpper ? 'green' : '#888';
            pvUpper.innerHTML = (hasUpper ? '<i class="bi bi-check-circle-fill"></i>' : '<i class="bi bi-dot"></i>') + ' Büyük harf';

            pvLower.style.color = hasLower ? 'green' : '#888';
            pvLower.innerHTML = (hasLower ? '<i class="bi bi-check-circle-fill"></i>' : '<i class="bi bi-dot"></i>') + ' Küçük harf';

            pvDigit.style.color = hasDigit ? 'green' : '#888';
            pvDigit.innerHTML = (hasDigit ? '<i class="bi bi-check-circle-fill"></i>' : '<i class="bi bi-dot"></i>') + ' Rakam';

            pvSpecial.style.color = hasSpecial ? 'green' : '#888';
            pvSpecial.innerHTML = (hasSpecial ? '<i class="bi bi-check-circle-fill"></i>' : '<i class="bi bi-dot"></i>') + ' Özel karakter (@$!%*?&+)';

            // Eski validasyon
            const gucluSifre = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&+])[A-Za-z\d@$!%*?&+]{8,}$/;
            if (!gucluSifre.test(sifre)) {
                this.setCustomValidity('<?= __("password_strength_requirement") ?>');
            } else {
                this.setCustomValidity('');
            }
        });
    </script>
</body>
                   
              
            </div>
        </div>
    </div>
</html>

