<?php
/**
 * Rig N Dig - Mobile API v1 / Register
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$name    = sanitize($_POST['name'] ?? '');
$company = sanitize($_POST['company'] ?? '');
$email   = trim($_POST['email'] ?? '');
$phone   = sanitize($_POST['phone'] ?? '');
$pass    = $_POST['password'] ?? '';

if (!$name || !$email || !$pass) {
    echo json_encode(['success' => false, 'message' => 'Name, email and password are required.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email address.']);
    exit;
}

if (strlen($pass) < 8) {
    echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters.']);
    exit;
}

// Check if email exists
$existing = Database::fetchOne("SELECT id FROM customers WHERE email = ?", [$email]);
if ($existing) {
    echo json_encode(['success' => false, 'message' => 'An account with this email already exists.']);
    exit;
}

// Create account
$hash = password_hash($pass, PASSWORD_BCRYPT);
try {
    $id = Database::insert(
        "INSERT INTO customers (company_name, contact_name, email, password, phone, status) VALUES (?,?,?,?,?,'active')",
        [$company ?: $name, $name, $email, $hash, $phone]
    );

    logActivity('customer', $id, 'API Registration', 'Account created via mobile app');

    echo json_encode([
        'success' => true,
        'message' => 'Account created successfully',
        'data' => [
            'id' => $id,
            'name' => $name,
            'email' => $email
        ]
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
