<?php
session_start();
header('Content-Type: application/json');
include_once('../../includes/config.php');

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customerName = trim($_POST['customerName']);
    $phone = trim($_POST['phone']);
    $contactPerson = isset($_POST['contactPerson']) ? trim($_POST['contactPerson']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $address = isset($_POST['address']) ? trim($_POST['address']) : '';
    $city = isset($_POST['city']) ? trim($_POST['city']) : '';
    $state = isset($_POST['state']) ? trim($_POST['state']) : '';
    $pinCode = isset($_POST['pinCode']) ? trim($_POST['pinCode']) : '';
    $gstNumber = isset($_POST['gstNumber']) ? trim($_POST['gstNumber']) : '';
    $panNumber = isset($_POST['panNumber']) ? trim($_POST['panNumber']) : '';
    $customerType = isset($_POST['customerType']) ? trim($_POST['customerType']) : 'Individual';
    $creditLimit = isset($_POST['creditLimit']) ? floatval($_POST['creditLimit']) : 0.00;
    $creditDays = isset($_POST['creditDays']) ? intval($_POST['creditDays']) : 0;
    $userId = $_SESSION['uid'];
    
    if (empty($customerName)) {
        $response['message'] = 'Customer name is required';
        echo json_encode($response);
        exit();
    }
    
    if (empty($phone)) {
        $response['message'] = 'Phone number is required';
        echo json_encode($response);
        exit();
    }
    
    try {
        // Generate customer code
        $codeQuery = "SELECT CustomerCode FROM tblcustomers ORDER BY ID DESC LIMIT 1";
        $codeResult = mysqli_query($con, $codeQuery);
        
        if (mysqli_num_rows($codeResult) > 0) {
            $lastCode = mysqli_fetch_assoc($codeResult)['CustomerCode'];
            $lastNumber = intval(substr($lastCode, 1));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        $customerCode = 'C' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
        
        // Generate CustomerID (CUST format)
        $customerIDQuery = "SELECT CustomerID FROM tblcustomers WHERE CustomerID != '' ORDER BY ID DESC LIMIT 1";
        $customerIDResult = mysqli_query($con, $customerIDQuery);
        
        if ($customerIDResult && mysqli_num_rows($customerIDResult) > 0) {
            $lastCustomerID = mysqli_fetch_assoc($customerIDResult)['CustomerID'];
            $numericPart = (int)substr($lastCustomerID, 4); // Remove 'CUST' prefix
            $nextNumericPart = $numericPart + 1;
            $customerID = 'CUST' . str_pad($nextNumericPart, 3, '0', STR_PAD_LEFT);
        } else {
            $customerID = 'CUST001';
        }
        
        // Insert customer
        $customerName = mysqli_real_escape_string($con, $customerName);
        $phone = mysqli_real_escape_string($con, $phone);
        $contactPerson = mysqli_real_escape_string($con, $contactPerson);
        $email = mysqli_real_escape_string($con, $email);
        $address = mysqli_real_escape_string($con, $address);
        $city = mysqli_real_escape_string($con, $city);
        $state = mysqli_real_escape_string($con, $state);
        $pinCode = mysqli_real_escape_string($con, $pinCode);
        $gstNumber = mysqli_real_escape_string($con, $gstNumber);
        $panNumber = mysqli_real_escape_string($con, $panNumber);
        $customerType = mysqli_real_escape_string($con, $customerType);
        
        $sql = "INSERT INTO tblcustomers 
                (CustomerID, CustomerCode, CustomerName, ContactPerson, Mobile, Email, 
                 Address, City, State, PinCode, GSTNumber, PANNumber, CustomerType, 
                 CreditLimit, CreditDays, CurrentBalance, IsActive, DateAdded) 
                VALUES 
                ('$customerID', '$customerCode', '$customerName', '$contactPerson', '$phone', '$email',
                 '$address', '$city', '$state', '$pinCode', '$gstNumber', '$panNumber', '$customerType',
                 $creditLimit, $creditDays, 0.00, 1, NOW())";
        
        if (mysqli_query($con, $sql)) {
            $customerId = mysqli_insert_id($con);
            
            $response['success'] = true;
            $response['message'] = 'Customer added successfully';
            $response['customer'] = [
                'id' => $customerId,
                'customerID' => $customerID,
                'code' => $customerCode,
                'name' => $customerName,
                'phone' => $phone,
                'balance' => 0.00,
                'gst' => $gstNumber
            ];
        } else {
            $response['message'] = 'Database error: ' . mysqli_error($con);
        }
        
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
} else {
    $response['message'] = 'Invalid request method';
}

echo json_encode($response);
?>
