<?php
session_start();
include 'db.php'; // Your database connection file

$errors = [];
$name = $mobile = $email = '';

if (isset($_POST['register'])) {

    // Sanitize inputs
    $name   = trim($_POST['full_name']);
    $mobile = trim($_POST['mobile']);
    $email  = trim($_POST['email']);
    $password = $_POST['password'];
    $cpass    = $_POST['cpassword'];

    // ---- VALIDATIONS ---- //

    // 1️⃣ Empty fields
    if (empty($name)) $errors[] = "Full Name is required.";
    if (empty($mobile)) $errors[] = "Mobile number is required.";
    if (empty($email)) $errors[] = "Email is required.";
    if (empty($password)) $errors[] = "Password is required.";
    if (empty($cpass)) $errors[] = "Confirm Password is required.";

    // 2️⃣ Email format
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // 3️⃣ Mobile validation (digits only, 10–15 characters)
    if (!empty($mobile) && !preg_match('/^[0-9]{10,15}$/', $mobile)) {
        $errors[] = "Invalid mobile number. Only digits allowed (10-15).";
    }

    // 4️⃣ Password length
    if (!empty($password) && strlen($password) < 6) {
        $errors[] = "Password must be at least 6 characters.";
    }

    // 5️⃣ Password match
    if (!empty($password) && !empty($cpass) && $password !== $cpass) {
        $errors[] = "Passwords do not match.";
    }

    // 6️⃣ Check if email already exists
    if (!empty($email)) {
        $check = $conn->prepare("SELECT id FROM register WHERE email = ?");
        $check->bind_param("s", $email);
        $check->execute();
        $check->store_result();
        if ($check->num_rows > 0) {
            $errors[] = "Email is already registered.";
        }
    }

    // ---- INSERT INTO DATABASE IF NO ERRORS ---- //
    if (empty($errors)) {
        //$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
         $hashedPassword = $password;
        $status = 1; // Active by default

        $stmt = $conn->prepare(
            "INSERT INTO register (full_name, mobile, email, password, status) 
             VALUES (?, ?, ?, ?, ?)"
        );
        $stmt->bind_param("ssssi", $name, $mobile, $email, $hashedPassword, $status);

        if ($stmt->execute()) {
            $_SESSION['success'] = "Registration successful!";
            header("Location: login.php");
            exit;
        } else {
            $errors[] = "Registration failed. Please try again.";
        }
    }

    // Store errors in session to display back in the form
    $_SESSION['errors'] = $errors;
    $_SESSION['old'] = [
        'full_name' => $name,
        'mobile' => $mobile,
        'email' => $email
    ];
    header("Location: register.php");
    exit;
}
?>
