<?php
// insertClient.php

session_start();
require_once('../config/dbConnection.php');

$db = DatabaseConnection::getInstance();
$conn = $db->getConnection();

function sanitize($value) {
    return trim(htmlspecialchars($value));
}

function generateUniqueClientID($conn) {
    do {
        $clientID = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT); // 6 digits with leading zeros
        $stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE ClientID = ?");
        $stmt->bind_param("s", $clientID);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();
    } while ($count > 0);

    return $clientID;
}

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

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

if (!isset($_SESSION['username'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$clientName  = sanitize($_POST['clientName'] ?? '');
$nrc         = sanitize($_POST['nrc'] ?? '');
$mobilePhone = sanitize($_POST['mobilePhone'] ?? '');
$email       = sanitize($_POST['email'] ?? '');

// Validate required fields
if (!$clientName || !$nrc || !$mobilePhone || !$email) {
    echo json_encode(['status' => 'error', 'message' => 'Please fill in all required fields']);
    exit;
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid email format']);
    exit;
}

// Validate mobile phone format (adjust regex to your expected format)
if (!preg_match('/^\+?\d{7,15}$/', $mobilePhone)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid mobile phone number']);
    exit;
}

// Check if NRC exists
$stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE NRC = ?");
$stmt->bind_param("s", $nrc);
$stmt->execute();
$stmt->bind_result($nrcCount);
$stmt->fetch();
$stmt->close();

if ($nrcCount > 0) {
    echo json_encode(['status' => 'error', 'message' => 'NRC already exists']);
    exit;
}

// Check if email exists
$stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($emailCount);
$stmt->fetch();
$stmt->close();

if ($emailCount > 0) {
    echo json_encode(['status' => 'error', 'message' => 'Email already exists']);
    exit;
}

// Check if mobile phone exists
$stmt = $conn->prepare("SELECT COUNT(*) FROM clients WHERE MobilePhone = ?");
$stmt->bind_param("s", $mobilePhone);
$stmt->execute();
$stmt->bind_result($phoneCount);
$stmt->fetch();
$stmt->close();

if ($phoneCount > 0) {
    echo json_encode(['status' => 'error', 'message' => 'Mobile phone number already exists']);
    exit;
}

// Generate unique ClientID
$clientID = generateUniqueClientID($conn);

// Insert client with ClientID
$stmt = $conn->prepare("INSERT INTO clients (ClientID, ClientName, NRC, MobilePhone, email) VALUES (?, ?, ?, ?, ?)");
if (!$stmt) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$stmt->bind_param("sssss", $clientID, $clientName, $nrc, $mobilePhone, $email);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Client saved successfully', 'ClientID' => $clientID]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to save client: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
