<?php
// register_fixed.php: Fixed registration endpoint for Ton Sui Mining
// This is a replacement for register.php

// Enable error logging
ini_set('display_errors', 0); // Don't display errors to browser
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/register_fixed_error.log');

// CORS and security // Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';
 
header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Include the proper database connection file
error_log("Including db.php for database connection");
require_once 'db.php';
error_log("Database connection included successfully");

// Helper function for responses
function respond($success, $message, $code = 200, $data = []) {
    http_response_code($code);
    echo json_encode([
        'success' => $success, 
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

// Get and parse input data
$data = [];
$raw_input = file_get_contents('php://input');
error_log("Raw input: $raw_input");

// First try to parse as JSON
$json_data = json_decode($raw_input, true);
if (json_last_error() === JSON_ERROR_NONE) {
    $data = $json_data;
    error_log("Successfully parsed JSON data");
} 
// If not JSON, check standard form POST data
else if (!empty($_POST)) {
    $data = $_POST;
    error_log("Using standard form POST data");
} 
// Log if no data found
else {
    error_log("Could not parse input data as JSON and no POST data found: " . json_last_error_msg());
}

// Extract and validate data
$name = isset($data['name']) ? trim($data['name']) : '';
$username = isset($data['username']) ? trim($data['username']) : '';
$email = isset($data['email']) ? trim($data['email']) : '';
$password = $data['password'] ?? '';
$confirm = $data['confirmPassword'] ?? $data['confirm_password'] ?? $data['confirm'] ?? '';
    
// Debug confirmation password
error_log("Received confirm password: " . (!empty($confirm) ? "YES" : "NO"));
error_log("Raw confirmPassword value: " . ($data['confirmPassword'] ?? 'not found'));


error_log("Processing registration for: $username / $email / $name");

// Validation
if (empty($name) || empty($username) || empty($email) || empty($password)) {
    error_log("Missing fields: name=$name, username=$username, email=$email, pass=" . 
        (empty($password) ? "empty" : "provided"));
    respond(false, 'All fields are required', 400);
}

// Make confirmation password optional
if (empty($confirm)) {
    $confirm = $password; // If not provided, use the password itself
    error_log("Confirmation password not provided, using password value instead");
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    error_log("Invalid email format: $email");
    respond(false, 'Invalid email format', 400);
}

if ($password !== $confirm) {
    error_log("Passwords do not match for user: $username");
    respond(false, 'Passwords do not match', 400);
}

if (strlen($password) < 6) {
    error_log("Password too short for user: $username");
    respond(false, 'Password must be at least 6 characters', 400);
}

try {
    // Check if user already exists
    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
    $stmt->execute([$username, $email]);
    if ($stmt->fetch()) {
        error_log("User already exists: $username / $email");
        respond(false, 'Username or email already exists', 409);
    }
    
    // Create new user
    $hash = password_hash($password, PASSWORD_DEFAULT);
    
    // Insert user into users table - match schema (no ref_code or activation_code columns)
    $stmt = $pdo->prepare(
        "INSERT INTO users (name, username, email, password) 
         VALUES (?, ?, ?, ?)"
    );
    $result = $stmt->execute([$name, $username, $email, $hash]);
    
    if ($result) {
        $user_id = $pdo->lastInsertId();
        error_log("User created successfully with ID: $user_id");
        respond(true, 'Registration successful', 200, ['user_id' => $user_id]);
    } else {
        error_log("Failed to insert user into database");
        respond(false, 'Registration failed', 500);
    }
} catch (PDOException $e) {
    error_log("Database error during registration: " . $e->getMessage());
    respond(false, 'Registration failed due to database error', 500);
} catch (Exception $e) {
    error_log("Unexpected error during registration: " . $e->getMessage());
    respond(false, 'Registration failed due to an unexpected error', 500);
}
