<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: signin');
    exit();
}

// Include database connection
require_once 'db.php';

// Verify role-based access
checkAccess();

$user_id = $_SESSION['user_id'];
$user_name = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Admin User';

// Vendor categories
$vendor_categories = [
    'Raw Materials Supplier (Cement, Steel)',
    'Specialty Subcontractor (Electrical, Plumbing)',
    'Machinery Rental & Maintenance',
    'Logistics & Transportation',
    'Consulting & Engineering Services',
    'Safety Equipment Provider',
];

// Handle vendor deletion - maps to vendors table: id
if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['vendor_id'])) {
    $vendor_id = intval($_POST['vendor_id']);
    
    // First check if vendor status is 'Pending'
    $check_sql = "SELECT status, material_kit_image FROM vendors WHERE id = ?";
    $check_stmt = mysqli_prepare($conn, $check_sql);

    if ($check_stmt) {
        mysqli_stmt_bind_param($check_stmt, "i", $vendor_id);
        if (mysqli_stmt_execute($check_stmt)) {
            $check_result = mysqli_stmt_get_result($check_stmt);
            $vendor = mysqli_fetch_assoc($check_result);

            if (!$vendor) {
                echo json_encode(['success' => false, 'message' => 'Vendor not found']);
                mysqli_stmt_close($check_stmt);
                exit();
            }

            // Check if vendor status is 'Pending'
            if ($vendor['status'] !== 'Pending') {
                echo json_encode(['success' => false, 'message' => 'Only pending vendors can be deleted']);
                mysqli_stmt_close($check_stmt);
                exit();
            }

            // Delete material kit image if exists
            if (!empty($vendor['material_kit_image'])) {
                $imagePath = $vendor['material_kit_image'];
                if (file_exists($imagePath)) {
                    unlink($imagePath);
                }
            }

            // Delete the vendor record
            $delete_sql = "DELETE FROM vendors WHERE id = ?";
            $delete_stmt = mysqli_prepare($conn, $delete_sql);
            
            if ($delete_stmt) {
                mysqli_stmt_bind_param($delete_stmt, "i", $vendor_id);
                if (mysqli_stmt_execute($delete_stmt)) {
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
                }
                mysqli_stmt_close($delete_stmt);
            } else {
                echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
        }
        mysqli_stmt_close($check_stmt);
    } else {
        echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
    }
    exit();
}

// Handle vendor update - maps to vendors table: vendor_name, contact_person, phone, email, category, rating, payment_terms, address, material_kit_given, location_details, status, id
if (isset($_POST['action']) && $_POST['action'] === 'update' && isset($_POST['vendor_id'])) {
    $vendor_id = intval($_POST['vendor_id']);
    $vendor_name = trim($_POST['vendor_name']);
    $contact_person = trim($_POST['contact_person']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $category = $_POST['category'];
    $rating = intval($_POST['rating']);
    $payment_terms = trim($_POST['payment_terms']);
    $address = trim($_POST['address']);
    $material_kit_given = $_POST['material_kit_given'];
    $location_details = !empty($_POST['location_details']) ? trim($_POST['location_details']) : NULL;
    $status = $_POST['status'];

$sql = "UPDATE vendors SET vendor_name=?, contact_person=?, phone=?, email=?, category=?, rating=?, payment_terms=?, address=?, material_kit_given=?, location_details=?, status=?, updated_at = NOW()
             WHERE id=?";
    $stmt = mysqli_prepare($conn, $sql);

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "sssssisssssi", $vendor_name, $contact_person, $phone, $email, $category, $rating, $payment_terms, $address, $material_kit_given, $location_details, $status, $vendor_id);
        if (mysqli_stmt_execute($stmt)) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
        }
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
    }
    exit();
}

// Handle get vendor details - maps to vendors table: all fields for a specific vendor
if (isset($_POST['action']) && $_POST['action'] === 'get_details' && isset($_POST['vendor_id'])) {
    $vendor_id = intval($_POST['vendor_id']);

$sql = "SELECT id, vendor_name, contact_person, phone, email, category, payment_terms, address, status, rating, projects_completed, material_kit_given, location_details, material_kit_image, created_at, updated_at
            FROM vendors WHERE id = ?";
    $stmt = mysqli_prepare($conn, $sql);

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $vendor_id);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            if ($row = mysqli_fetch_assoc($result)) {
                echo json_encode(['success' => true, 'vendor' => $row]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Vendor not found']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
        }
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
    }
    exit();
}

// Fetch vendors from database - selects from vendors table: id, vendor_name, contact_person, phone, email, category, payment_terms, address, status, rating, projects_completed, material_kit_given, location_details, material_kit_image
$vendors = [];
$sql = "SELECT id, vendor_name, contact_person, phone, email, category, payment_terms, address, status, rating, projects_completed, material_kit_given, location_details, material_kit_image
        FROM vendors ORDER BY created_at DESC";
$stmt = mysqli_prepare($conn, $sql);

if ($stmt) {
    if (mysqli_stmt_execute($stmt)) {
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $vendors[] = $row;
        }
    }
    mysqli_stmt_close($stmt);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Vendors - ConstructCRM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
    :root {
        --primary-color: #977C49;
        --primary-dark: #7a633a;
        --primary-light: #f8f5ef;
        --secondary-color: #343a40;
        --secondary-light: #f8f9fa;
        --success-color: #28a745;
        --info-color: #17a2b8;
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --light-color: #f8f9fa;
        --dark-color: #343a40;
        --sidebar-width: 320px;
        --nav-width: 260px;
        --header-height: 70px;
        --footer-height: 40px;
        --border-radius: 12px;
        --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', sans-serif;
        background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
        color: #2c3e50;
        font-size: 14px;
        line-height: 1.4;
        overflow-x: hidden;
    }

    /* Header */
    .header {
        background-color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: var(--header-height);
        z-index: 1000;
        display: flex;
        align-items: center;
        padding: 0 20px;
    }

    .logo {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 20px;
        color: var(--primary-color);
        text-decoration: none;
    }

    .logo i {
        font-size: 24px;
        margin-right: 10px;
    }

    .header-actions {
        margin-left: auto;
        display: flex;
        align-items: center;
    }

    .mobile-menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 24px;
        color: var(--primary-color);
        margin-right: 15px;
        cursor: pointer;
    }

    /* User Dropdown */
    .user-dropdown {
        position: relative;
    }

    .user-profile {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: var(--border-radius);
        transition: var(--transition);
    }

    .user-profile:hover {
        background-color: #f8f9fa;
    }

    .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-right: 10px;
    }

    .user-name {
        font-weight: 500;
        margin-right: 5px;
    }

    .dropdown-arrow {
        font-size: 12px;
        color: #666;
        transition: var(--transition);
    }

    .user-dropdown.show .dropdown-arrow {
        transform: rotate(180deg);
    }

    .user-dropdown-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        min-width: 180px;
        padding: 8px 0;
        margin-top: 5px;
        opacity: 0;
        visibility: hidden;
        transform: translateY(-10px);
        transition: var(--transition);
        z-index: 1001;
    }

    .user-dropdown.show .user-dropdown-menu {
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
    }

    .dropdown-item {
        display: flex;
        align-items: center;
        padding: 10px 20px;
        color: #555;
        text-decoration: none;
        transition: var(--transition);
    }

    .dropdown-item:hover {
        background-color: #f8f9fa;
        color: var(--primary-color);
    }

    .dropdown-item i {
        margin-right: 10px;
        font-size: 16px;
    }

    .dropdown-divider {
        height: 1px;
        background-color: #eee;
        margin: 8px 0;
    }

    /* Main Layout */
    .main-container {
        display: flex;
        min-height: calc(100vh - var(--header-height));
        margin-top: var(--header-height);
    }

    /* Sidebar Navigation */
    .sidebar-nav {
        width: var(--nav-width);
        background-color: #fff;
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: var(--header-height);
        left: 0;
        bottom: 0;
        z-index: 999;
        overflow-y: auto;
        transition: var(--transition);
    }

    .nav-section {
        padding: 15px 0;
    }

    .nav-section:last-child {
        padding-bottom: 20px;
    }

    .nav-title {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #999;
        padding: 0 20px;
        margin-bottom: 10px;
    }

    .nav-list {
        list-style: none;
    }

    .nav-item {
        margin-bottom: 5px;
    }

    .nav-link {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        color: #555;
        text-decoration: none;
        font-weight: 500;
        transition: var(--transition);
        position: relative;
    }

    .nav-link i {
        font-size: 18px;
        margin-right: 12px;
        width: 20px;
        text-align: center;
    }

    .nav-link:hover {
        background-color: rgba(151, 124, 73, 0.05);
        color: var(--primary-color);
    }

    .nav-link.active {
        background: linear-gradient(90deg, rgba(151, 124, 73, 0.15) 0%, rgba(151, 124, 73, 0.05) 100%);
        color: var(--primary-color);
        font-weight: 600;
    }

    .nav-link.active::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background-color: var(--primary-color);
    }

    /* Content Wrapper */
    .content-wrapper {
        flex: 1;
        margin-left: var(--nav-width);
        display: flex;
        flex-direction: column;
        transition: var(--transition);
    }

    .content-header {
        background-color: #fff;
        padding: 20px 30px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }

    .breadcrumb {
        background-color: transparent;
        padding: 0;
        margin: 0;
        font-size: 13px;
    }

    .breadcrumb-item {
        color: #999;
    }

    .breadcrumb-item a {
        color: #999;
        text-decoration: none;
        transition: var(--transition);
    }

    .breadcrumb-item a:hover {
        color: var(--primary-color);
    }

    .breadcrumb-item.active {
        color: var(--primary-color);
        font-weight: 600;
    }

    .breadcrumb-item + .breadcrumb-item::before {
        content: "›";
        color: #ccc;
    }

    /* Main Content */
    .main-content {
        flex: 1;
        padding: 30px;
        overflow-y: auto;
    }

    /* Page Controls */
    .page-controls {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        padding: 25px;
        margin-bottom: 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 20px;
    }

    .search-container {
        position: relative;
        flex: 1;
        max-width: 400px;
    }

    .search-input {
        width: 100%;
        padding: 12px 0px 12px 27px;
        border: 2px solid #e9ecef;
        border-radius: 50px;
        font-size: 13px;
        transition: var(--transition);
        background: #fff;
    }

    .search-input:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
    }

    .search-icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        font-size: 15px;
    }

    .filter-container {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .filter-select {
        padding: 10px 15px;
        border: 2px solid #e9ecef;
        border-radius: var(--border-radius);
        font-size: 14px;
        transition: var(--transition);
        background: #fff;
    }

    .filter-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
    }

    .btn {
        padding: 10px 20px;
        border-radius: var(--border-radius);
        font-weight: 600;
        font-size: 14px;
        transition: var(--transition);
        cursor: pointer;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        box-shadow: 0 4px 12px rgba(151, 124, 73, 0.3);
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(151, 124, 73, 0.4);
    }

    .btn-outline-primary {
        background: transparent;
        color: var(--primary-color);
        border: 2px solid var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    /* Vendor Cards Container */
    .vendors-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 30px;
    }

    /* Vendor Card - Fixed Status Position */
    .vendor-card {
        background: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        transition: var(--transition);
        position: relative;
        border-top: 4px solid transparent;
    }

    .vendor-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
    }

    .vendor-card.active-vendor {
        border-top-color: transparent;
    }

    .vendor-card.hold-vendor {
        border-top-color: var(--warning-color);
    }

    .vendor-card-header {
        padding: 20px;
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        position: relative;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .vendor-id {
        position: absolute;
        top: 10px;
        right: 15px;
        background: rgba(255, 255, 255, 0.2);
        padding: 3px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
    }

    /* Fixed: Status moved to top right corner */
    .vendor-status {
        position: absolute;
        top: 10px;
        left: 15px;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: flex;
        align-items: center;
        gap: 5px;
        z-index: 10;
    }

    .status-active {
        background: white;
        color: var(--success-color);
        box-shadow: 0 2px 5px rgba(40, 167, 69, 0.2);
    }

    .status-hold {
        background: rgba(255, 193, 7, 0.2);
        color: var(--warning-color);
        box-shadow: 0 2px 5px rgba(255, 193, 7, 0.2);
    }

    /* Simplified status indicator */
    .status-active::before,
    .status-hold::before {
        content: '';
        width: 8px;
        height: 8px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 5px;
    }

    .status-active::before {
        background-color: var(--success-color);
    }

    .status-hold::before {
        background-color: var(--warning-color);
    }

    /* Fixed: Vendor name with proper spacing */
    .vendor-title {
        font-size: 20px;
        font-weight: 600;
        margin: 25px 0 5px 0; /* Added top margin to avoid overlap */
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .vendor-category {
        background: rgba(255, 255, 255, 0.2);
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: inline-block;
        align-self: flex-start;
    }

    .vendor-card-body {
        padding: 25px;
    }

    .vendor-info {
        margin-bottom: 20px;
    }

    .vendor-name {
        font-size: 18px;
        font-weight: 600;
        color: var(--primary-color);
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .vendor-contact {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-bottom: 20px;
    }

    .contact-item {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 14px;
        color: #555;
    }

    .contact-item i {
        font-size: 18px;
        color: var(--primary-color);
        width: 20px;
        text-align: center;
    }

    .vendor-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #eee;
    }

    .vendor-rating {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .rating-stars {
        display: flex;
        gap: 2px;
    }

    .rating-star {
        color: #ddd;
        font-size: 18px;
        transition: var(--transition);
    }

    .rating-star.filled {
        color: #ffc107;
    }

    .vendor-projects {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        color: #555;
    }

    .vendor-projects i {
        color: var(--primary-color);
    }

    /* Enhanced Vendor Actions */
    .vendor-actions {
        display: flex;
        gap: 10px;
        margin-top: 20px;
    }

    .vendor-actions .btn {
        flex: 1;
        justify-content: center;
    }

    /* View Details Button */
    .view-details-btn {
        background: linear-gradient(135deg, #6c757d, #5a6268);
        color: white;
        margin-bottom:20px;
        margin-left:12px;
    }

    .view-details-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(108, 117, 125, 0.4);
    }

    /* Edit Button */
    .edit-vendor-btn, .delete-vendor-btn {
        margin-bottom:20px;
        margin-left:9px;
        margin-right:5px;
    }

    /* Edit Modal */
    .modal-content {
        border-radius: var(--border-radius);
        border: none;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
    }

    .modal-header {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        border-radius: var(--border-radius) var(--border-radius) 0 0;
        border: none;
        padding: 20px 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        margin: 0;
    }

    .btn-close-white {
        filter: invert(1);
    }

    .modal-body {
        padding: 30px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-label {
        font-weight: 500;
        color: var(--dark-color);
        margin-bottom: 10px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-label i {
        color: var(--primary-color);
        font-size: 18px;
    }

    .form-control, .form-select {
        border: 2px solid #e9ecef;
        border-radius: var(--border-radius);
        padding: 12px 16px;
        font-size: 15px;
        transition: var(--transition);
        background: #fff;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
    }

    .modal-footer {
        padding: 20px 30px;
        display: flex;
        justify-content: flex-end;
        gap: 15px;
        border-top: 1px solid #eee;
    }

    /* Alert styling */
    .alert {
        border-radius: var(--border-radius);
        border: none;
        padding: 16px 20px;
        margin-top: 20px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .alert-success {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
    }

    .alert-danger {
        background-color: rgba(220, 53, 69, 0.1);
        color: var(--danger-color);
    }

    /* Empty State */
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
    }

    .empty-state i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #ddd;
    }

    .empty-state h3 {
        font-size: 22px;
        margin-bottom: 10px;
        color: #666;
    }

    .empty-state p {
        font-size: 16px;
        margin: 0;
    }

    /* Stats Section */
    .stats-section {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .stat-card {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 15px;
        transition: var(--transition);
    }

    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
    }

    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
    }

    .stat-icon.primary {
        background: rgba(151, 124, 73, 0.1);
        color: var(--primary-color);
    }

    .stat-icon.success {
        background: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
    }

    .stat-icon.warning {
        background: rgba(255, 193, 7, 0.1);
        color: var(--warning-color);
    }

    .stat-icon.info {
        background: rgba(23, 162, 184, 0.1);
        color: var(--info-color);
    }

    .stat-content {
        flex: 1;
    }

    .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #333;
    }

    .stat-label {
        font-size: 14px;
        color: #666;
    }

    /* Enhanced View Toggle */
    .view-toggle {
        display: flex;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        overflow: hidden;
    }

    .view-option {
        padding: 10px 15px;
        background: none;
        border: none;
        color: #666;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .view-option.active {
        background-color: var(--primary-color);
        color: white;
    }

    .view-option:hover:not(.active) {
        background-color: #f8f9fa;
    }

    /* List View Styles */
    .vendors-container.list-view {
        display: block;
    }

    .vendor-table {
        background: white;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        overflow: hidden;
    }

    .vendor-table table {
        width: 100%;
        border-collapse: collapse;
    }

    .vendor-table th {
        background-color: var(--primary-light);
        padding: 15px;
        text-align: left;
        font-weight: 600;
        color: var(--primary-color);
        border-bottom: 2px solid var(--primary-color);
    }

    .vendor-table td {
        padding: 15px;
        border-bottom: 1px solid #eee;
    }

    .vendor-table tr:last-child td {
        border-bottom: none;
    }

    .vendor-table tr:hover {
        background-color: rgba(151, 124, 73, 0.05);
    }

    .vendor-table .badge {
        padding: 5px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .vendor-table .badge-success {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
    }

    .vendor-table .badge-warning {
        background-color: rgba(255, 193, 7, 0.1);
        color: var(--warning-color);
    }

    /* Responsive */
    @media (max-width: 1200px) {
        .vendors-container {
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        }
    }

    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: block;
        }
        
        .sidebar-nav {
            transform: translateX(-100%);
            width: 280px;
            z-index: 1001;
        }
        
        .sidebar-nav.show {
            transform: translateX(0);
        }
        
        .content-wrapper {
            margin-left: 0;
        }

        .overlay {
            z-index: 1000;
        }

        .overlay.show {
            display: block;
        }

        .content-header {
            padding: 15px 20px;
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .main-content {
            padding: 20px;
        }

        .page-controls {
            flex-direction: column;
            gap: 15px;
        }

        .search-container {
            max-width: 100%;
        }

        .filter-container {
            flex-direction: column;
            align-items: stretch;
            gap: 10px;
        }

        .filter-select {
            width: 100%;
        }

        .vendors-container {
            grid-template-columns: 1fr;
        }

        .stats-section {
            grid-template-columns: 1fr;
        }

        .form-body {
            padding: 20px;
        }

        .header {
            padding: 0 15px;
        }

        .logo {
            font-size: 18px;
        }

        .logo i {
            font-size: 20px;
        }

        .user-name {
            display: none;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            font-size: 14px;
        }
    }

   /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    ::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #ccc;
    }

    /* Overlay for mobile menu */
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 998;
    }

    .overlay.show {
        display: block;
    }

    /* Star Rating Component - Enhanced */
    .star-rating-container {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-top: 10px;
        border: 1px solid #e9ecef;
    }

    .star-rating {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
    }

    .star {
        font-size: 32px;
        color: #ddd;
        cursor: pointer;
        transition: all 0.2s ease;
        position: relative;
    }

    .star:hover {
        transform: scale(1.15);
    }

    .star.filled {
        color: #ffc107;
        animation: starPop 0.3s ease;
    }

    .star.hover {
        color: #ffdb4d;
        transform: scale(1.15);
    }

    @keyframes starPop {
        0% { transform: scale(1); }
        50% { transform: scale(1.3); }
        100% { transform: scale(1); }
    }

    .rating-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
    }

    .rating-text {
        font-size: 14px;
        color: #666;
        font-weight: 500;
    }

    .rating-value {
        background: var(--primary-color);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
        display: none;
    }

    .rating-value.show {
        display: inline-block;
    }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="header">
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="bi bi-list"></i>
        </button>
        <a href="crmdashboard" class="logo">
            <img src="./assets/logo.png" alt="ConstructCRM Logo" style="height: 60px; width: 85px;">
        </a>
        <div class="header-actions">
            <!-- User Dropdown -->
            <div class="user-dropdown" id="userDropdown">
                <div class="user-profile" id="userProfile">
                    <div class="user-avatar"><?php echo htmlspecialchars(strtoupper(substr($user_name, 0, 1))); ?></div>
                    <span class="user-name"><?php echo htmlspecialchars($user_name); ?></span>
                    <i class="bi bi-chevron-down dropdown-arrow"></i>
                </div>
                <div class="user-dropdown-menu">
                    <a href="profile" class="dropdown-item">
                        <i class="bi bi-person"></i>
                        <span>Profile</span>
                    </a>
                    <a href="settings" class="dropdown-item">
                        <i class="bi bi-gear"></i>
                        <span>Settings</span>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="signin?logout=true" class="dropdown-item">
                        <i class="bi bi-box-arrow-right"></i>
                        <span>Logout</span>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="main-container">
        <!-- Overlay for mobile -->
        <div class="overlay" id="overlay"></div>

        <!-- Sidebar Navigation -->
        <nav class="sidebar-nav" id="sidebarNav">
            <div class="nav-section">
                <div class="nav-title">Main</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="crmdashboard" class="nav-link">
                            <i class="bi bi-speedometer2"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="dashboard" class="nav-link">
                            <i class="bi bi-grid-1x2-fill"></i>
                            <span>Client</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="projectlist" class="nav-link">
                            <i class="bi bi-list-ul"></i>
                            <span>Project List</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="designimages" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Design images</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="assignmentcalendar" class="nav-link">
                            <i class="bi bi-calendar-event-fill"></i>
                            <span>Assignment Calendar</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>place_order" class="nav-link">
                            <i class="bi bi-cart-check"></i> 
                            <span>Place Order</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="financetracker" class="nav-link">
                            <i class="bi bi-cash-stack"></i>
                            <span>Finance Tracker</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="imagepin" class="nav-link">
                            <i class="bi bi-pin-map-fill"></i>
                            <span>Image Pin & Comment</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="designcost" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Designs Cost</span>
                        </a>
                    </li>
                </ul>
            </div>
            
            <div class="nav-section">
                <div class="nav-title">Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="taskmanager" class="nav-link">
                            <i class="bi bi-check2-square"></i>
                            <span>Task Manager</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="users" class="nav-link">
                            <i class="bi bi-people-fill"></i>
                            <span>Users</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <div class="nav-section">
                <div class="nav-title">Vendor Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="addvendors" class="nav-link">
                            <i class="bi bi-person-plus-fill"></i>
                            <span>Add New Vendor</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="viewvendors" class="nav-link active">
                            <i class="bi bi-card-list"></i>
                            <span>View All Vendors</span>
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Wrapper -->
        <div class="content-wrapper">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="page-title">Vendor Management</h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item"><a href="#">Management</a></li>
                        <li class="breadcrumb-item active" aria-current="page">View All Vendors</li>
                    </ol>
                </nav>
            </div>

            <!-- Main Content -->
            <div class="main-content">
                <!-- Stats Section -->
                <div class="stats-section">
                    <div class="stat-card">
                        <div class="stat-icon primary">
                            <i class="bi bi-people-fill"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value"><?php echo count($vendors); ?></div>
                            <div class="stat-label">Total Vendors</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon success">
                            <i class="bi bi-check-circle-fill"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value"><?php echo count(array_filter($vendors, function($v) { return $v['status'] === 'Active'; })); ?></div>
                            <div class="stat-label">Active Vendors</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon warning">
                            <i class="bi bi-pause-circle-fill"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value"><?php echo count(array_filter($vendors, function($v) { return $v['status'] === 'On Hold'; })); ?></div>
                            <div class="stat-label">On Hold</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon info">
                            <i class="bi bi-star-fill"></i>
                        </div>
                        <div class="stat-content">
                            <div class="stat-value"><?php echo count($vendors) > 0 ? number_format(array_sum(array_column($vendors, 'rating')) / count($vendors), 1) : '0.0'; ?></div>
                            <div class="stat-label">Avg. Rating</div>
                        </div>
                    </div>
                </div>

                <!-- Page Controls -->
                <div class="page-controls">
                    <div class="search-container">
                        <input type="text" class="search-input" id="vendorSearch" placeholder="Search vendors by name or category...">
                        <i class="bi bi-search search-icon"></i>
                    </div>
                    
                    <div class="filter-container">
                        <div class="view-toggle">
                            <button class="view-option active" data-view="grid">
                                <i class="bi bi-grid-3x3-gap"></i>
                                Grid
                            </button>
                            <button class="view-option" data-view="list">
                                <i class="bi bi-list-ul"></i>
                                List
                            </button>
                        </div>
                        
                        <select class="filter-select" id="categoryFilter">
                            <option value="">All Categories</option>
                            <?php foreach ($vendor_categories as $cat): ?>
                                <option value="<?= $cat ?>"><?= $cat ?></option>
                            <?php endforeach; ?>
                        </select>
                        
<select class="filter-select" id="statusFilter">
                            <option value="">All Status</option>
                            <option value="Active">Active</option>
                            <option value="On Hold">On Hold</option>
                            <option value="Pending">Pending</option>
                        </select>
                        
                        <button class="btn btn-outline-primary" id="addVendorBtn">
                            <i class="bi bi-plus-circle"></i>
                            Add New Vendor
                        </button>
                    </div>
                </div>

                <!-- Vendor Cards Container -->
                <div class="vendors-container" id="vendorsContainer">
                    <?php if (empty($vendors)): ?>
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <h3>No Vendors Found</h3>
                            <p>Start by adding your first vendor using the "Add New Vendor" button.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($vendors as $vendor): ?>
                            <div class="vendor-card <?php echo $vendor['status'] === 'Active' ? 'active-vendor' : 'hold-vendor'; ?>" 
                                 data-vendor-id="<?= htmlspecialchars($vendor['id']) ?>" 
                                 data-vendor-name="<?= htmlspecialchars($vendor['vendor_name']) ?>" 
                                 data-vendor-category="<?= htmlspecialchars($vendor['category']) ?>"
                                 data-vendor-status="<?= htmlspecialchars($vendor['status']) ?>">
                                <div class="vendor-card-header">
                                    <div class="vendor-id">V-<?= htmlspecialchars($vendor['id']) ?></div>
                                    <div class="vendor-status status-<?= htmlspecialchars(strtolower(str_replace(' ', '-', $vendor['status']))) ?>">
                                        <?= htmlspecialchars($vendor['status']) ?>
                                    </div>
                                    <div class="vendor-title">
                                        <i class="bi bi-building"></i>
                                        <?= htmlspecialchars($vendor['vendor_name']) ?>
                                    </div>
                                    <div class="vendor-category">
                                        <?= htmlspecialchars($vendor['category']) ?>
                                    </div>
                                </div>
                                <div class="vendor-card-body">
                                    <div class="vendor-info">
                                        <div class="vendor-contact">
                                            <div class="contact-item">
                                                <i class="bi bi-person-circle"></i>
                                                <span><?= htmlspecialchars($vendor['contact_person']) ?></span>
                                            </div>
                                            <div class="contact-item">
                                                <i class="bi bi-telephone"></i>
                                                <span><?= htmlspecialchars($vendor['phone']) ?></span>
                                            </div>
                                            <div class="contact-item">
                                                <i class="bi bi-envelope"></i>
                                                <span><?= htmlspecialchars($vendor['email']) ?></span>
                                            </div>
                                            <div class="contact-item">
                                                <i class="bi bi-credit-card"></i>
                                                <span><?= htmlspecialchars($vendor['payment_terms']) ?></span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="vendor-meta">
                                        <div class="vendor-rating">
                                            <div class="rating-stars">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <i class="bi bi-star-fill rating-star <?= $i <= round($vendor['rating']) ? 'filled' : '' ?>"></i>
                                                <?php endfor; ?>
                                            </div>
                                            <span><?= number_format($vendor['rating'], 1) ?>/5</span>
                                        </div>
                                        <div class="vendor-projects">
                                            <i class="bi bi-briefcase-fill"></i>
                                            <span><?= $vendor['projects_completed'] ?> Projects</span>
                                        </div>
                                    </div>
                                    <!-- Material Kit Badge -->
                                    <?php if (!empty($vendor['material_kit_given']) && $vendor['material_kit_given'] === 'Yes'): ?>
                                    <div class="vendor-material-kit mt-2">
                                        <span class="badge" style="background-color: #6f42c1; color: white;">
                                            <i class="bi bi-box-seam me-1"></i>
                                            Material Kit Given
                                        </span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="vendor-actions">
                                    <button class="btn btn-outline-primary view-details-btn" data-vendor-id="<?= htmlspecialchars($vendor['id']) ?>">
                                        <i class="bi bi-eye"></i>
                                        View Details
                                    </button>
                                    <button class="btn btn-outline-primary edit-vendor-btn" data-vendor-id="<?= htmlspecialchars($vendor['id']) ?>">
                                        <i class="bi bi-pencil"></i>
                                        Edit
                                    </button>
<button class="btn btn-outline-danger delete-vendor-btn" data-vendor-id="<?= htmlspecialchars($vendor['id']) ?>" data-vendor-name="<?= htmlspecialchars($vendor['vendor_name']) ?>" data-vendor-status="<?= htmlspecialchars($vendor['status']) ?>">
                                        <i class="bi bi-trash"></i>
                                        Delete
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Vendor Modal -->
    <div class="modal fade" id="editVendorModal" tabindex="-1" aria-labelledby="editVendorModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editVendorModalLabel">
                        <i class="bi bi-pencil-square"></i>
                        Edit Vendor Information
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editVendorForm">
                        <input type="hidden" id="editVendorId">
                        
                        <div class="form-group">
                            <label for="editVendorName" class="form-label">
                                <i class="bi bi-building"></i>
                                Vendor Name
                            </label>
                            <input type="text" class="form-control" id="editVendorName" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorCategory" class="form-label">
                                <i class="bi bi-tags"></i>
                                Service Category
                            </label>
                            <select class="form-select" id="editVendorCategory" required>
                                <?php foreach ($vendor_categories as $cat): ?>
                                    <option value="<?= $cat ?>"><?= $cat ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorContact" class="form-label">
                                <i class="bi bi-person-circle"></i>
                                Primary Contact Person
                            </label>
                            <input type="text" class="form-control" id="editVendorContact" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorPhone" class="form-label">
                                <i class="bi bi-telephone"></i>
                                Phone Number
                            </label>
                            <input type="tel" class="form-control" id="editVendorPhone" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorEmail" class="form-label">
                                <i class="bi bi-envelope"></i>
                                Email Address
                            </label>
                            <input type="email" class="form-control" id="editVendorEmail" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorTerms" class="form-label">
                                <i class="bi bi-credit-card"></i>
                                Payment Terms
                            </label>
                            <input type="text" class="form-control" id="editVendorTerms" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorRating" class="form-label">
                                <i class="bi bi-star-fill"></i>
                                Vendor Rating
                            </label>
                            <div class="star-rating-container">
                                <div class="star-rating" id="editStarRating">
                                    <i class="bi bi-star-fill star" data-rating="1"></i>
                                    <i class="bi bi-star-fill star" data-rating="2"></i>
                                    <i class="bi bi-star-fill star" data-rating="3"></i>
                                    <i class="bi bi-star-fill star" data-rating="4"></i>
                                    <i class="bi bi-star-fill star" data-rating="5"></i>
                                </div>
                                <div class="rating-info">
                                    <span class="rating-text" id="editRatingText">Click to rate vendor</span>
                                    <span class="rating-value" id="editRatingValue"></span>
                                </div>
                            </div>
                            <input type="hidden" id="editVendorRating" name="rating" value="">
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorAddress" class="form-label">
                                <i class="bi bi-geo-alt"></i>
                                Billing/Physical Address
                            </label>
                            <textarea class="form-control" id="editVendorAddress" rows="3" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorMaterialKit" class="form-label">
                                <i class="bi bi-box-seam"></i>
                                Material Kit Given
                            </label>
                            <select class="form-select" id="editVendorMaterialKit" required>
                                <option value="No">No</option>
                                <option value="Yes">Yes</option>
                            </select>
                        </div>
                        
                        <div class="form-group" id="editLocationDetailsGroup" style="display: none;">
                            <label for="editLocationDetails" class="form-label">
                                <i class="bi bi-geo"></i>
                                Location Details
                            </label>
                            <input type="text" class="form-control" id="editLocationDetails" placeholder="e.g., Cupboard number, box number, rack, etc.">
                        </div>
                        
                        <div class="form-group">
                            <label for="editVendorStatus" class="form-label">
                                <i class="bi bi-toggle-on"></i>
                                Status
                            </label>
<select class="form-select" id="editVendorStatus" required>
                                <option value="Active">Active</option>
                                <option value="On Hold">On Hold</option>
                                <option value="Pending">Pending</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveVendorChanges">Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- View Vendor Details Modal -->
    <div class="modal fade" id="viewVendorModal" tabindex="-1" aria-labelledby="viewVendorModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewVendorModalLabel">
                        <i class="bi bi-eye"></i>
                        Vendor Details
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="vendorDetailsContent">
                    <!-- Vendor details will be populated here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="editFromViewBtn">Edit Vendor</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="deleteConfirmModalLabel">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                        Confirm Delete
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this vendor?</p>
                    <div class="alert alert-warning" role="alert">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong id="deleteVendorName"></strong>
                    </div>
                    <p class="text-muted small">This action cannot be undone. The vendor and all associated data will be permanently removed.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                        <i class="bi bi-trash"></i>
                        Delete Vendor
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Status Message -->
    <div id="statusMessage" class="alert alert-success d-none" role="alert"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // DOM Elements
            const vendorSearch = document.getElementById('vendorSearch');
            const categoryFilter = document.getElementById('categoryFilter');
            const statusFilter = document.getElementById('statusFilter');
            const vendorsContainer = document.getElementById('vendorsContainer');
            const editVendorModal = new bootstrap.Modal(document.getElementById('editVendorModal'));
            const viewVendorModal = new bootstrap.Modal(document.getElementById('viewVendorModal'));
            const deleteConfirmModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
            const editVendorForm = document.getElementById('editVendorForm');
            const saveVendorChangesBtn = document.getElementById('saveVendorChanges');
            const editFromViewBtn = document.getElementById('editFromViewBtn');
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            const statusMessage = document.getElementById('statusMessage');
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebarNav = document.getElementById('sidebarNav');
            const overlay = document.getElementById('overlay');
            const userDropdown = document.getElementById('userDropdown');
            const userProfile = document.getElementById('userProfile');
            const viewOptions = document.querySelectorAll('.view-option');
            
            // Variables for delete functionality
            let pendingDeleteVendorId = null;
            let pendingDeleteVendorName = null;

/* Vendor data from PHP - maps to vendors table fields */
            const vendorsData = <?php echo json_encode(array_map(function($v) {
                return [
                    'id' => $v['id'],
                    'name' => $v['vendor_name'],
                    'category' => $v['category'],
                    'contact' => $v['contact_person'],
                    'phone' => $v['phone'],
                    'email' => $v['email'],
                    'terms' => $v['payment_terms'],
                    'status' => $v['status'],
                    'rating' => floatval($v['rating']),
                    'projects_completed' => intval($v['projects_completed']),
                    'material_kit_given' => isset($v['material_kit_given']) ? $v['material_kit_given'] : 'No',
                    'location_details' => isset($v['location_details']) ? $v['location_details'] : '',
                    'material_kit_image' => isset($v['material_kit_image']) ? $v['material_kit_image'] : ''
                ];
            }, $vendors)); ?>;
            let currentViewingVendor = null;
            let currentView = 'grid'; // Default view

            // Show status message function
            function showStatusMessage(message, type = 'success') {
                statusMessage.textContent = message;
                statusMessage.className = `alert alert-${type}`;
                statusMessage.classList.remove('d-none');

                // Auto-hide after 5 seconds
                setTimeout(() => {
                    statusMessage.classList.add('d-none');
                }, 5000);
            }

            // Initialize star rating for edit modal
            function initializeEditStarRating(rating) {
                const editStarRating = document.getElementById('editStarRating');
                const editStars = editStarRating ? editStarRating.querySelectorAll('.star') : [];
                const editRatingText = document.getElementById('editRatingText');
                const editRatingValue = document.getElementById('editRatingValue');
                const editVendorRating = document.getElementById('editVendorRating');
                
                editStars.forEach(star => star.classList.remove('filled'));
                
                for (let i = 0; i < rating && i < editStars.length; i++) {
                    editStars[i].classList.add('filled');
                }
                
                if (rating > 0) {
                    editRatingText.textContent = rating + ' Star' + (rating > 1 ? 's' : '');
                    editRatingValue.textContent = rating + '/5';
                    editRatingValue.classList.add('show');
                } else {
                    editRatingText.textContent = 'Click to rate vendor';
                    editRatingValue.classList.remove('show');
                }
                editVendorRating.value = rating;
            }

            // Handle material kit toggle in edit modal
            function handleEditMaterialKitToggle(materialKitGiven, locationDetails) {
                const editVendorMaterialKit = document.getElementById('editVendorMaterialKit');
                const editLocationDetailsGroup = document.getElementById('editLocationDetailsGroup');
                
                if (editVendorMaterialKit && editLocationDetailsGroup) {
                    editVendorMaterialKit.value = materialKitGiven || 'No';
                    if (materialKitGiven === 'Yes') {
                        editLocationDetailsGroup.style.display = 'block';
                        document.getElementById('editLocationDetails').value = locationDetails || '';
                    } else {
                        editLocationDetailsGroup.style.display = 'none';
                        document.getElementById('editLocationDetails').value = '';
                    }
                }
            }

            // Initialize star rating click handlers
            const editStarRatingEl = document.getElementById('editStarRating');
            if (editStarRatingEl) {
                const editStars = editStarRatingEl.querySelectorAll('.star');
                const editRatingText = document.getElementById('editRatingText');
                const editRatingValue = document.getElementById('editRatingValue');
                const editVendorRating = document.getElementById('editVendorRating');
                
                editStars.forEach(star => {
                    star.addEventListener('click', function() {
                        const rating = parseInt(this.dataset.rating);
                        editStars.forEach((s, index) => {
                            if (index < rating) {
                                s.classList.add('filled');
                            } else {
                                s.classList.remove('filled');
                            }
                        });
                        if (rating > 0) {
                            editRatingText.textContent = rating + ' Star' + (rating > 1 ? 's' : '');
                            editRatingValue.textContent = rating + '/5';
                            editRatingValue.classList.add('show');
                        } else {
                            editRatingText.textContent = 'Click to rate vendor';
                            editRatingValue.classList.remove('show');
                        }
                        editVendorRating.value = rating;
                    });
                    
                    star.addEventListener('mouseenter', function() {
                        const rating = parseInt(this.dataset.rating);
                        editStars.forEach((s, index) => {
                            if (index < rating) {
                                s.classList.add('hover');
                            } else {
                                s.classList.remove('hover');
                            }
                        });
                    });
                    
                    star.addEventListener('mouseleave', function() {
                        editStars.forEach(s => s.classList.remove('hover'));
                    });
                });
            }

            // Initialize material kit change handler
            const editVendorMaterialKitEl = document.getElementById('editVendorMaterialKit');
            if (editVendorMaterialKitEl) {
                editVendorMaterialKitEl.addEventListener('change', function() {
                    const editLocationDetailsGroup = document.getElementById('editLocationDetailsGroup');
                    if (this.value === 'Yes') {
                        editLocationDetailsGroup.style.display = 'block';
                    } else {
                        editLocationDetailsGroup.style.display = 'none';
                        document.getElementById('editLocationDetails').value = '';
                    }
                });
            }

            // Toggle view between grid and list
            function toggleView(viewType) {
                currentView = viewType;
                
                // Update active state of view buttons
                viewOptions.forEach(option => {
                    if (option.dataset.view === viewType) {
                        option.classList.add('active');
                    } else {
                        option.classList.remove('active');
                    }
                });

                // Update container class based on view type
                if (viewType === 'list') {
                    vendorsContainer.classList.add('list-view');
                    // Convert cards to list view
                    renderListView();
                } else {
                    vendorsContainer.classList.remove('list-view');
                    // Convert cards to grid view
                    renderGridView();
                }
            }

            // Render vendors in grid view
            function renderGridView() {
                vendorsContainer.innerHTML = '';
                
                if (vendorsData.length === 0) {
                    vendorsContainer.innerHTML = `
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <h3>No Vendors Found</h3>
                            <p>Start by adding your first vendor using the "Add New Vendor" button.</p>
                        </div>
                    `;
                    return;
                }

                vendorsData.forEach(vendor => {
                    const card = createVendorCard(vendor);
                    vendorsContainer.appendChild(card);
                });
            }

            // Render vendors in list view
            function renderListView() {
                vendorsContainer.innerHTML = '';
                
                if (vendorsData.length === 0) {
                    vendorsContainer.innerHTML = `
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <h3>No Vendors Found</h3>
                            <p>Start by adding your first vendor using the "Add New Vendor" button.</p>
                        </div>
                    `;
                    return;
                }

                // Create a table for list view
                const tableContainer = document.createElement('div');
                tableContainer.className = 'vendor-table';
                
                const table = document.createElement('table');
                table.innerHTML = `
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Contact</th>
                            <th>Status</th>
                            <th>Rating</th>
                            <th>Projects</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                `;

                const tbody = table.querySelector('tbody');
                vendorsData.forEach(vendor => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${vendor.id}</td>
                        <td><strong>${vendor.name}</strong></td>
                        <td>${vendor.category}</td>
                        <td>${vendor.contact}</td>
                        <td><span class="badge badge-${vendor.status === 'Active' ? 'success' : 'warning'}">${vendor.status}</span></td>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="rating-stars me-1">
                                    ${Array(5).fill(0).map((_, i) => 
                                        `<i class="bi bi-star-fill rating-star ${i < Math.round(vendor.rating) ? 'filled' : ''}" style="font-size: 14px;"></i>`
                                    ).join('')}
                                </div>
                                <span>${vendor.rating}</span>
                            </div>
                        </td>
                        <td>${vendor.projects_completed}</td>
                        <td>
                            <div class="btn-group" role="group">
                                <button class="btn btn-sm btn-outline-primary view-details-btn" data-vendor-id="${vendor.id}">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-primary edit-vendor-btn" data-vendor-id="${vendor.id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
<button class="btn btn-sm btn-outline-danger delete-vendor-btn" data-vendor-id="${vendor.id}" data-vendor-name="${vendor.name}" data-vendor-status="${vendor.status}">
                                    <i class="bi bi-trash"></i>
                        </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });

                tableContainer.appendChild(table);
                vendorsContainer.appendChild(tableContainer);
            }

            // Create vendor card element
            function createVendorCard(vendor) {
                const card = document.createElement('div');
                card.className = `vendor-card ${vendor.status === 'Active' ? 'active-vendor' : 'hold-vendor'}`;
                card.dataset.vendorId = vendor.id;
                card.dataset.vendorName = vendor.name;
                card.dataset.vendorCategory = vendor.category;
                card.dataset.vendorStatus = vendor.status;

                card.innerHTML = `
                    <div class="vendor-card-header">
                        <div class="vendor-id">${vendor.id}</div>
                        <div class="vendor-status status-${vendor.status.toLowerCase().replace(' ', '-')}">
                            ${vendor.status}
                        </div>
                        <div class="vendor-title">
                            <i class="bi bi-building"></i>
                            ${vendor.name}
                        </div>
                        <div class="vendor-category">
                            ${vendor.category}
                        </div>
                    </div>
                    <div class="vendor-card-body">
                        <div class="vendor-info">
                            <div class="vendor-contact">
                                <div class="contact-item">
                                    <i class="bi bi-person-circle"></i>
                                    <span>${vendor.contact}</span>
                                </div>
                                <div class="contact-item">
                                    <i class="bi bi-telephone"></i>
                                    <span>${vendor.phone}</span>
                                </div>
                                <div class="contact-item">
                                    <i class="bi bi-envelope"></i>
                                    <span>${vendor.email}</span>
                                </div>
                                <div class="contact-item">
                                    <i class="bi bi-credit-card"></i>
                                    <span>${vendor.terms}</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="vendor-meta">
                            <div class="vendor-rating">
                                <div class="rating-stars">
                                    ${Array(5).fill(0).map((_, i) => 
                                        `<i class="bi bi-star-fill rating-star ${i < Math.round(vendor.rating) ? 'filled' : ''}"></i>`
                                    ).join('')}
                                </div>
                                <span>${vendor.rating}/5</span>
                            </div>
                            <div class="vendor-projects">
                                <i class="bi bi-briefcase-fill"></i>
                                <span>${vendor.projects_completed} Projects</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="vendor-actions">
                        <button class="btn btn-outline-primary view-details-btn" data-vendor-id="${vendor.id}">
                            <i class="bi bi-eye"></i>
                            View Details
                        </button>
                        <button class="btn btn-outline-primary edit-vendor-btn" data-vendor-id="${vendor.id}">
                            <i class="bi bi-pencil"></i>
                            Edit
                        </button>
                        <button class="btn btn-outline-danger delete-vendor-btn" data-vendor-id="${vendor.id}" data-vendor-name="${vendor.name}" data-vendor-status="${vendor.status}">
                            <i class="bi bi-trash"></i>
                            Delete
                        </button>
                    </div>
                `;

                return card;
            }

            // Filter vendors function
            function filterVendors() {
                const searchTerm = vendorSearch.value.toLowerCase();
                const selectedCategory = categoryFilter.value;
                const selectedStatus = statusFilter.value;

                // Filter vendors data
                const filteredVendors = vendorsData.filter(vendor => {
                    const searchTermMatch = !searchTerm || vendor.name.toLowerCase().includes(searchTerm);
                    const categoryMatch = !selectedCategory || vendor.category === selectedCategory;
                    const statusMatch = !selectedStatus || vendor.status === selectedStatus;
                    
                    return searchTermMatch && categoryMatch && statusMatch;
                });

                // Re-render based on current view
                if (currentView === 'grid') {
                    vendorsContainer.innerHTML = '';
                    
                    if (filteredVendors.length === 0) {
                        vendorsContainer.innerHTML = `
                            <div class="empty-state">
                                <i class="bi bi-inbox"></i>
                                <h3>No Vendors Found</h3>
                                <p>Try adjusting your search or filter criteria.</p>
                            </div>
                        `;
                        return;
                    }

                    filteredVendors.forEach(vendor => {
                        const card = createVendorCard(vendor);
                        vendorsContainer.appendChild(card);
                    });
                } else {
                    // Update list view
                    const tbody = document.querySelector('.vendor-table tbody');
                    if (!tbody) return;
                    
                    tbody.innerHTML = '';
                    
                    if (filteredVendors.length === 0) {
                        vendorsContainer.innerHTML = `
                            <div class="empty-state">
                                <i class="bi bi-inbox"></i>
                                <h3>No Vendors Found</h3>
                                <p>Try adjusting your search or filter criteria.</p>
                            </div>
                        `;
                        return;
                    }

                    filteredVendors.forEach(vendor => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${vendor.id}</td>
                            <td><strong>${vendor.name}</strong></td>
                            <td>${vendor.category}</td>
                            <td>${vendor.contact}</td>
                            <td><span class="badge badge-${vendor.status === 'Active' ? 'success' : 'warning'}">${vendor.status}</span></td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="rating-stars me-1">
                                        ${Array(5).fill(0).map((_, i) => 
                                            `<i class="bi bi-star-fill rating-star ${i < Math.round(vendor.rating) ? 'filled' : ''}" style="font-size: 14px;"></i>`
                                        ).join('')}
                                    </div>
                                    <span>${vendor.rating}</span>
                                </div>
                            </td>
                            <td>${vendor.projects_completed}</td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-primary view-details-btn" data-vendor-id="${vendor.id}">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary edit-vendor-btn" data-vendor-id="${vendor.id}">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger delete-vendor-btn" data-vendor-id="${vendor.id}" data-vendor-name="${vendor.name}">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                }
            }

            // View vendor details function
            function viewVendorDetails(vendorId) {
                // Show loading state
                const detailsContent = document.getElementById('vendorDetailsContent');
                detailsContent.innerHTML = `
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">Loading vendor details...</p>
                    </div>
                `;

                // Make AJAX call to get vendor details
                const formData = new FormData();
                formData.append('action', 'get_details');
                formData.append('vendor_id', vendorId);

                fetch('viewvendors.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const vendor = data.vendor;
                        currentViewingVendor = vendor;

                        // Populate modal with vendor details
                        // Build Material Kit section if applicable
                        let materialKitHtml = '';
                        if (vendor.material_kit_given === 'Yes') {
                            materialKitHtml = `
                                <div class="mb-3">
                                    <h6 class="text-muted"><i class="bi bi-box-seam me-2"></i>Material Kit</h6>
                                    <p><span class="badge bg-success">Yes</span></p>
                                    ${vendor.location_details ? `
                                        <p><strong>Location:</strong> ${vendor.location_details}</p>
                                    ` : ''}
                                    ${vendor.material_kit_image ? `
                                        <p><strong>Material Kit Image:</strong></p>
                                        <img src="${vendor.material_kit_image}" alt="Material Kit" class="img-thumbnail" style="max-width: 200px; max-height: 200px;">
                                    ` : ''}
                                </div>
                            `;
                        } else {
                            materialKitHtml = `
                                <div class="mb-3">
                                    <h6 class="text-muted"><i class="bi bi-box-seam me-2"></i>Material Kit</h6>
                                    <p><span class="badge bg-secondary">No</span></p>
                                </div>
                            `;
                        }
                        
                        detailsContent.innerHTML = `
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <h6 class="text-muted">Vendor ID</h6>
                                        <p>${vendor.id}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Vendor Name</h6>
                                        <p>${vendor.vendor_name}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Category</h6>
                                        <p>${vendor.category}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Contact Person</h6>
                                        <p>${vendor.contact_person}</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <h6 class="text-muted">Phone Number</h6>
                                        <p>${vendor.phone}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Email Address</h6>
                                        <p>${vendor.email}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted"> Payment Terms</h6>
                                        <p>${vendor.payment_terms}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Status</h6>
                                        <p><span class="badge bg-${vendor.status === 'Active' ? 'success' : 'warning'}">${vendor.status}</span></p>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <h6 class="text-muted">Address</h6>
                                        <p>${vendor.address || 'Not provided'}</p>
                                    </div>
                                    <div class="mb-3">
                                        <h6 class="text-muted">Performance</h6>
                                        <div class="d-flex align-items-center">
                                            <div class="me-3">
                                                <div class="d-flex align-items-center mb-2">
                                                    <span class="me-2">Rating:</span>
                                                    <div class="rating-stars">
                                                        ${Array(5).fill(0).map((_, i) =>
                                                            `<i class="bi bi-star-fill rating-star ${i < Math.round(vendor.rating) ? 'filled' : ''}"></i>`
                                                        ).join('')}
                                                    </div>
                                                    <span class="ms-2">${vendor.rating}/5</span>
                                                </div>
                                                <div class="d-flex align-items-center">
                                                    <i class="bi bi-briefcase-fill me-2 text-primary"></i>
                                                    <span>${vendor.projects_completed} Projects Completed</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    ${materialKitHtml}
                                    <div class="mb-3">
                                        <h6 class="text-muted">Created</h6>
                                        <p>${new Date(vendor.created_at).toLocaleDateString()}</p>
                                    </div>
                                </div>
                            </div>
                        `;

                        // Show modal
                        viewVendorModal.show();
                    } else {
                        detailsContent.innerHTML = `
                            <div class="alert alert-danger">
                                <i class="bi bi-exclamation-triangle"></i>
                                ${data.message || 'Failed to load vendor details'}
                            </div>
                        `;
                        viewVendorModal.show();
                    }
                })
                .catch(error => {
                    detailsContent.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle"></i>
                            Error loading vendor details: ${error.message}
                        </div>
                    `;
                    viewVendorModal.show();
                });
            }

            // Edit vendor function
            function editVendor(vendorId) {
                // Make AJAX call to get latest vendor details
                const formData = new FormData();
                formData.append('action', 'get_details');
                formData.append('vendor_id', vendorId);

                fetch('viewvendors.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const vendor = data.vendor;

                        // Populate form with vendor data
                        document.getElementById('editVendorId').value = vendor.id;
                        document.getElementById('editVendorName').value = vendor.vendor_name;
                        document.getElementById('editVendorCategory').value = vendor.category;
                        document.getElementById('editVendorContact').value = vendor.contact_person;
                        document.getElementById('editVendorPhone').value = vendor.phone;
                        document.getElementById('editVendorEmail').value = vendor.email;
                        document.getElementById('editVendorTerms').value = vendor.payment_terms;
                        document.getElementById('editVendorAddress').value = vendor.address || '';
                        document.getElementById('editVendorStatus').value = vendor.status;
                        
                        // Initialize rating and material kit
                        initializeEditStarRating(parseInt(vendor.rating) || 0);
                        handleEditMaterialKitToggle(vendor.material_kit_given, vendor.location_details);

                        // Show modal
                        editVendorModal.show();
                    } else {
                        showStatusMessage('Error loading vendor data: ' + (data.message || 'Unknown error'), 'danger');
                    }
                })
                .catch(error => {
                    showStatusMessage('Error loading vendor data: ' + error.message, 'danger');
                });
            }

            // Save vendor changes function (removed, now inline)
            function saveVendorChanges() {
                // This function is no longer used
            }

            // Event Listeners
            vendorSearch.addEventListener('input', filterVendors);
            categoryFilter.addEventListener('change', filterVendors);
            statusFilter.addEventListener('change', filterVendors);

            // View toggle event listeners
            viewOptions.forEach(option => {
                option.addEventListener('click', function() {
                    toggleView(this.dataset.view);
                });
            });

            // Event delegation for dynamic elements
            vendorsContainer.addEventListener('click', function(e) {
                // View details button
                if (e.target.closest('.view-details-btn')) {
                    const vendorId = e.target.closest('.view-details-btn').dataset.vendorId;
                    viewVendorDetails(vendorId);
                }
                
                // Edit button
                if (e.target.closest('.edit-vendor-btn')) {
                    const vendorId = e.target.closest('.edit-vendor-btn').dataset.vendorId;
                    editVendor(vendorId);
                }
                
                // Delete button
                if (e.target.closest('.delete-vendor-btn')) {
                    const vendorId = e.target.closest('.delete-vendor-btn').dataset.vendorId;
                    const vendorName = e.target.closest('.delete-vendor-btn').dataset.vendorName;
                    const vendorStatus = e.target.closest('.delete-vendor-btn').dataset.vendorStatus;

                    // Check if vendor status is 'Pending'
                    if (vendorStatus !== 'Pending') {
                        showStatusMessage('Only pending vendors can be deleted', 'warning');
                        return;
                    }

                    if (confirm(`Are you sure you want to delete "${vendorName}"?`)) {
                        // Send delete request to server
                        const formData = new FormData();
                        formData.append('action', 'delete');
                        formData.append('vendor_id', vendorId);

                        fetch('viewvendors.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                const index = vendorsData.findIndex(v => v.id == vendorId);
                                if (index !== -1) {
                                    vendorsData.splice(index, 1);
                                }
                                filterVendors();
                                showStatusMessage(`Vendor "${vendorName}" deleted successfully!`, 'success');
                            } else {
                                showStatusMessage('Error deleting vendor: ' + data.message, 'danger');
                            }
                        })
                        .catch(error => {
                            showStatusMessage('Error deleting vendor: ' + error.message, 'danger');
                        });
                    }
                }
                
                // Option toggle
                if (e.target.closest('.option-toggle')) {
                    const vendorId = e.target.closest('.option-toggle').dataset.vendorId;
                    const dropdown = document.getElementById(`optionDropdown-${vendorId}`);
                    
                    // Close all other dropdowns
                    document.querySelectorAll('.option-dropdown').forEach(d => {
                        if (d !== dropdown) {
                            d.classList.remove('show');
                        }
                    });
                    
                    // Toggle current dropdown
                    dropdown.classList.toggle('show');
                }
            });

            // Close option dropdowns when clicking outside
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.option-menu')) {
                    document.querySelectorAll('.option-dropdown').forEach(dropdown => {
                        dropdown.classList.remove('show');
                    });
                }
            });

            // Save button listener
            saveVendorChangesBtn.addEventListener('click', function() {
                const vendorId = document.getElementById('editVendorId').value;
                const vendorIndex = vendorsData.findIndex(v => v.id == vendorId);

                if (vendorIndex === -1) {
                    showStatusMessage('Vendor not found', 'danger');
                    return;
                }

                // Get all form values including rating, address, material kit
                const rating = parseInt(document.getElementById('editVendorRating').value) || 0;
                const address = document.getElementById('editVendorAddress').value;
                const materialKitGiven = document.getElementById('editVendorMaterialKit').value;
                const locationDetails = document.getElementById('editLocationDetails').value;

                // Update vendor data
                const updatedVendor = {
                    ...vendorsData[vendorIndex],
                    name: document.getElementById('editVendorName').value,
                    category: document.getElementById('editVendorCategory').value,
                    contact: document.getElementById('editVendorContact').value,
                    phone: document.getElementById('editVendorPhone').value,
                    email: document.getElementById('editVendorEmail').value,
                    terms: document.getElementById('editVendorTerms').value,
                    status: document.getElementById('editVendorStatus').value,
                    rating: rating,
                    address: address,
                    material_kit_given: materialKitGiven,
                    location_details: locationDetails
                };

                // Send update to server with all fields
                const formData = new FormData();
                formData.append('action', 'update');
                formData.append('vendor_id', vendorId);
                formData.append('vendor_name', updatedVendor.name);
                formData.append('contact_person', updatedVendor.contact);
                formData.append('phone', updatedVendor.phone);
                formData.append('email', updatedVendor.email);
                formData.append('category', updatedVendor.category);
                formData.append('rating', updatedVendor.rating);
                formData.append('payment_terms', updatedVendor.terms);
                formData.append('address', updatedVendor.address);
                formData.append('material_kit_given', updatedVendor.material_kit_given);
                formData.append('location_details', updatedVendor.location_details);
                formData.append('status', updatedVendor.status);

                fetch('viewvendors.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        vendorsData[vendorIndex] = updatedVendor;
                        showStatusMessage(`Vendor "${updatedVendor.name}" updated successfully!`, 'success');
                        editVendorModal.hide();
                        filterVendors();
                    } else {
                        showStatusMessage('Error updating vendor: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showStatusMessage('Error updating vendor: ' + error.message, 'danger');
                });
            });

            // Edit from view button listener
            editFromViewBtn.addEventListener('click', function() {
                if (currentViewingVendor) {
                    viewVendorModal.hide();
                    setTimeout(() => {
                        editVendor(currentViewingVendor.id);
                    }, 300);
                }
            });

            // Mobile menu toggle
            mobileMenuToggle.addEventListener('click', () => {
                sidebarNav.classList.toggle('show');
                overlay.classList.toggle('show');
            });

            overlay.addEventListener('click', () => {
                sidebarNav.classList.remove('show');
                overlay.classList.remove('show');
            });

            // User dropdown
            userProfile.addEventListener('click', (e) => {
                e.stopPropagation();
                userDropdown.classList.toggle('show');
            });

            document.addEventListener('click', () => {
                userDropdown.classList.remove('show');
            });

            // Confirm delete button listener
            confirmDeleteBtn.addEventListener('click', function() {
                if (!pendingDeleteVendorId || !pendingDeleteVendorName) return;

                // Send delete request to server
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('vendor_id', pendingDeleteVendorId);

                fetch('viewvendors.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const index = vendorsData.findIndex(v => v.id == pendingDeleteVendorId);
                        if (index !== -1) {
                            vendorsData.splice(index, 1);
                        }
                        filterVendors();
                        showStatusMessage(`Vendor "${pendingDeleteVendorName}" deleted successfully!`, 'success');
                        deleteConfirmModal.hide();
                        pendingDeleteVendorId = null;
                        pendingDeleteVendorName = null;
                    } else {
                        showStatusMessage('Error deleting vendor: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showStatusMessage('Error deleting vendor: ' + error.message, 'danger');
                });
            });

            // Add new vendor button
            document.getElementById('addVendorBtn').addEventListener('click', () => {
                window.location.href = 'addvendors.php';
            });

            // Initialize with grid view
            renderGridView();
        });
    </script>
</body>
</html>
