<?php
session_start();
require_once __DIR__ . '/db.php';

// Δημιουργία CSRF token, αν δεν υπάρχει ήδη
if(empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$register_errors = [];
$dimos_list = $pdo->query("SELECT id,onoma FROM dimos ORDER BY onoma")->fetchAll(PDO::FETCH_ASSOC);

if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register'])){

    // Έλεγχος αν το token στο POST ταιριάζει με αυτό του session
    if(!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('Invalid CSRF token');
    }
    
    $first = trim($_POST['first_name'] ?? '');
    $last = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirm = trim($_POST['confirm_password'] ?? '');
    $terms = isset($_POST['terms']);
    $dimos_id = $_POST['dimos_id'] ?? '';

    if(!$first) $register_errors[] = "Συμπληρώστε το όνομα";
    if(!$last) $register_errors[] = "Συμπληρώστε το επώνυμο";

    // Έλεγχος email (εγκυρότητα)
    if(!$email) {
        $register_errors[] = "Συμπληρώστε το email";
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $register_errors[] = "Μη έγκυρο email";
    }

    // Έλεγχος username (αποδεκτοί χαρακτήρες μόνο γράμματα, αριθμοί και _)
    if(!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
        $register_errors[] = "Το username πρέπει να έχει 3-20 χαρακτήρες και να περιλαμβάνει μόνο γράμματα, αριθμούς ή _";
    }

    // Έλεγχος password
    if(!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/', $password)) {
        $register_errors[] = "Το password πρέπει να περιλαμβάνει τουλάχιστον 8 χαρακτήρες, κεφαλαία, πεζά, αριθμό και σύμβολο";
    }

    if($password !== $confirm) $register_errors[] = "Τα passwords δεν ταιριάζουν";
    if(!$terms) $register_errors[] = "Πρέπει να αποδεχθείτε τους όρους";

    // Έλεγχος dimos_id (είναι αριθμός και υπάρχει στη βάση)
    if(!$dimos_id) $register_errors[] = "Επιλέξτε δήμο";

    if(empty($register_errors)){
        $hash = password_hash($password, PASSWORD_DEFAULT);

        // Έλεγχος αν υπάρχει ήδη email ή username
        $stmtCheck = $pdo->prepare("SELECT username, email FROM dim_ypalilos WHERE username = :username OR email = :email");
        $stmtCheck->execute([
            ':username' => $username,
            ':email' => $email
        ]);
        $existing = $stmtCheck->fetch(PDO::FETCH_ASSOC);

        if($existing){
            if($existing['username'] === $username){
                $register_errors[] = "Το username υπάρχει ήδη";
            }
            if($existing['email'] === $email){
                $register_errors[] = "Το email υπάρχει ήδη";
            }
        } else {
            // Αν δεν υπάρχει τίποτα - insert
            try{
                $stmt = $pdo->prepare("
                    INSERT INTO dim_ypalilos (first_name, last_name, email, username, password, dimos_id)
                    VALUES (:first, :last, :email, :username, :password, :dimos)
                ");
                $stmt->execute([
                    ':first' => $first,
                    ':last' => $last,
                    ':email' => $email,
                    ':username' => $username,
                    ':password' => $hash,
                    ':dimos' => $dimos_id
                ]);

                header("Location: login.php?registered=1");
                exit;
            }catch(PDOException $e){
                // Fallback για άλλα σφάλματα
                $register_errors[] = "Σφάλμα κατά την εγγραφή, δοκιμάστε ξανά.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="el">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Εγγραφή - Register</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<style>
body, html {
    margin: 0;
    padding: 0;
    height: 100%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #e3f2fd, #ffffff);
}

.auth-wrapper {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px; 
}

.auth-card {
    width: 100%;
    max-width: 400px;
    background: #ffffff;
    padding: 30px 25px;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.12);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.auth-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.15);
}

h3, h4 {
    color: #333;
    font-weight: 600;
}

.error-message {
    background: #ffebee;
    color: #c62828;
    padding: 8px 12px;
    border-radius: 6px;
    margin-bottom: 15px;
    font-size: 14px;
}

.form-group label {
    font-weight: 500;
    color: #555;
}

.form-control {
    border-radius: 8px;
    border: 1px solid #ced4da;
    padding: 10px 12px;
    font-size: 15px;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-control:focus {
    border-color: #42a5f5;
    box-shadow: 0 0 5px rgba(66,165,245,0.3);
}

select.form-control {
    padding: 0px 12px;   
    font-size: 15px;      
    line-height: 1.2;      

    border-radius: 8px;
    border: 1px solid #ced4da;
    background-color: #fff;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}


.password-wrapper {
    position: relative;
}

.password-wrapper .toggle-password {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    color: #777;
    transition: color 0.2s ease;
}

.password-wrapper .toggle-password:hover {
    color: #42a5f5;
}

button.btn-primary {
    background: #42a5f5;
    border: none;
    border-radius: 8px;
    padding: 10px 0;
    font-weight: 600;
    transition: background 0.3s ease, transform 0.2s ease;
}

button.btn-primary:hover {
    background: #1e88e5;
    transform: translateY(-2px);
}

p.text-center a {
    color: #42a5f5;
    text-decoration: none;
    font-weight: 500;
    transition: color 0.3s ease;
}

p.text-center a:hover {
    color: #1e88e5;
    text-decoration: underline;
}

footer {
    font-size: 13px;
    padding: 15px;
    color: #555;
    text-align: right;
}

footer a {
    text-decoration: underline;
    color: #42a5f5;
}

footer a:hover {
    color: #1e88e5;
}

</style>

</head>
<body>

<div class="auth-wrapper">
  <div class="auth-card">
    <h3 class="text-center">Εγγραφή</h3>
    <hr>

    <!-- Προσθηκη htmlspecialchars -->
    <?php foreach($register_errors as $e): ?>
        <div class="error-message"><?=htmlspecialchars($e)?></div>
    <?php endforeach; ?>

    <form id="registerForm" method="post">

        <!-- Προσθηκη hidden input με το CSRF token μέσα στο <form> -->
        <input type="hidden" name="csrf_token" value="<?=htmlspecialchars($_SESSION['csrf_token'])?>">

        <input class="form-control" name="first_name" placeholder="Όνομα" value="<?=htmlspecialchars($first ?? '')?>"><br>
        <input class="form-control" name="last_name" placeholder="Επώνυμο" value="<?=htmlspecialchars($last ?? '')?>"><br>
        <input class="form-control" name="email" placeholder="Email" value="<?=htmlspecialchars($email ?? '')?>"><br>
        <input class="form-control" name="username" placeholder="Username" value="<?=htmlspecialchars($username ?? '')?>"><br>

      <!-- Password -->
      <div class="password-wrapper" style="display:flex; flex-direction:column; position:relative;">
        <small style="color:#aaa; font-size:12px; display:block; margin-bottom:5px;">
            (Να περιλαμβάνει τουλάχιστον 8 χαρακτήρες, κεφαλαία, πεζά, αριθμό και σύμβολο)
        </small> 
        <div style="position:relative; display:flex; align-items:center;">
            
          <input type="password" class="form-control" name="password" id="regPassword" placeholder="Password" style="flex:1;">
          <span class="toggle-password" onclick="togglePassword('regPassword', this)">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye-slash-fill" viewBox="0 0 16 16">
              <path d="m10.79 12.912-1.614-1.615a3.5 3.5 0 0 1-4.474-4.474l-2.06-2.06C.938 6.278 0 8 0 8s3 5.5 8 5.5a7 7 0 0 0 2.79-.588"/>
              <path d="M5.525 7.646a2.5 2.5 0 0 0 2.829 2.829zm4.95.708-2.829-2.83a2.5 2.5 0 0 1 2.829 2.829zm3.171 6-12-12 .708-.708 12 12z"/>
            </svg>
          </span>
        </div>
        <div class="progress" style="height:8px; margin-top:1px;">
          <div id="passwordStrengthBar" class="progress-bar" role="progressbar" style="width:0%; background-color:#d9534f;"></div>
        </div>
        <div id="passwordError" class="error-message" style="display:none; margin-top:5px;"></div>
      </div>

      <!-- Confirm Password -->
      <div class="password-wrapper" style="position:relative; display:flex; align-items:center; margin-top:10px;">
        <input type="password" class="form-control" name="confirm_password" id="regConfirm" placeholder="Confirm Password" style="flex:1;">
        <span class="toggle-password" onclick="togglePassword('regConfirm', this)">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye-slash-fill" viewBox="0 0 16 16">
            <path d="m10.79 12.912-1.614-1.615a3.5 3.5 0 0 1-4.474-4.474l-2.06-2.06C.938 6.278 0 8 0 8s3 5.5 8 5.5a7 7 0 0 0 2.79-.588"/>
            <path d="M5.525 7.646a2.5 2.5 0 0 0 2.829 2.829zm4.95.708-2.829-2.83a2.5 2.5 0 0 1 2.829 2.829zm3.171 6-12-12 .708-.708 12 12z"/>
          </svg>
        </span>
      </div>

      <br>

      <!-- Δήμος -->
      <select name="dimos_id" class="form-control">
        <option value="">Επιλέξτε δήμο</option>
        <?php foreach($dimos_list as $d): ?>
          <option value="<?=$d['id']?>"><?=$d['onoma']?></option>
        <?php endforeach; ?>
      </select><br>

      <label><input type="checkbox" name="terms"> Αποδέχομαι τους όρους</label><br><br>

      <button name="register" class="btn btn-success btn-block">Δημιουργία</button><br>
      <p class="text-center"><a href="login.php">Επιστροφή στο Login</a></p>
    </form>
  </div>
</div>

<footer style="text-align:right; font-size:13px; padding:15px;">
  <strong>Δημόσιοι Φορείς</strong><br>
  <a href="https://www.gov.gr/" target="_blank">gov.gr</a> |
  <a href="https://data.gov.gr/" target="_blank">data.gov.gr</a> |
  <a href="https://sdigmap.tee.gov.gr/erga/" target="_blank">Εθνικό Μητρώο Υποδομών</a><br>
  WCAG 2.1 AA – <a href="https://www.w3.org/WAI/WCAG21/quickref/" target="_blank">Πληροφορίες</a>
</footer>

<!-- Scripts -->
<script>
function togglePassword(id, elem){
    const x = document.getElementById(id);
    elem.innerHTML = '';
    if(x.type === "password"){
        x.type = "text";
        elem.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye-fill" viewBox="0 0 16 16">
        <path d="M10.5 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0"/>
        <path d="M0 8s3-5.5 8-5.5S16 8 16 8s-3 5.5-8 5.5S0 8 0 8m8 3.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7"/>
        </svg>`;
    } else {
        x.type = "password";
        elem.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eye-slash-fill" viewBox="0 0 16 16">
        <path d="m10.79 12.912-1.614-1.615a3.5 3.5 0 0 1-4.474-4.474l-2.06-2.06C.938 6.278 0 8 0 8s3 5.5 8 5.5a7 7 0 0 0 2.79-.588"/>
        <path d="M5.525 7.646a2.5 2.5 0 0 0 2.829 2.829zm4.95.708-2.829-2.83a2.5 2.5 0 0 1 2.829 2.829zm3.171 6-12-12 .708-.708 12 12z"/>
        </svg>`;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const registerForm = document.getElementById('registerForm');
    const passwordInput = document.getElementById('regPassword');
    const confirmInput = document.getElementById('regConfirm');
    const strengthBar = document.getElementById('passwordStrengthBar');
    const passwordError = document.getElementById('passwordError');

    function updateStrength() {
        const val = passwordInput.value;
        let score = 0;
        if(val.length >= 8) score++;
        if(/[a-z]/.test(val)) score++;
        if(/[A-Z]/.test(val)) score++;
        if(/\d/.test(val)) score++;
        if(/[\W_]/.test(val)) score++;

        let width = 0, color = '#d9534f';
        if(score<=2){ width=33; color='#d9534f'; }
        else if(score<=4){ width=66; color='#f0ad4e'; }
        else { width=100; color='#5cb85c'; }

        strengthBar.style.width = width + '%';
        strengthBar.style.backgroundColor = color;
    }

    function validatePassword() {
        const val = passwordInput.value;
        const confirmVal = confirmInput.value;
        const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/;

        if(!pattern.test(val)){
            passwordError.style.display = 'block';
            passwordError.textContent = "Το password πρέπει να περιλαμβάνει τουλάχιστον 8 χαρακτήρες,  κεφαλαία, πεζά, αριθμό και σύμβολο ";
            return false;
        } else if(confirmVal && val !== confirmVal){
            passwordError.style.display = 'block';
            passwordError.textContent = "Τα passwords δεν ταιριάζουν!";
            return false;
        } else {
            passwordError.style.display = 'none';
            return true;
        }
    }

    passwordInput.addEventListener('input', () => {
        updateStrength();
        validatePassword();
    });
    confirmInput.addEventListener('input', validatePassword);

    registerForm.addEventListener('submit', (e) => {
        updateStrength();
        if(!validatePassword()){
            e.preventDefault();
            passwordInput.focus();
        }
    });
});
</script>

</body>
</html>


