<?php
declare(strict_types=1);
session_start();
require_once 'db/config.php';

// If user is already logged in, redirect them to the main page.
if (isset($_SESSION['user_id'])) {
    header("Location: horses.php");
    exit;
}

$errors = [];
$messages = [];

// Handle POST requests
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {

    // Handle registration
    if ($_POST['action'] === 'signup') {
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        if (empty($username) || empty($email) || empty($password)) {
            $errors[] = 'Please fill in all fields for registration.';
        } else {
            try {
                $pdo = db();
                $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
                $stmt->execute([$username, $email]);
                if ($stmt->fetch()) {
                    $errors[] = 'Username or email already exists.';
                } else {
                    $stmt = $pdo->query("SELECT id FROM users LIMIT 1");
                    $role = ($stmt->fetch()) ? 'client' : 'administrator';

                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$username, $email, $hashedPassword, $role]);
                    $messages[] = 'Registration successful! Please log in.';
                }
            } catch (PDOException $e) {
                error_log("Signup Error: " . $e->getMessage());
                $errors[] = 'A database error occurred during registration.';
            }
        }
    }

    // Handle login
    if ($_POST['action'] === 'login') {
        $login = $_POST['login'] ?? '';
        $password = $_POST['password'] ?? '';

        if (empty($login) || empty($password)) {
            $errors[] = 'Please provide your login and password.';
        } else {
            try {
                $pdo = db();
                $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR username = ?");
                $stmt->execute([$login, $login]);
                $user = $stmt->fetch();

                if ($user && password_verify($password, $user['password'])) {
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['role'] = $user['role'];
                    $_SESSION['flash_message'] = 'Welcome back! You have successfully logged in.';
                    
                    session_write_close();
                    header("Location: horses.php");
                    exit;
                } else {
                    $errors[] = 'Invalid login credentials.';
                }
            } catch (PDOException $e) {
                error_log("Login Error: " . $e->getMessage());
                $errors[] = 'A database error occurred during login.';
            }
        }
    }
}

// The rest of the file is for display purposes only if no redirect has happened.
$now = date('Y-m-d H:i:s');
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Login / Sign Up</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400&display=swap" rel="stylesheet">
  <style>
    :root {
      --text-color: #ffffff;
      --input-border-color: rgba(255, 255, 255, 0.5);
      --button-bg-color: #ffffff;
      --button-text-color: #000000;
      --error-color: #ffcdd2;
      --success-color: #c8e6c9;
    }
    body {
      margin: 0;
      font-family: 'Lato', 'Hero Light', sans-serif;
      font-weight: 300;
      color: var(--text-color);
      display: flex;
      justify-content: flex-start; /* Align content to the left */
      align-items: flex-start;   /* Align content to the top */
      min-height: 100vh;
      background: #000000 url('assets/pasted-20250910-063752-96793b4f.jpg') no-repeat center center fixed;
      background-size: cover;
    }
    main {
      padding: 4rem; /* Add some padding from the corner */
      width: auto;
    }
    .card {
      background: transparent;
      border: none;
      padding: 0;
      width: 100%;
      max-width: 500px; /* Increased max-width for horizontal layout */
      text-align: left;
    }
    h1 {
      font-size: 2.2rem;
      font-weight: 300;
      margin: 0 0 2.5rem;
      letter-spacing: 1px;
    }
    form {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    .form-row {
        display: flex;
        gap: 1.5rem;
        align-items: flex-end;
    }
    .form-group {
      margin-bottom: 0;
      text-align: left;
      flex-grow: 1;
    }
    label {
      display: block;
      margin-bottom: 0.5rem;
      font-size: 0.9rem;
      color: rgba(255, 255, 255, 0.8);
    }
    input {
      width: 100%;
      padding: 0.8rem 0;
      background: transparent;
      border: none;
      border-bottom: 1px solid var(--input-border-color);
      color: var(--text-color);
      font-size: 1.1rem;
      box-sizing: border-box;
      font-family: 'Lato', sans-serif;
      font-weight: 300;
    }
    input:focus {
        outline: none;
        border-bottom-color: #ffffff;
    }
    input:-webkit-autofill,
    input:-webkit-autofill:hover, 
    input:-webkit-autofill:focus, 
    input:-webkit-autofill:active {
        -webkit-box-shadow: 0 0 0 30px #222 inset !important; /* Darker background for autofill */
        -webkit-text-fill-color: #fff !important;
    }
    input::placeholder {
      color: rgba(255, 255, 255, 0.5);
    }
    button {
      padding: 0.9rem 2rem;
      background: var(--button-bg-color);
      color: var(--button-text-color);
      border: none;
      border-radius: 25px;
      font-size: 1rem;
      font-weight: 400;
      text-transform: uppercase;
      letter-spacing: 1px;
      cursor: pointer;
      transition: background-color 0.2s ease, color 0.2s ease;
      align-self: flex-start; /* Align button to the start of the flex container */
      margin-top: 1rem;
    }
    button:hover {
        background-color: #f0f0f0;
    }
    .home-link {
        color: var(--text-color);
        text-decoration: none;
        position: absolute;
        top: 1.5rem;
        right: 1.5rem; /* Moved to the right */
        opacity: 0.8;
        font-size: 0.9rem;
    }
    .messages {
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 8px;
        text-align: left;
        position: fixed;
        bottom: 20px; /* Positioned at the bottom */
        left: 50%;
        transform: translateX(-50%);
        z-index: 100;
        min-width: 300px;
        font-size: 0.9rem;
        background: rgba(0,0,0,0.7);
    }
    .errors {
        color: var(--error-color);
        border: 1px solid #d32f2f;
    }
    .success {
        color: var(--success-color);
        border: 1px solid #388e3c;
    }
    .toggle-form {
        margin-top: 2rem;
        font-size: 0.9rem;
    }
    .toggle-form a {
        color: #fff;
        text-decoration: underline;
        cursor: pointer;
    }
    #signup-card {
        display: none;
    }
  </style>
</head>
<body>
  
  <main>
    <div class="card" id="login-card">
      <h1>Login</h1>
      <form action="login.php" method="post">
        <input type="hidden" name="action" value="login">
        <div class="form-row">
            <div class="form-group">
              <label for="login-field">Email or Username</label>
              <input type="text" id="login-field" name="login" required>
            </div>
            <div class="form-group">
              <label for="login-password">Password</label>
              <input type="password" id="login-password" name="password" required>
            </div>
        </div>
        <button type="submit">Login</button>
      </form>
      <p class="toggle-form">Don't have an account? <a onclick="toggleForms()">Sign up</a></p>
    </div>
    <div class="card" id="signup-card">
      <h1>Sign Up</h1>
      <form action="login.php" method="post">
        <input type="hidden" name="action" value="signup">
        <div class="form-row">
            <div class="form-group">
              <label for="signup-username">Username</label>
              <input type="text" id="signup-username" name="username" required>
            </div>
            <div class="form-group">
              <label for="signup-email">Email</label>
              <input type="email" id="signup-email" name="email" required>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
              <label for="signup-password">Password</label>
              <input type="password" id="signup-password" name="password" required>
            </div>
        </div>
        <button type="submit">Sign Up</button>
      </form>
      <p class="toggle-form">Already have an account? <a onclick="toggleForms()">Log in</a></p>
    </div>
  </main>
    <?php if (!empty($errors)): ?>
        <div class="messages errors">
            <?php foreach ($errors as $error): ?>
                <p style="margin: 0;"><?= htmlspecialchars($error) ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <?php if (!empty($messages)): ?>
        <div class="messages success">
            <?php foreach ($messages as $message): ?>
                <p style="margin: 0;"><?= htmlspecialchars($message) ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <script>
        function toggleForms() {
            const loginCard = document.getElementById('login-card');
            const signupCard = document.getElementById('signup-card');
            if (loginCard.style.display === 'none') {
                loginCard.style.display = 'block';
                signupCard.style.display = 'none';
            } else {
                loginCard.style.display = 'none';
                signupCard.style.display = 'block';
            }
        }
        
        // If there were registration errors, show the signup form
        <?php if (!empty($errors) && $_POST['action'] === 'signup'): ?>
        toggleForms();
        <?php endif; ?>
    </script>
</body>
</html>