<?php
session_start();
require_once 'config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Handle user addition (admin only)
if ($_SESSION['user']['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $first_name = $_POST['first_name'] ?? '';
    $last_name = $_POST['last_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $role = $_POST['role'] ?? 'user';
    
    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($first_name) || empty($last_name)) {
        $error = 'Tüm alanlar zorunludur.';
    } else {
        // Check if user already exists
        $email = $con->real_escape_string($email);
        $username = $con->real_escape_string($username);
        
        $check_sql = "SELECT id FROM users WHERE email = '$email' OR username = '$username'";
        $check_result = $con->query($check_sql);
        
        if ($check_result->num_rows > 0) {
            $error = 'Bu email veya kullanıcı adı zaten kullanılıyor.';
        } else {
            // Hash password
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            
            // Insert new user
            $insert_sql = "INSERT INTO users (username, email, password_hash, first_name, last_name, phone, role, created_at) 
                           VALUES ('$username', '$email', '$password_hash', '$first_name', '$last_name', '$phone', '$role', NOW())";
            
            if ($con->query($insert_sql)) {
                $success = 'Kullanıcı başarıyla eklendi!';
            } else {
                $error = 'Kullanıcı eklenirken bir hata oluştu.';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kullanıcı Ekle - DMAppsESP</title>
    
    <!-- POS AdminLTE CSS -->
    <link rel="stylesheet" href="assets/dist/css/adminlte.min.css">
    <link rel="stylesheet" href="assets/plugins/fontawesome-free/css/all.min.css">
    <link rel="stylesheet" href="assets/plugins/sweetalert2/sweetalert2.min.css">
    
    <style>
        .content-wrapper {
            background: #f4f6f9;
        }
        .card {
            border: none;
            box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2);
        }
        .btn-primary {
            background: #667eea;
            border-color: #667eea;
        }
        .btn-primary:hover {
            background: #5a67d8;
            border-color: #5a67d8;
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <!-- Sidebar -->
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <a href="dashboard.php" class="brand-link">
            <i class="fas fa-microchip brand-image"></i>
            <span class="brand-text font-weight-light">DMAppsESP</span>
        </a>

        <div class="sidebar">
            <nav class="mt-2">
                <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu">
                    <li class="nav-item">
                        <a href="dashboard.php" class="nav-link">
                            <i class="nav-icon fas fa-tachometer-alt"></i>
                            <p>Dashboard</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="devices.php" class="nav-link">
                            <i class="nav-icon fas fa-microchip"></i>
                            <p>Cihazlar</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="#" class="nav-link active">
                            <i class="nav-icon fas fa-users"></i>
                            <p>Kullanıcılar</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="settings.php" class="nav-link">
                            <i class="nav-icon fas fa-cog"></i>
                            <p>Ayarlar</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="logout.php" class="nav-link">
                            <i class="nav-icon fas fa-sign-out-alt"></i>
                            <p>Çıkış</p>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </aside>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Kullanıcı Ekle</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Ana Sayfa</a></li>
                            <li class="breadcrumb-item active">Kullanıcı Ekle</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Yeni Kullanıcı Bilgileri</h3>
                        </div>
                        
                        <form role="form" method="post" action="add_user.php">
                            <div class="card-body">
                                <?php if (isset($error)): ?>
                                    <div class="alert alert-danger alert-dismissible">
                                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                        <strong>Hata!</strong> <?php echo $error; ?>
                                    </div>
                                <?php endif; ?>

                                <?php if (isset($success)): ?>
                                    <div class="alert alert-success alert-dismissible">
                                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                        <strong>Başarılı!</strong> <?php echo $success; ?>
                                    </div>
                                <?php endif; ?>

                                <div class="form-group">
                                    <label for="username">Kullanıcı Adı</label>
                                    <input type="text" name="username" class="form-control" id="username"
                                           placeholder="Kullanıcı adı" required>
                                </div>

                                <div class="form-group">
                                    <label for="email">E-posta</label>
                                    <input type="email" name="email" class="form-control" id="email"
                                           placeholder="E-posta adresi" required>
                                </div>

                                <div class="form-group">
                                    <label for="full_name">Ad Soyad</label>
                                    <input type="text" name="full_name" class="form-control" id="full_name"
                                           placeholder="Ad Soyad" required>
                                </div>

                                <div class="form-group">
                                    <label for="phone">Telefon</label>
                                    <input type="tel" name="phone" class="form-control" id="phone"
                                           placeholder="Telefon numarası">
                                </div>

                                <div class="form-group">
                                    <label for="password">Şifre</label>
                                    <input type="password" name="password" class="form-control" id="password"
                                           placeholder="Şifre" required minlength="6">
                                </div>

                                <div class="form-group">
                                    <label for="user_type">Kullanıcı Tipi</label>
                                    <select class="form-control" name="user_type" id="user_type">
                                        <option value="user" selected>Normal Kullanıcı</option>
                                        <option value="admin">Yönetici</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="card-footer">
                                <button type="reset" class="btn btn-dark"><i class="fa fa-times-circle"></i> Temizle</button>
                                <button type="submit" class="btn btn-primary"><i class="fa fa-check-circle"></i> Kullanıcı Ekle</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<!-- POS AdminLTE JS -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/dist/js/adminlte.min.js"></script>
<script src="assets/plugins/sweetalert2/sweetalert2.min.js"></script>

<script>
$(document).ready(function() {
    // Form validation
    $('form').on('submit', function(e) {
        var username = $('#username').val();
        var email = $('#email').val();
        var password = $('#password').val();
        var full_name = $('#full_name').val();
        
        if (!username || !email || !password || !full_name) {
            e.preventDefault();
            Swal.fire({
                icon: 'error',
                title: 'Hata',
                text: 'Tüm alanları doldurunuz!'
            });
        }
    });
});
</script>
</body>
</html>
