<?php
include 'config.php';

$message = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    $usernameInput = trim($_POST['username']);
    $email = trim($_POST['email']);
    $pass = $_POST['password'];
    $repass = $_POST['re_password'];

    if (empty($name) || empty($usernameInput) || empty($email) || empty($pass) || empty($repass)) {
        $message = "Please fill all fields.";
    } elseif (strlen($pass) < 8) {
        $message = "Password must contain at least 8 characters.";
    } elseif ($pass !== $repass) {
        $message = "Passwords do not match.";
    } else {
        $hashed = password_hash($pass, PASSWORD_DEFAULT);
        $date = date('Y-m-d');
        $time = date('H:i:s');

        $stmt = $conn->prepare("INSERT INTO user (name, username, email, password, created_date, created_time) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssss", $name, $usernameInput, $email, $hashed, $date, $time);

        if ($stmt->execute()) {
            header("Location: login.php?registered=1");
            exit();
        } else {
            $message = "Username or Email already exists.";
        }
    }
}
?>

<style>
        .login-logo-wrap{
            text-align:center;
            margin-bottom:12px;
        }
        .login-logo-wrap img{
            width:120px;
            height:120px;
            object-fit:contain;
            display:inline-block;
        }
        .auth-card p{
            text-align:center;
            margin-top:2px;
            font-size:0.92rem;
        }
        .auth-card p a{
            color:#1f7a3f;
            font-weight:750;
            text-decoration:none;
        }
        .auth-card p a:hover{
            text-decoration:underline;
        }
    </style>

<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Register</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body class="auth-body">
<div class="auth-card">
    <div class="login-logo-wrap">
        <img src="logo/logo_color1.png" alt="Krushi Sewa Piyasa Logo">
    </div>
    <h2>Krushi Sewa Piyasa - Create Account</h2>
    <?php if($message) echo "<div class='alert'>$message</div>"; ?>
    <form method="POST">
        <input type="text" name="name" placeholder="Name" required>
        <input type="text" name="username" placeholder="Username" required>
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="password" name="re_password" placeholder="Re-enter Password" required>
        <button type="submit">Register</button>
    </form>
    <p>Already have an account? <a href="login.php">Login</a></p>
</div>
</body>
</html>