<?php
session_start();
include 'db_conn.php'; 

header('Content-Type: application/json'); // atgriež JSON

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (empty($email) || empty($password)) {
        echo json_encode(['success' => false, 'error' => 'Aizpildiet visus laukus!']);
        exit();
    }

    if (strlen($password) < 10) {
        echo json_encode(['success' => false, 'error' => 'Parolei jābūt vismaz 10 simbolus garai!']);
        exit();
    }
// Paroļu drošība
if (!preg_match('/[0-9]/', $password) || !preg_match('/[\W]/', $password)) {
    echo json_encode([
        'success' => false,
        'error' => 'Parolei jābūt vismaz vienam ciparam un vienam simbolam!'
    ]);
    exit();
}
if (!preg_match('/^[a-zA-Z0-9]/', $email)) {
    echo json_encode([
        'success' => false,
        'error' => 'E-pasts nedrīkst sākties ar simbolu!'
    ]);
    exit();
}
    $stmt = $conn->prepare("SELECT id, name, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['email'] = $email;
$_SESSION['name'] = $user['name'];
            echo json_encode(['success' => true]);
            exit();
        } else {
            echo json_encode(['success' => false, 'error' => 'Nepareiza parole!']);
            exit();
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Lietotājs nav atrasts!']);
        exit();
    }
}

$conn->close();
?>
