<?php
session_start();
include_once('../includes/config.php');
include_once('../includes/quick-menu.php');
if (!isset($_SESSION['uid'])) {
    header('location:../logout.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'];
    $masterType = $_POST['masterType'];
    $activeTab = isset($_POST['activeTab']) ? $_POST['activeTab'] : 'units';
    
    if ($masterType == 'unit') {
        handleUnitOperations($con, $action);
    } elseif ($masterType == 'category') {
        handleCategoryOperations($con, $action);
    } elseif ($masterType == 'brand') {
        handleBrandOperations($con, $action);
    } elseif ($masterType == 'supplier') {
        handleSupplierOperations($con, $action);
    } elseif ($masterType == 'tax') {
        handleTaxOperations($con, $action);
    } elseif ($masterType == 'location') {
        handleLocationOperations($con, $action);
    } elseif ($masterType == 'rack') {
        handleRackOperations($con, $action);
    } elseif ($masterType == 'type') {
        handleTypeOperations($con, $action);
    }
    
    // Redirect back to the same tab after processing
    if (isset($success) || isset($error)) {
        header("Location: masters-management.php#tab-" . $activeTab);
        exit();
    }
}

// Handle delete operations
if (isset($_GET['delete']) && isset($_GET['type'])) {
    $id = (int)$_GET['delete'];
    $type = $_GET['type'];
    $activeTab = isset($_GET['tab']) ? $_GET['tab'] : getTabFromType($type);
    
    handleDeleteOperation($con, $type, $id);
    
    // Redirect back to the same tab after delete
    if (isset($success) || isset($error)) {
        header("Location: masters-management.php#tab-" . $activeTab);
        exit();
    }
}

// Function to handle unit operations
function handleUnitOperations($con, $action) {
    global $success, $error;
    
    $unitName = mysqli_real_escape_string($con, $_POST['unitName']);
    $unitSymbol = mysqli_real_escape_string($con, $_POST['unitSymbol']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tblunits WHERE UnitName = '$unitName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Unit name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblunits (UnitName, UnitSymbol, Description, Status) 
                           VALUES ('$unitName', '$unitSymbol', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Unit added successfully!";
            } else {
                $error = "Error adding unit: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tblunits SET 
                       UnitName = '$unitName',
                       UnitSymbol = '$unitSymbol',
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Unit updated successfully!";
        } else {
            $error = "Error updating unit: " . mysqli_error($con);
        }
    }
}

// Function to handle category operations
function handleCategoryOperations($con, $action) {
    global $success, $error;
    
    $categoryName = mysqli_real_escape_string($con, $_POST['categoryName']);
    $categoryCode = mysqli_real_escape_string($con, $_POST['categoryCode']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tblcategories WHERE CategoryName = '$categoryName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Category name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblcategories (CategoryName, CategoryCode, Description, Status) 
                           VALUES ('$categoryName', '$categoryCode', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Category added successfully!";
            } else {
                $error = "Error adding category: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tblcategories SET 
                       CategoryName = '$categoryName',
                       CategoryCode = '$categoryCode',
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Category updated successfully!";
        } else {
            $error = "Error updating category: " . mysqli_error($con);
        }
    }
}

// Function to handle brand operations
function handleBrandOperations($con, $action) {
    global $success, $error;
    
    $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']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tblbrands WHERE BrandName = '$brandName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Brand name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblbrands (BrandName, BrandCode, Manufacturer, ContactInfo, Description, Status) 
                           VALUES ('$brandName', '$brandCode', '$manufacturer', '$contactInfo', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Brand added successfully!";
            } else {
                $error = "Error adding brand: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tblbrands SET 
                       BrandName = '$brandName',
                       BrandCode = '$brandCode',
                       Manufacturer = '$manufacturer',
                       ContactInfo = '$contactInfo',
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Brand updated successfully!";
        } else {
            $error = "Error updating brand: " . mysqli_error($con);
        }
    }
}

// Function to handle supplier operations
function handleSupplierOperations($con, $action) {
    global $success, $error;
    
    $supplierName = mysqli_real_escape_string($con, $_POST['supplierName']);
    $supplierCode = mysqli_real_escape_string($con, $_POST['supplierCode']);
    $contactPerson = mysqli_real_escape_string($con, $_POST['contactPerson']);
    $phoneNumber = mysqli_real_escape_string($con, $_POST['phoneNumber']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $gstNumber = mysqli_real_escape_string($con, $_POST['gstNumber']);
    $panNumber = mysqli_real_escape_string($con, $_POST['panNumber']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tblsuppliers WHERE SupplierName = '$supplierName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Supplier name already exists!";
        } else {
            $insertQuery = "INSERT INTO tblsuppliers (SupplierName, SupplierCode, ContactPerson, PhoneNumber, Email, Address, GSTNumber, PanNumber, Status) 
                           VALUES ('$supplierName', '$supplierCode', '$contactPerson', '$phoneNumber', '$email', '$address', '$gstNumber', '$panNumber', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Supplier added successfully!";
            } else {
                $error = "Error adding supplier: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tblsuppliers SET 
                       SupplierName = '$supplierName',
                       SupplierCode = '$supplierCode',
                       ContactPerson = '$contactPerson',
                       PhoneNumber = '$phoneNumber',
                       Email = '$email',
                       Address = '$address',
                       GSTNumber = '$gstNumber',
                       PanNumber = '$panNumber',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Supplier updated successfully!";
        } else {
            $error = "Error updating supplier: " . mysqli_error($con);
        }
    }
}

// Function to handle tax operations
function handleTaxOperations($con, $action) {
    global $success, $error;
    
    $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']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $insertQuery = "INSERT INTO tbltaxtypes (TaxName, TaxType, TaxRate, Description, Status) 
                       VALUES ('$taxName', '$taxType', $taxRate, '$description', '$status')";
        
        if (mysqli_query($con, $insertQuery)) {
            $success = "Tax type added successfully!";
        } else {
            $error = "Error adding tax type: " . mysqli_error($con);
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tbltaxtypes SET 
                       TaxName = '$taxName',
                       TaxType = '$taxType',
                       TaxRate = $taxRate,
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Tax type updated successfully!";
        } else {
            $error = "Error updating tax type: " . mysqli_error($con);
        }
    }
}

// Function to handle location operations
function handleLocationOperations($con, $action) {
    global $success, $error;
    
    $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']);
    $contactPerson = mysqli_real_escape_string($con, $_POST['contactPerson']);
    $phoneNumber = mysqli_real_escape_string($con, $_POST['phoneNumber']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tbllocations WHERE LocationName = '$locationName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Location name already exists!";
        } else {
            $insertQuery = "INSERT INTO tbllocations (LocationName, LocationCode, LocationType, Address, ContactPerson, PhoneNumber, Status) 
                           VALUES ('$locationName', '$locationCode', '$locationType', '$address', '$contactPerson', '$phoneNumber', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Location added successfully!";
            } else {
                $error = "Error adding location: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tbllocations SET 
                       LocationName = '$locationName',
                       LocationCode = '$locationCode',
                       LocationType = '$locationType',
                       Address = '$address',
                       ContactPerson = '$contactPerson',
                       PhoneNumber = '$phoneNumber',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Location updated successfully!";
        } else {
            $error = "Error updating location: " . mysqli_error($con);
        }
    }
}

// Function to handle rack operations
function handleRackOperations($con, $action) {
    global $success, $error;
    
    $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;
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $insertQuery = "INSERT INTO tblracks (RackName, RackCode, LocationID, Capacity, Description, Status) 
                       VALUES ('$rackName', '$rackCode', " . ($locationID ? $locationID : 'NULL') . ", " . ($capacity ? $capacity : 'NULL') . ", '$description', '$status')";
        
        if (mysqli_query($con, $insertQuery)) {
            $success = "Rack added successfully!";
        } else {
            $error = "Error adding rack: " . mysqli_error($con);
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tblracks SET 
                       RackName = '$rackName',
                       RackCode = '$rackCode',
                       LocationID = " . ($locationID ? $locationID : 'NULL') . ",
                       Capacity = " . ($capacity ? $capacity : 'NULL') . ",
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Rack updated successfully!";
        } else {
            $error = "Error updating rack: " . mysqli_error($con);
        }
    }
}

// Function to handle type operations
function handleTypeOperations($con, $action) {
    global $success, $error;
    
    $typeName = mysqli_real_escape_string($con, $_POST['typeName']);
    $typeCode = mysqli_real_escape_string($con, $_POST['typeCode']);
    $typeCategory = mysqli_real_escape_string($con, $_POST['typeCategory']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        $checkQuery = "SELECT ID FROM tbltypes WHERE TypeName = '$typeName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Type name already exists!";
        } else {
            $insertQuery = "INSERT INTO tbltypes (TypeName, TypeCode, TypeCategory, Description, Status) 
                           VALUES ('$typeName', '$typeCode', '$typeCategory', '$description', '$status')";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Type added successfully!";
            } else {
                $error = "Error adding type: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        $updateQuery = "UPDATE tbltypes SET 
                       TypeName = '$typeName',
                       TypeCode = '$typeCode',
                       TypeCategory = '$typeCategory',
                       Description = '$description',
                       Status = '$status',
                       LastUpdated = NOW()
                       WHERE ID = $id";
        
        if (mysqli_query($con, $updateQuery)) {
            $success = "Type updated successfully!";
        } else {
            $error = "Error updating type: " . mysqli_error($con);
        }
    }
}

// Function to handle delete operations
function handleDeleteOperation($con, $type, $id) {
    global $success, $error;
    
    $tables = [
        'unit' => 'tblunits',
        'category' => 'tblcategories',
        'brand' => 'tblbrands',
        'supplier' => 'tblsuppliers',
        'tax' => 'tbltaxtypes',
        'location' => 'tbllocations',
        'rack' => 'tblracks',
        'type' => 'tbltypes'
    ];
    
    if (isset($tables[$type])) {
        $deleteQuery = "DELETE FROM {$tables[$type]} WHERE ID = $id";
        
        if (mysqli_query($con, $deleteQuery)) {
            $success = ucfirst($type) . " deleted successfully!";
        } else {
            $error = "Error deleting " . $type . ": " . mysqli_error($con);
        }
    }
}

// Fetch all data for display
$units = fetchData($con, 'tblunits', 'UnitName');
$categories = fetchData($con, 'tblcategories', 'CategoryName');
$brands = fetchData($con, 'tblbrands', 'BrandName');
$suppliers = fetchData($con, 'tblsuppliers', 'SupplierName');
$taxes = fetchData($con, 'tbltaxtypes', 'TaxName');
$locations = fetchData($con, 'tbllocations', 'LocationName');
$racks = fetchRacksWithLocation($con);
$types = fetchData($con, 'tbltypes', 'TypeName');

function fetchData($con, $table, $orderBy) {
    $query = "SELECT * FROM $table ORDER BY $orderBy";
    $result = mysqli_query($con, $query);
    $data = [];
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    return $data;
}

function fetchRacksWithLocation($con) {
    $query = "SELECT r.*, l.LocationName FROM tblracks r 
              LEFT JOIN tbllocations l ON r.LocationID = l.ID 
              ORDER BY r.RackName";
    $result = mysqli_query($con, $query);
    $data = [];
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    return $data;
}

function getTabFromType($type) {
    $typeToTab = [
        'unit' => 'units',
        'category' => 'categories', 
        'brand' => 'brands',
        'supplier' => 'suppliers',
        'tax' => 'taxes',
        'location' => 'locations',
        'rack' => 'racks',
        'type' => 'types'
    ];
    return isset($typeToTab[$type]) ? $typeToTab[$type] : 'units';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>UZRS Inventory | Masters Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/modern-messagebox.css" rel="stylesheet">
    <link href="css/masters.css" rel="stylesheet">
    <?php renderQuickMenuCSS(); ?>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('../includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('../includes/topbar.php');?>
                
                <div class="container-fluid">
                    
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <?php renderQuickMenu("Masters Management", "Manage all master data"); ?>

                    <!-- Tab Navigation -->
                    <div class="master-tabs">
                        <div class="tab-nav">
                            <button class="tab-btn active" data-tab="units">
                                <i class="fas fa-balance-scale"></i> Units
                            </button>
                            <button class="tab-btn" data-tab="categories">
                                <i class="fas fa-tags"></i> Categories
                            </button>
                            <button class="tab-btn" data-tab="brands">
                                <i class="fas fa-certificate"></i> Brands
                            </button>
                            <button class="tab-btn" data-tab="suppliers">
                                <i class="fas fa-truck"></i> Suppliers
                            </button>
                            <button class="tab-btn" data-tab="taxes">
                                <i class="fas fa-percent"></i> Taxes
                            </button>
                            <button class="tab-btn" data-tab="locations">
                                <i class="fas fa-map-marker-alt"></i> Locations
                            </button>
                            <button class="tab-btn" data-tab="racks">
                                <i class="fas fa-warehouse"></i> Racks
                            </button>
                            <button class="tab-btn" data-tab="types">
                                <i class="fas fa-layer-group"></i> Types
                            </button>
                        </div>

                        <!-- Units Tab -->
                        <div class="tab-content active" id="units">
                            <div class="tab-header">
                                <h5><i class="fas fa-balance-scale text-primary"></i> Units Management</h5>
                                <button class="btn btn-primary btn-sm" onclick="openModal('unit')">
                                    <i class="fas fa-plus"></i> Add Unit
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($units as $unit): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($unit['UnitName']); ?></h6>
                                            <small><?php echo htmlspecialchars($unit['UnitSymbol']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($unit['Status']); ?>">
                                            <?php echo $unit['Status']; ?>
                                        </span>
                                    </div>
                                    <?php if (!empty($unit['Description'])): ?>
                                    <div class="master-card-body">
                                        <p><?php echo htmlspecialchars($unit['Description']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('unit', <?php echo $unit['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('unit', <?php echo $unit['ID']; ?>, '<?php echo htmlspecialchars($unit['UnitName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Categories Tab -->
                        <div class="tab-content" id="categories">
                            <div class="tab-header">
                                <h5><i class="fas fa-tags text-info"></i> Categories Management</h5>
                                <button class="btn btn-info btn-sm" onclick="openModal('category')">
                                    <i class="fas fa-plus"></i> Add Category
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($categories as $category): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($category['CategoryName']); ?></h6>
                                            <small><?php echo htmlspecialchars($category['CategoryCode']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($category['Status']); ?>">
                                            <?php echo $category['Status']; ?>
                                        </span>
                                    </div>
                                    <?php if (!empty($category['Description'])): ?>
                                    <div class="master-card-body">
                                        <p><?php echo htmlspecialchars($category['Description']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('category', <?php echo $category['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('category', <?php echo $category['ID']; ?>, '<?php echo htmlspecialchars($category['CategoryName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Brands Tab -->
                        <div class="tab-content" id="brands">
                            <div class="tab-header">
                                <h5><i class="fas fa-certificate text-warning"></i> Brands Management</h5>
                                <button class="btn btn-warning btn-sm" onclick="openModal('brand')">
                                    <i class="fas fa-plus"></i> Add Brand
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($brands as $brand): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($brand['BrandName']); ?></h6>
                                            <small><?php echo htmlspecialchars($brand['BrandCode']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($brand['Status']); ?>">
                                            <?php echo $brand['Status']; ?>
                                        </span>
                                    </div>
                                    <div class="master-card-body">
                                        <?php if (!empty($brand['Manufacturer'])): ?>
                                        <p><strong>Mfg:</strong> <?php echo htmlspecialchars($brand['Manufacturer']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($brand['Description'])): ?>
                                        <p><?php echo htmlspecialchars($brand['Description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('brand', <?php echo $brand['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('brand', <?php echo $brand['ID']; ?>, '<?php echo htmlspecialchars($brand['BrandName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Suppliers Tab -->
                        <div class="tab-content" id="suppliers">
                            <div class="tab-header">
                                <h5><i class="fas fa-truck text-success"></i> Suppliers Management</h5>
                                <button class="btn btn-success btn-sm" onclick="openModal('supplier')">
                                    <i class="fas fa-plus"></i> Add Supplier
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($suppliers as $supplier): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($supplier['SupplierName']); ?></h6>
                                            <small><?php echo htmlspecialchars($supplier['SupplierCode']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($supplier['Status']); ?>">
                                            <?php echo $supplier['Status']; ?>
                                        </span>
                                    </div>
                                    <div class="master-card-body">
                                        <?php if (!empty($supplier['ContactPerson'])): ?>
                                        <p><i class="fas fa-user"></i> <?php echo htmlspecialchars($supplier['ContactPerson']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($supplier['PhoneNumber'])): ?>
                                        <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($supplier['PhoneNumber']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($supplier['Email'])): ?>
                                        <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($supplier['Email']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('supplier', <?php echo $supplier['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('supplier', <?php echo $supplier['ID']; ?>, '<?php echo htmlspecialchars($supplier['SupplierName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Taxes Tab -->
                        <div class="tab-content" id="taxes">
                            <div class="tab-header">
                                <h5><i class="fas fa-percent text-danger"></i> Tax Types Management</h5>
                                <button class="btn btn-danger btn-sm" onclick="openModal('tax')">
                                    <i class="fas fa-plus"></i> Add Tax Type
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($taxes as $tax): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($tax['TaxName']); ?></h6>
                                            <small><?php echo htmlspecialchars($tax['TaxType']); ?> - <?php echo $tax['TaxRate']; ?>%</small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($tax['Status']); ?>">
                                            <?php echo $tax['Status']; ?>
                                        </span>
                                    </div>
                                    <?php if (!empty($tax['Description'])): ?>
                                    <div class="master-card-body">
                                        <p><?php echo htmlspecialchars($tax['Description']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('tax', <?php echo $tax['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('tax', <?php echo $tax['ID']; ?>, '<?php echo htmlspecialchars($tax['TaxName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Locations Tab -->
                        <div class="tab-content" id="locations">
                            <div class="tab-header">
                                <h5><i class="fas fa-map-marker-alt text-secondary"></i> Locations Management</h5>
                                <button class="btn btn-secondary btn-sm" onclick="openModal('location')">
                                    <i class="fas fa-plus"></i> Add Location
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($locations as $location): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($location['LocationName']); ?></h6>
                                            <small><?php echo htmlspecialchars($location['LocationCode']); ?> - <?php echo htmlspecialchars($location['LocationType']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($location['Status']); ?>">
                                            <?php echo $location['Status']; ?>
                                        </span>
                                    </div>
                                    <div class="master-card-body">
                                        <?php if (!empty($location['ContactPerson'])): ?>
                                        <p><i class="fas fa-user"></i> <?php echo htmlspecialchars($location['ContactPerson']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($location['PhoneNumber'])): ?>
                                        <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($location['PhoneNumber']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($location['Address'])): ?>
                                        <p><i class="fas fa-map-marker"></i> <?php echo htmlspecialchars($location['Address']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('location', <?php echo $location['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('location', <?php echo $location['ID']; ?>, '<?php echo htmlspecialchars($location['LocationName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Racks Tab -->
                        <div class="tab-content" id="racks">
                            <div class="tab-header">
                                <h5><i class="fas fa-warehouse text-dark"></i> Racks Management</h5>
                                <button class="btn btn-dark btn-sm" onclick="openModal('rack')">
                                    <i class="fas fa-plus"></i> Add Rack
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($racks as $rack): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($rack['RackName']); ?></h6>
                                            <small><?php echo htmlspecialchars($rack['RackCode']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($rack['Status']); ?>">
                                            <?php echo $rack['Status']; ?>
                                        </span>
                                    </div>
                                    <div class="master-card-body">
                                        <?php if (!empty($rack['LocationName'])): ?>
                                        <p><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($rack['LocationName']); ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($rack['Capacity'])): ?>
                                        <p><i class="fas fa-weight"></i> Capacity: <?php echo $rack['Capacity']; ?></p>
                                        <?php endif; ?>
                                        <?php if (!empty($rack['Description'])): ?>
                                        <p><?php echo htmlspecialchars($rack['Description']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('rack', <?php echo $rack['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('rack', <?php echo $rack['ID']; ?>, '<?php echo htmlspecialchars($rack['RackName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Types Tab -->
                        <div class="tab-content" id="types">
                            <div class="tab-header">
                                <h5><i class="fas fa-layer-group" style="color: #6610f2;"></i> Types Management</h5>
                                <button class="btn btn-sm" style="background: #6610f2; color: white;" onclick="openModal('type')">
                                    <i class="fas fa-plus"></i> Add Type
                                </button>
                            </div>
                            <div class="master-grid">
                                <?php foreach($types as $type): ?>
                                <div class="master-card">
                                    <div class="master-card-header">
                                        <div class="master-info">
                                            <h6><?php echo htmlspecialchars($type['TypeName']); ?></h6>
                                            <small><?php echo htmlspecialchars($type['TypeCode']); ?> - <?php echo htmlspecialchars($type['TypeCategory']); ?></small>
                                        </div>
                                        <span class="status-badge <?php echo strtolower($type['Status']); ?>">
                                            <?php echo $type['Status']; ?>
                                        </span>
                                    </div>
                                    <?php if (!empty($type['Description'])): ?>
                                    <div class="master-card-body">
                                        <p><?php echo htmlspecialchars($type['Description']); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    <div class="master-actions">
                                        <button class="btn-edit" onclick="editItem('type', <?php echo $type['ID']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-delete" onclick="deleteItem('type', <?php echo $type['ID']; ?>, '<?php echo htmlspecialchars($type['TypeName']); ?>')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
            <?php include_once('../includes/footer.php');?>
        </div>
    </div>

    <!-- Master Modal -->
    <div class="modal fade" id="masterModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add Item</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form method="POST" id="masterForm">
                    <div class="modal-body" id="modalBody">
                        <!-- Dynamic form content -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>
    <script src="../js/modern-messagebox.js"></script>
    <script src="../js/messagebox-wrapper.js"></script>
    <script src="js/masters.js"></script>
    <?php renderQuickMenuScript(); ?>

    <script>
        $(document).ready(function() {
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            setTimeout(function() {
                $('.alert').fadeOut();
            }, 5000);
        });
    </script>
</body>
</html>