<?php
/**
 * controllers/newClientSubmit.php
 *
 * Handle new client creation from modal form.
 */

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include dependencies
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/validation.php';
require_once __DIR__ . '/../lib/csrf.php';

// Check authentication
if (!isLoggedIn()) {
    http_response_code(403);
    die(json_encode(['success' => false, 'message' => 'Authentication required']));
}

// Check CSRF token
if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    die(json_encode(['success' => false, 'message' => 'CSRF token validation failed']));
}

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['NCsubmit'])) {
    http_response_code(405);
    die(json_encode(['success' => false, 'message' => 'Method not allowed']));
}

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

try {
    // Validate and sanitize input data
    $input = validateNewClientData($_POST);

    // Check if client with this email already exists for this user
    if (clientEmailExists($input['email'], $_SESSION['user_id'])) {
        throw new ValidationException('A client with this email address already exists');
    }

    // Insert new client
    $clientId = insertNewClient($input);

    // Return success response with client data for dropdown update
    echo json_encode([
        'success' => true,
        'message' => 'Client added successfully',
        'client' => [
            'id' => $clientId,
            'name' => $input['name'],
            'company' => $input['company'],
            'email' => $input['email'],
            'address' => $input['address'] . ', ' . $input['state']
        ]
    ]);

} catch (ValidationException $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
} catch (PDOException $e) {
    error_log("Database error in new client creation: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error occurred. Please try again later.']);
} catch (Exception $e) {
    error_log("Unexpected error in new client creation: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An unexpected error occurred. Please try again later.']);
}

/**
 * Validate and sanitize new client form data
 */
function validateNewClientData(array $post): array
{
    $validated = [];

    // Required fields
    $validated['name'] = sanitizeString($post['Nname'] ?? '', 100);
    if (empty($validated['name'])) {
        throw new ValidationException('Client name is required');
    }

    $validated['email'] = filter_var($post['Nemail'] ?? '', FILTER_VALIDATE_EMAIL);
    if (!$validated['email']) {
        throw new ValidationException('Valid email address is required');
    }

    $validated['address'] = sanitizeString($post['Naddress'] ?? '', 255);
    if (empty($validated['address'])) {
        throw new ValidationException('Address is required');
    }

    $validated['state'] = sanitizeString($post['Nstate'] ?? '', 255);
    if (empty($validated['state'])) {
        throw new ValidationException('Town/State/Postcode is required');
    }

    // Optional fields
    $validated['company'] = sanitizeString($post['Ncompany'] ?? '', 100);
    $validated['mobile'] = sanitizeString($post['Nmobile'] ?? '', 20);

    return $validated;
}

/**
 * Check if client email already exists for this user
 */
function clientEmailExists(string $email, int $userId): bool
{
    global $pdo;

    $stmt = $pdo->prepare("SELECT id FROM client_records WHERE email = ? AND modx_user_id = ?");
    $stmt->execute([$email, $userId]);

    return $stmt->fetch() !== false;
}

/**
 * Insert new client into database
 */
function insertNewClient(array $data): int
{
    global $pdo;

    $sql = "INSERT INTO client_records (
        modx_user_id,
        modx_user_attributes,
        client,
        company,
        email,
        address,
        mobile,
        created_at
    ) VALUES (
        :modx_user_id,
        :modx_user_attributes,
        :client,
        :company,
        :email,
        :address,
        :mobile,
        NOW()
    )";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        'modx_user_id' => $_SESSION['user_id'],
        'modx_user_attributes' => $_SESSION['user_id'],
        'client' => $data['name'],
        'company' => $data['company'],
        'email' => $data['email'],
        'address' => $data['address'] . ', ' . $data['state'],
        'mobile' => $data['mobile']
    ]);

    return $pdo->lastInsertId();
}
?>