<?php
// login.php

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

if(isset($_SESSION['user_id'])){
    header("Location: index.php");
    exit;
}

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

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

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

   // Έλεγχος αν το token στο POST ταιριάζει με αυτό του session
    if(!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']){
        die("Invalid CSRF token");
    }

    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    // Έλεγχος συμπλήρωσης και ότι το username έχει έγκυρους χαρακτήρες
    if($username && $password){
        if(!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)){
            $login_error = "Μη έγκυρο username";
        } else {
        $stmt = $pdo->prepare("SELECT id, username, password, dimos_id FROM dim_ypalilos WHERE username=:username");
            $stmt->execute([':username'=>$username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if($user && password_verify($password, $user['password'])){
                // Numeric user_id για session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['dimos_id'] = (int)$user['dimos_id'];

                // Centroid του δήμου του χρήστη
                $stmt2 = $pdo->prepare("
                    SELECT 
                        ST_Y(centroid) AS lat,
                        ST_X(centroid) AS lng
                    FROM dimos
                    WHERE id = :dimos_id
                ");
                $stmt2->execute([':dimos_id' => $_SESSION['dimos_id']]);
                $dimos = $stmt2->fetch(PDO::FETCH_ASSOC);

                if ($dimos && $dimos['lat'] && $dimos['lng']) {
                    $_SESSION['centroid_lat'] = (float)$dimos['lat'];
                    $_SESSION['centroid_lng'] = (float)$dimos['lng'];
                } else {
                    // Fallback
                    $_SESSION['centroid_lat'] = 39.611;
                    $_SESSION['centroid_lng'] = 21.694;
                }

                header("Location: index.php");
                exit;
            } else {
                $login_error = "Λάθος username ή password";
            }
        }
    } else {
        $login_error = "Συμπληρώστε username και password";
    }
}
?>

<!DOCTYPE html>
<html lang="el">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Σύνδεση - Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

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

.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);
}

.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;
}

.page-footer {
    position: fixed;
    bottom: 10px;
    right: 15px;
    font-size: 13px;
    color: #555;
    text-align: right;
    z-index: 1000;
}

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

.page-footer a:hover {
    color: #1e88e5;
}
</style>

</head>
<body>

<div class="auth-wrapper">
<div class="auth-card">

<h3 class="text-center">Σύνδεση</h3>
<hr>

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

<!-- Προσθηκη htmlspecialchars -->
<?php if($login_error): ?>
    <div class="error-message"><?=htmlspecialchars($login_error)?></div>
<?php endif; ?>

<!-- Έλεγχος CSRF Token -->
<input type="hidden" name="csrf_token" value="<?=htmlspecialchars($_SESSION['csrf_token'])?>">

<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control"
    value="<?=htmlspecialchars($username ?? '')?>">
</div>

<div class="password-wrapper" 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)" 
          style="position:absolute; right:10px; cursor:pointer; display:flex; align-items:center; justify-content:center; width:30px; height:30px; overflow:visible;">
        <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-.588M5.21 3.088A7 7 0 0 1 8 2.5c5 0 8 5.5 8 5.5s-.939 1.721-2.641 3.238l-2.062-2.062a3.5 3.5 0 0 0-4.474-4.474z"/>
              <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>

<button name="login" class="btn btn-primary btn-block">Σύνδεση</button>
<p class="text-center" style="margin-top:10px">
Νέος χρήστης; <a href="register.php">Εγγραφή εδώ</a>
</p>
</form>
</div>
</div>

<footer class="page-footer">
  <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>

<script>
function togglePassword(id, elem){
    var 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-.588M5.21 3.088A7 7 0 0 1 8 2.5c5 0 8 5.5 8 5.5s-.939 1.721-2.641 3.238l-2.062-2.062a3.5 3.5 0 0 0-4.474-4.474z"/>
            <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>
        `;
    }
}

</script>

<!-- Sienna Accessibility -->
<script src="https://cdn.jsdelivr.net/npm/sienna-accessibility@latest/dist/sienna-accessibility.umd.js" defer></script>

<!-- Cookies για τις ρυθμίσεις προσβασιμότητας -->
<script>
(function() {
  const cookieName = "siennaSettings";

  function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
  }

  function setCookie(name, value, days = 30) {
    const d = new Date();
    d.setTime(d.getTime() + (days*24*60*60*1000));
    const expires = "expires=" + d.toUTCString();
    document.cookie = `${name}=${value};${expires};path=/`;
  }

  function applySettings() {
    const saved = getCookie(cookieName);
    if (!saved) return;
    try {
      const settings = JSON.parse(saved);
      if (window.SiennaAccessibility) {
        for (let key in settings) {
          window.SiennaAccessibility.setSetting(key, settings[key]);
        }
      } else {
        setTimeout(applySettings, 500);
      }
    } catch(e){ console.error("Sienna cookie error:", e); }
  }

  document.addEventListener("DOMContentLoaded", () => {
    applySettings();
    document.addEventListener("SiennaSettingsChanged", e => {
      setCookie(cookieName, JSON.stringify(e.detail));
    });
  });
})();

  document.addEventListener("DOMContentLoaded", () => {
    if (window.SiennaAccessibility) {
      window.SiennaAccessibility.init({
        position: 'bottom-right' 
      });
    }
  });

</script>
</body>
</html>
