MMCT TEAM
Server IP : 217.21.85.138  /  Your IP : 216.73.216.103
Web Server : LiteSpeed
System : Linux in-mum-web906.main-hosting.eu 4.18.0-553.37.1.lve.el8.x86_64 #1 SMP Mon Feb 10 22:45:17 UTC 2025 x86_64
User : u915722082 ( 915722082)
PHP Version : 7.4.33
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : OFF
Directory (0755) :  /home/u915722082/.nvm/../public_html/invoice/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u915722082/.nvm/../public_html/invoice/ajax_customer.php
<?php
// Prevent PHP from displaying errors directly in response
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Enable proper JSON responses
header('Content-Type: application/json');

require_once "db.php";

// Check database connection
if ($con->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Function to validate required fields
function validateRequiredFields($data) {
    $required = ['cname', 'phone', 'gst'];
    $missing = [];
    
    foreach ($required as $field) {
        if (empty($data[$field])) {
            $missing[] = $field;
        }
    }
    
    if (!empty($missing)) {
        throw new Exception("Required fields missing: " . implode(', ', $missing));
    }
    
    // Validate email if provided
    if (!empty($data['cemail']) && !filter_var($data['cemail'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception("Invalid email format");
    }
    
    // Validate phone (10 digits, starting with 6-9 for Indian format)
    if (!preg_match('/^[6-9]\d{9}$/', $data['phone'])) {
        throw new Exception("Please enter a valid 10-digit phone number");
    }
}

// Escape and sanitize input
function escape($con, $value) {
    return mysqli_real_escape_string($con, trim($value));
}

// Process shipping addresses
function processAddresses($addressesData) {
    $addresses = [];
    
    if (is_string($addressesData)) {
        $decoded = json_decode($addressesData, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
            $addresses = $decoded;
        }
    } else if (is_array($addressesData)) {
        $addresses = $addressesData;
    }
    
    return $addresses;
}

// Start transaction
$con->begin_transaction();

try {
    // Get and validate customer data
    $name = escape($con, $_POST['cname']);
    $email = escape($con, $_POST['cemail']);
    $phone = escape($con, $_POST['phone']);
    $gst = escape($con, $_POST['gst']);
    $hasShippingAddress = isset($_POST['has_shipping_address']) && $_POST['has_shipping_address'] == '1' ? 1 : 0;
    
    $billingAddress = escape($con, $_POST['billing_address']);
    $billingCity = escape($con, $_POST['billing_city']);
    $billingPincode = escape($con, $_POST['billing_pincode']);
    $billingState = escape($con, $_POST['billing_state']);
    $custype = escape($con, $_POST['custype']);

    validateRequiredFields($_POST);

    // Check if the Name already exists
    $checkQuery = "SELECT id FROM customers WHERE name = '$name'";
    $result = $con->query($checkQuery);
    if ($result->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => 'This Name is already registered.']);
        exit;
    }
    $result->free();

    // Insert customer record
    $insertCustomer = "INSERT INTO customers 
        (name, email, phone, gst_number, has_shipping_address, billing_address, billing_city, billing_pincode, billing_state, custype) 
        VALUES 
        ('$name', '$email', '$phone', '$gst', '$hasShippingAddress', '$billingAddress', '$billingCity', '$billingPincode', '$billingState', '$custype')";

    if (!$con->query($insertCustomer)) {
        throw new Exception("Error inserting customer: " . $con->error);
    }

    $customerId = $con->insert_id;

    // Process shipping addresses
    if ($hasShippingAddress && isset($_POST['addresses'])) {
        $addresses = processAddresses($_POST['addresses']);
        foreach ($addresses as $address) {
            $addrValue = escape($con, $address['address']);
            $cityValue = escape($con, $address['city']);
            $pincodeValue = escape($con, $address['pincode'] ?? $address['addr_pincode'] ?? '');
            $stateValue = escape($con, $address['state'] ?? $address['addr_state'] ?? '');
            $isBilling = isset($address['is_billing']) ? intval($address['is_billing']) : 0;

            if (empty($addrValue) && empty($cityValue) && empty($pincodeValue) && empty($stateValue)) {
                continue;
            }

            // Insert shipping address
            $insertAddress = "INSERT INTO customer_addresses 
                (customer_id, address, city, pincode, state, is_billing) 
                VALUES 
                ('$customerId', '$addrValue', '$cityValue', '$pincodeValue', '$stateValue', '$isBilling')";

            if (!$con->query($insertAddress)) {
                throw new Exception("Error inserting address: " . $con->error);
            }
        }
    }

    // Commit transaction
    $con->commit();

    echo json_encode(['status' => 'success', 'message' => 'Customer added successfully', 'customer_id' => $customerId]);

} catch (Exception $e) {
    $con->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>

MMCT - 2023