<?php
// FINAL CORRECTED SCRIPT: register_user.php

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database connection failed.';
    echo json_encode($response);
    exit;
}

$required_fields = ['name', 'mobile', 'address', 'password'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
        http_response_code(400);
        $response['status'] = 'error';
        $response['message'] = "All fields are required.";
        echo json_encode($response);
        exit;
    }
}

$name = trim($_POST['name']);
$mobile = trim($_POST['mobile']);
$address = trim($_POST['address']);
$password = $_POST['password'];

// Hash the password for secure storage.
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

try {
    // Check if user already exists
    $sql_check = "SELECT id FROM users WHERE mobile = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param("s", $mobile);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        http_response_code(409); // Conflict
        $response['status'] = 'error';
        $response['message'] = 'A user with this mobile number already exists.';
    } else {
        // THE FIX: Insert into the correct 'password_hash' column
        $sql = "INSERT INTO users (name, mobile, address, password_hash) VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssss", $name, $mobile, $address, $hashed_password);

        if ($stmt->execute()) {
            $response['status'] = 'success';
            $response['message'] = 'Registration successful.';
        } else {
            throw new Exception('Failed to execute the insert statement.');
        }
        $stmt->close();
    }
    $stmt_check->close();

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: ' . $e->getMessage();
}

echo json_encode($response);
$conn->close();
exit;
?>