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

// Handle registration
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $full_name = $_POST['full_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $user_type = $_POST['user_type'] ?? 'user';
    
    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($confirm_password)) {
        $error = 'Tüm alanlar zorunludur.';
    } elseif ($password !== $confirm_password) {
        $error = 'Şifreler eşleşmiyor.';
    } elseif (strlen($password) < 6) {
        $error = 'Şifre en az 6 karakter olmalıdır.';
    } 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 = 'Kayıt başarıyla oluşturuldu! Giriş yapabilirsiniz.';
                // Redirect to login after 2 seconds
                header('Refresh: 2; url=login.php');
                exit();
            } else {
                $error = 'Kayıt sırasında bir hata oluştu. Lütfen tekrar deneyin.';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kayıt Ol - 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">
    
    <style>
        .register-page {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .register-box {
            width: 400px;
            margin: 7% auto;
        }
        .register-logo {
            font-size: 2.1rem;
            font-weight: 300;
            margin-bottom: 1rem;
        }
        .register-card-body {
            padding: 20px;
        }
        .form-control {
            border-radius: 5px;
            border: 1px solid #ddd;
            padding: 12px;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 114, 234, 0.25);
        }
        .btn-primary {
            background: #667eea;
            border: none;
            border-radius: 5px;
            padding: 12px;
            font-weight: 500;
        }
        .btn-primary:hover {
            background: #5a67d8;
        }
        .alert {
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .text-center {
            text-align: center;
        }
        .mt-3 {
            margin-top: 1rem;
        }
    </style>
</head>
<body class="register-page">
    <div class="register-box">
        <div class="register-logo">
            <b>DMAppsESP</b><br>
            <small>IoT Device Manager</small>
        </div>

        <div class="card">
            <div class="card-body register-card-body">
                <p class="login-box-msg">Hesabınızı oluşturun</p>

                <?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; ?>

                <form action="register.php" method="post">
                    <div class="form-group">
                        <label for="username">Kullanıcı Adı</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="username" id="username" 
                                   placeholder="Kullanıcı adı" required 
                                   value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-user"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email">E-posta</label>
                        <div class="input-group">
                            <input type="email" class="form-control" name="email" id="email" 
                                   placeholder="E-posta adresi" required 
                                   value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-envelope"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="full_name">Ad Soyad</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="full_name" id="full_name" 
                                   placeholder="Adınız soyadınız" 
                                   value="<?php echo isset($_POST['full_name']) ? htmlspecialchars($_POST['full_name']) : ''; ?>">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-user"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="phone">Telefon</label>
                        <div class="input-group">
                            <input type="tel" class="form-control" name="phone" id="phone" 
                                   placeholder="Telefon numaranız" 
                                   value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-phone"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password">Şifre</label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="password" id="password" 
                                   placeholder="Şifre (en az 6 karakter)" required minlength="6">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-lock"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="confirm_password">Şifre Tekrarı</label>
                        <div class="input-group">
                            <input type="password" class="form-control" name="confirm_password" id="confirm_password" 
                                   placeholder="Şifrenizi tekrar girin" required minlength="6">
                            <div class="input-group-append">
                                <div class="input-group-text">
                                    <span class="fas fa-lock"></span>
                                </div>
                            </div>
                        </div>
                    </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 class="row">
                        <div class="col-8">
                            <button type="submit" class="btn btn-primary btn-block">Kayıt Ol</button>
                        </div>
                        <div class="col-4">
                            <button type="button" class="btn btn-outline-secondary btn-block" onclick="window.location.href='login.php'">İptal</button>
                        </div>
                    </div>
                </form>

                <p class="mt-3 mb-1">
                    <a href="login.php" class="text-center">Zaten hesabınız var mı? Giriş yapın</a>
                </p>
            </div>
            <!-- /.register-card-body -->
        </div>
    </div>
    <!-- /.register-box -->

    <!-- 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>
        // Auto-focus on username field
        $(document).ready(function() {
            $('#username').focus();
        });
    </script>
</body>
</html>
