<?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') {
    $supplierName = trim($_POST['supplierName']);
    $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']) : '';
    $supplierType = isset($_POST['supplierType']) ? trim($_POST['supplierType']) : 'Individual';
    $creditLimit = isset($_POST['creditLimit']) ? floatval($_POST['creditLimit']) : 0.00;
    $creditDays = isset($_POST['creditDays']) ? intval($_POST['creditDays']) : 0;
    $userId = $_SESSION['uid'];
    
    if (empty($supplierName)) {
        $response['message'] = 'Supplier name is required';
        echo json_encode($response);
        exit();
    }
    
    if (empty($phone)) {
        $response['message'] = 'Phone number is required';
        echo json_encode($response);
        exit();
    }
    
    try {
        // Generate supplier code
        $codeQuery = "SELECT SupplierCode FROM tblsuppliers ORDER BY ID DESC LIMIT 1";
        $codeResult = mysqli_query($con, $codeQuery);
        
        if (mysqli_num_rows($codeResult) > 0) {
            $lastCode = mysqli_fetch_assoc($codeResult)['SupplierCode'];
            $lastNumber = intval(substr($lastCode, 1));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        $supplierCode = 'S' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
        
        // Insert supplier
        $supplierName = mysqli_real_escape_string($con, $supplierName);
        $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);
        $gstNumber = mysqli_real_escape_string($con, $gstNumber);
        $panNumber = mysqli_real_escape_string($con, $panNumber);
        
        $sql = "INSERT INTO tblsuppliers 
                (SupplierCode, SupplierName, ContactPerson, PhoneNumber, Email, 
                 Address, GSTNumber, PanNumber, Status, CreatedAt) 
                VALUES 
                ('$supplierCode', '$supplierName', '$contactPerson', '$phone', '$email',
                 '$address', '$gstNumber', '$panNumber', 'Active', NOW())";
        
        if (mysqli_query($con, $sql)) {
            $supplierId = mysqli_insert_id($con);
            
            $response['success'] = true;
            $response['message'] = 'Supplier added successfully';
            $response['supplier'] = [
                'id' => $supplierId,
                'code' => $supplierCode,
                'name' => $supplierName,
                '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);
?>
