<?php
session_start();
include_once('../../includes/config.php');

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

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

if (!isset($_POST['action']) || $_POST['action'] !== 'quick_add') {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit();
}

$masterType = $_POST['masterType'];
$status = mysqli_real_escape_string($con, $_POST['status']);

$success = false;
$message = '';
$data = [];

switch($masterType) {
    case 'unit':
        $unitName = mysqli_real_escape_string($con, $_POST['unitName']);
        $unitSymbol = mysqli_real_escape_string($con, $_POST['unitSymbol']);
        $description = mysqli_real_escape_string($con, $_POST['description']);
        
        // Check if exists
        $checkQuery = "SELECT ID FROM tblunits WHERE UnitName = '$unitName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $message = "Unit name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblunits (UnitName, UnitSymbol, Description, Status) 
                           VALUES ('$unitName', '$unitSymbol', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $id = mysqli_insert_id($con);
                $success = true;
                $message = "Unit added successfully!";
                $data = [
                    'ID' => $id,
                    'UnitName' => $unitName,
                    'UnitSymbol' => $unitSymbol,
                    'Description' => $description,
                    'Status' => $status
                ];
            } else {
                $message = "Error adding unit: " . mysqli_error($con);
            }
        }
        break;

    case 'category':
        $categoryName = mysqli_real_escape_string($con, $_POST['categoryName']);
        $categoryCode = mysqli_real_escape_string($con, $_POST['categoryCode']);
        $description = mysqli_real_escape_string($con, $_POST['description']);
        
        $checkQuery = "SELECT ID FROM tblcategories WHERE CategoryName = '$categoryName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $message = "Category name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblcategories (CategoryName, CategoryCode, Description, Status) 
                           VALUES ('$categoryName', '$categoryCode', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $id = mysqli_insert_id($con);
                $success = true;
                $message = "Category added successfully!";
                $data = [
                    'ID' => $id,
                    'CategoryName' => $categoryName,
                    'CategoryCode' => $categoryCode,
                    'Description' => $description,
                    'Status' => $status
                ];
            } else {
                $message = "Error adding category: " . mysqli_error($con);
            }
        }
        break;

    case 'brand':
        $brandName = mysqli_real_escape_string($con, $_POST['brandName']);
        $brandCode = mysqli_real_escape_string($con, $_POST['brandCode']);
        $manufacturer = mysqli_real_escape_string($con, $_POST['manufacturer']);
        $contactInfo = mysqli_real_escape_string($con, $_POST['contactInfo']);
        
        $checkQuery = "SELECT ID FROM tblbrands WHERE BrandName = '$brandName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $message = "Brand name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblbrands (BrandName, BrandCode, Manufacturer, ContactInfo, Status) 
                           VALUES ('$brandName', '$brandCode', '$manufacturer', '$contactInfo', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $id = mysqli_insert_id($con);
                $success = true;
                $message = "Brand added successfully!";
                $data = [
                    'ID' => $id,
                    'BrandName' => $brandName,
                    'BrandCode' => $brandCode,
                    'Manufacturer' => $manufacturer,
                    'ContactInfo' => $contactInfo,
                    'Status' => $status
                ];
            } else {
                $message = "Error adding brand: " . mysqli_error($con);
            }
        }
        break;

    case 'supplier':
        $supplierName = mysqli_real_escape_string($con, $_POST['supplierName']);
        $contactPerson = mysqli_real_escape_string($con, $_POST['contactPerson']);
        $phone = mysqli_real_escape_string($con, $_POST['phone']);
        
        $checkQuery = "SELECT ID FROM tblsuppliers WHERE SupplierName = '$supplierName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $message = "Supplier name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblsuppliers (SupplierName, ContactPerson, Phone, Status) 
                           VALUES ('$supplierName', '$contactPerson', '$phone', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $id = mysqli_insert_id($con);
                $success = true;
                $message = "Supplier added successfully!";
                $data = [
                    'ID' => $id,
                    'SupplierName' => $supplierName,
                    'ContactPerson' => $contactPerson,
                    'Phone' => $phone,
                    'Status' => $status
                ];
            } else {
                $message = "Error adding supplier: " . mysqli_error($con);
            }
        }
        break;

    case 'tax':
        $taxName = mysqli_real_escape_string($con, $_POST['taxName']);
        $taxType = mysqli_real_escape_string($con, $_POST['taxType']);
        $taxRate = (float)$_POST['taxRate'];
        $description = mysqli_real_escape_string($con, $_POST['description']);
        
        $insertQuery = "INSERT INTO tbltaxtypes (TaxName, TaxType, TaxRate, Description, Status) 
                       VALUES ('$taxName', '$taxType', $taxRate, '$description', '$status')";
        
        if (mysqli_query($con, $insertQuery)) {
            $id = mysqli_insert_id($con);
            $success = true;
            $message = "Tax type added successfully!";
            $data = [
                'ID' => $id,
                'TaxName' => $taxName,
                'TaxType' => $taxType,
                'TaxRate' => $taxRate,
                'Description' => $description,
                'Status' => $status
            ];
        } else {
            $message = "Error adding tax type: " . mysqli_error($con);
        }
        break;

    case 'location':
        $locationName = mysqli_real_escape_string($con, $_POST['locationName']);
        $locationCode = mysqli_real_escape_string($con, $_POST['locationCode']);
        $locationType = mysqli_real_escape_string($con, $_POST['locationType']);
        $address = mysqli_real_escape_string($con, $_POST['address']);
        
        $checkQuery = "SELECT ID FROM tbllocations WHERE LocationName = '$locationName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $message = "Location name already exists!";
        } else {
            $insertQuery = "INSERT INTO tbllocations (LocationName, LocationCode, LocationType, Address, Status) 
                           VALUES ('$locationName', '$locationCode', '$locationType', '$address', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $id = mysqli_insert_id($con);
                $success = true;
                $message = "Location added successfully!";
                $data = [
                    'ID' => $id,
                    'LocationName' => $locationName,
                    'LocationCode' => $locationCode,
                    'LocationType' => $locationType,
                    'Address' => $address,
                    'Status' => $status
                ];
            } else {
                $message = "Error adding location: " . mysqli_error($con);
            }
        }
        break;

    case 'rack':
        $rackName = mysqli_real_escape_string($con, $_POST['rackName']);
        $rackCode = mysqli_real_escape_string($con, $_POST['rackCode']);
        $locationID = !empty($_POST['locationID']) ? (int)$_POST['locationID'] : null;
        $capacity = !empty($_POST['capacity']) ? (float)$_POST['capacity'] : null;
        
        $insertQuery = "INSERT INTO tblracks (RackName, RackCode, LocationID, Capacity, Status) 
                       VALUES ('$rackName', '$rackCode', " . ($locationID ? $locationID : 'NULL') . ", " . ($capacity ? $capacity : 'NULL') . ", '$status')";
        
        if (mysqli_query($con, $insertQuery)) {
            $id = mysqli_insert_id($con);
            $success = true;
            $message = "Rack added successfully!";
            $data = [
                'ID' => $id,
                'RackName' => $rackName,
                'RackCode' => $rackCode,
                'LocationID' => $locationID,
                'Capacity' => $capacity,
                'Status' => $status
            ];
        } else {
            $message = "Error adding rack: " . mysqli_error($con);
        }
        break;

    default:
        $message = "Invalid master type";
}

echo json_encode([
    'success' => $success,
    'message' => $message,
    'data' => $data
]);
?>
