<?php
header('Content-Type: application/json');

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';
require_once __DIR__ . '/../../helpers/jwt_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, "Invalid request method.");
}

/* ---------------- READ MULTIPART DATA ---------------- */

$name  = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$role  = trim($_POST['role'] ?? '');

/* ---------------- VALIDATION ---------------- */

// Name & role required
if ($name === '' || $role === '') {
    sendResponse(422, "Name and role are required.");
}

// Either email OR phone required
if ($email === '' && $phone === '') {
    sendResponse(422, "Either email or phone number is required.");
}

// Email validation (if provided)
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(422, "Invalid email format.");
}

// Phone validation (if provided)
if ($phone !== '' && !preg_match('/^\+[1-9]\d{7,14}$/', $phone)) {
    sendResponse(422, "Invalid phone number format.");
}

/* ---------------- PROFILE IMAGE UPLOAD ---------------- */

$profileImageName = null;

if (!empty($_FILES['profile_image']['name'])) {

    $uploadDir = __DIR__ . '/../../uploads/profile/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
    $profileImageName = uniqid('profile_') . '.' . $extension;
    
    if (!move_uploaded_file(
        $_FILES['profile_image']['tmp_name'],
        $uploadDir . $profileImageName
    )) {
        sendResponse(500, "Failed to upload profile image.");
    }
}

/* ---------------- DATABASE ---------------- */

try {

    // Email uniqueness check (if provided)
    if ($email !== '') {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->rowCount() > 0) {
            sendResponse(409, "Email already registered.");
        }
    }

    // Phone uniqueness check (if provided)
    if ($phone !== '') {
        $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
        $stmt->execute([$phone]);
        if ($stmt->rowCount() > 0) {
            sendResponse(409, "Phone number already registered.");
        }
    }

    // Insert user (NO PASSWORD)
    $stmt = $conn->prepare("
        INSERT INTO users 
        (name, email, phone, role, profile, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");

    $stmt->execute([
        $name,
        $email !== '' ? $email : null,
        $phone !== '' ? $phone : null,
        $role,
        $profileImageName
    ]);

    $userId = $conn->lastInsertId();

    // Generate JWT
    $token = generateJWT([
        'user_id' => $userId,
        'role' => $role
    ]);

    sendResponse(201, "Registration successful.", [
        'user' => [
            'id' => $userId,
            'token' => $token,
            'name' => $name,
            'email' => $email !== '' ? $email : null,
            'phone' => $phone !== '' ? $phone : null,
            'role' => $role,
            'profile_image' => $profileImageName
                ? ($_ENV['BASE_URL'] ?? '') . '/uploads/profile/' . $profileImageName
                : null
        ]
    ]);

} catch (PDOException $e) {
    sendResponse(500, "Database error.");
}
