<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle supplier operations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $response = ['success' => false, 'message' => ''];
    
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_supplier':
                    $supplier_name = trim($_POST['supplier_name']);
                    $contact_person = trim($_POST['contact_person']);
                    $email = trim($_POST['email']);
                    $phone = trim($_POST['phone']);
                    $address = trim($_POST['address']);
                    $payment_terms = trim($_POST['payment_terms']);
                    
                    // Check if supplier name already exists
                    $check_sql = "SELECT supplier_id FROM suppliers WHERE supplier_name = ?";
                    $check_stmt = $conn->prepare($check_sql);
                    $check_stmt->bind_param("s", $supplier_name);
                    $check_stmt->execute();
                    
                    if ($check_stmt->get_result()->num_rows > 0) {
                        $response['message'] = 'Supplier with this name already exists';
                        break;
                    }
                    
                    $insert_sql = "INSERT INTO suppliers (supplier_name, contact_person, email, phone, address, payment_terms) 
                                  VALUES (?, ?, ?, ?, ?, ?)";
                    $insert_stmt = $conn->prepare($insert_sql);
                    $insert_stmt->bind_param("ssssss", $supplier_name, $contact_person, $email, $phone, $address, $payment_terms);
                    
                    if ($insert_stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Supplier added successfully';
                    } else {
                        $response['message'] = 'Failed to add supplier';
                    }
                    break;
                    
                case 'update_supplier':
                    $supplier_id = $_POST['supplier_id'];
                    $supplier_name = trim($_POST['supplier_name']);
                    $contact_person = trim($_POST['contact_person']);
                    $email = trim($_POST['email']);
                    $phone = trim($_POST['phone']);
                    $address = trim($_POST['address']);
                    $payment_terms = trim($_POST['payment_terms']);
                    
                    $update_sql = "UPDATE suppliers SET 
                                  supplier_name = ?, contact_person = ?, email = ?, 
                                  phone = ?, address = ?, payment_terms = ?
                                  WHERE supplier_id = ?";
                    $update_stmt = $conn->prepare($update_sql);
                    $update_stmt->bind_param("ssssssi", $supplier_name, $contact_person, $email, $phone, $address, $payment_terms, $supplier_id);
                    
                    if ($update_stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Supplier updated successfully';
                    } else {
                        $response['message'] = 'Failed to update supplier';
                    }
                    break;
                    
                case 'deactivate_supplier':
                    $supplier_id = $_POST['supplier_id'];
                    
                    $deactivate_sql = "UPDATE suppliers SET is_active = 0 WHERE supplier_id = ?";
                    $deactivate_stmt = $conn->prepare($deactivate_sql);
                    $deactivate_stmt->bind_param("i", $supplier_id);
                    
                    if ($deactivate_stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Supplier deactivated successfully';
                    } else {
                        $response['message'] = 'Failed to deactivate supplier';
                    }
                    break;
                    
                case 'activate_supplier':
                    $supplier_id = $_POST['supplier_id'];
                    
                    $activate_sql = "UPDATE suppliers SET is_active = 1 WHERE supplier_id = ?";
                    $activate_stmt = $conn->prepare($activate_sql);
                    $activate_stmt->bind_param("i", $supplier_id);
                    
                    if ($activate_stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Supplier activated successfully';
                    } else {
                        $response['message'] = 'Failed to activate supplier';
                    }
                    break;
            }
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Get suppliers statistics
$sql_total_suppliers = "SELECT COUNT(*) as total_suppliers FROM suppliers";
$total_suppliers = $conn->query($sql_total_suppliers)->fetch_assoc()['total_suppliers'];

$sql_active_suppliers = "SELECT COUNT(*) as active_suppliers FROM suppliers WHERE is_active = 1";
$active_suppliers = $conn->query($sql_active_suppliers)->fetch_assoc()['active_suppliers'];

$sql_inactive_suppliers = "SELECT COUNT(*) as inactive_suppliers FROM suppliers WHERE is_active = 0";
$inactive_suppliers = $conn->query($sql_inactive_suppliers)->fetch_assoc()['inactive_suppliers'];

// Get suppliers with item counts and purchase order stats
$sql_suppliers = "SELECT 
    s.*,
    COUNT(DISTINCT ii.item_id) as items_supplied,
    COUNT(DISTINCT po.po_id) as total_purchase_orders,
    COALESCE(SUM(CASE WHEN po.status = 'COMPLETED' THEN po.total_amount ELSE 0 END), 0) as total_purchases
FROM suppliers s
LEFT JOIN inventory_items ii ON s.supplier_id = ii.supplier_id AND ii.is_active = 1
LEFT JOIN purchase_orders po ON s.supplier_id = po.supplier_id
GROUP BY s.supplier_id, s.supplier_name, s.contact_person, s.email, s.phone, s.address, s.payment_terms, s.is_active, s.created_at, s.updated_at
ORDER BY s.supplier_name";
$result_suppliers = $conn->query($sql_suppliers);

// Get recent supplier activities
$sql_recent_activities = "SELECT 
    'Purchase Order' as activity_type,
    po.po_number as reference,
    po.total_amount as amount,
    po.order_date as activity_date,
    s.supplier_name,
    po.status
FROM purchase_orders po
JOIN suppliers s ON po.supplier_id = s.supplier_id
UNION ALL
SELECT 
    'New Item' as activity_type,
    ii.item_code as reference,
    ii.unit_cost as amount,
    ii.created_at as activity_date,
    s.supplier_name,
    'ACTIVE' as status
FROM inventory_items ii
JOIN suppliers s ON ii.supplier_id = s.supplier_id
WHERE ii.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
ORDER BY activity_date DESC
LIMIT 10";
$result_activities = $conn->query($sql_recent_activities);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Suppliers Management - Laundry System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active { background: #dcfce7; color: #166534; }
        .status-inactive { background: #fee2e2; color: #991b1b; }
        .status-completed { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-sent { background: #dbeafe; color: #1d4ed8; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        .btn-primary {
            background: #059669;
            border-color: #059669;
        }
        
        .btn-primary:hover {
            background: #047857;
            border-color: #047857;
        }
        
        .btn-success {
            background: #059669;
            border-color: #059669;
        }
        
        .btn-warning {
            background: #d97706;
            border-color: #d97706;
        }
        
        .btn-danger {
            background: #dc2626;
            border-color: #dc2626;
        }
        
        .form-control:focus {
            border-color: #059669;
            box-shadow: 0 0 0 0.2rem rgba(5, 150, 105, 0.25);
        }
        
        .modal-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            border: none;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .supplier-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #059669;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .search-filter-bar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 1rem;
            align-items: end;
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .table-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Suppliers Management</h2>
                                <p class="mb-0">Manage supplier information, contacts, and business relationships</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addSupplierModal">
                                    <i class="bi bi-plus-circle me-2"></i>Add New Supplier
                                </button>
                                <button type="button" class="btn btn-outline-light" onclick="exportSuppliers()">
                                    <i class="bi bi-download me-2"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-title">Total Suppliers</div>
                            <div class="stat-value"><?php echo number_format($total_suppliers); ?></div>
                            <div class="stat-change" style="color: #059669;">Registered suppliers</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Suppliers</div>
                            <div class="stat-value" style="color: #059669;"><?php echo number_format($active_suppliers); ?></div>
                            <div class="stat-change" style="color: #64748b;">Currently active</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Inactive Suppliers</div>
                            <div class="stat-value" style="color: <?php echo $inactive_suppliers > 0 ? '#dc2626' : '#64748b'; ?>;">
                                <?php echo number_format($inactive_suppliers); ?>
                            </div>
                            <div class="stat-change" style="color: #64748b;">Not active</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Active Rate</div>
                            <div class="stat-value" style="color: #059669;">
                                <?php echo $total_suppliers > 0 ? number_format(($active_suppliers / $total_suppliers) * 100, 1) : 0; ?>%
                            </div>
                            <div class="stat-change" style="color: #64748b;">Supplier activity</div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="search-filter-bar">
                        <div class="filter-group">
                            <div>
                                <label class="form-label">Search Suppliers</label>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search by name, contact, email...">
                            </div>
                            <div>
                                <label class="form-label">Status</label>
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-primary d-block" onclick="filterTable()">
                                    <i class="bi bi-search"></i> Filter
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Suppliers Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">All Suppliers</h3>
                            <div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshTable()">
                                    <i class="bi bi-arrow-clockwise me-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table" id="suppliersTable">
                                <thead>
                                    <tr>
                                        <th>Supplier</th>
                                        <th>Contact Person</th>
                                        <th>Email & Phone</th>
                                        <th>Payment Terms</th>
                                        <th>Items Supplied</th>
                                        <th>Purchase Orders</th>
                                        <th>Total Purchases</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result_suppliers->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="supplier-avatar me-3">
                                                    <?php echo strtoupper(substr($row['supplier_name'], 0, 2)); ?>
                                                </div>
                                                <div>
                                                    <div style="font-weight: 600;"><?php echo htmlspecialchars($row['supplier_name']); ?></div>
                                                    <small style="color: #64748b;">
                                                        Added: <?php echo date('M j, Y', strtotime($row['created_at'])); ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight: 500;">
                                                <?php echo htmlspecialchars($row['contact_person'] ?: 'Not specified'); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div>
                                                <?php if($row['email']): ?>
                                                    <div style="color: #059669; font-weight: 500;">
                                                        <i class="bi bi-envelope me-1"></i>
                                                        <?php echo htmlspecialchars($row['email']); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if($row['phone']): ?>
                                                    <div style="color: #64748b;">
                                                        <i class="bi bi-telephone me-1"></i>
                                                        <?php echo htmlspecialchars($row['phone']); ?>
                                                    </div>
                                                <?php endif; ?>
                                                <?php if(!$row['email'] && !$row['phone']): ?>
                                                    <span style="color: #64748b;">No contact info</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo htmlspecialchars($row['payment_terms'] ?: 'Not specified'); ?>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; color: #059669;">
                                                <?php echo number_format($row['items_supplied']); ?>
                                            </span>
                                            <small style="color: #64748b;"> items</small>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600;">
                                                <?php echo number_format($row['total_purchase_orders']); ?>
                                            </span>
                                            <small style="color: #64748b;"> orders</small>
                                        </td>
                                        <td style="font-weight: 600; color: #059669;">
                                            KES <?php echo number_format($row['total_purchases'], 2); ?>
                                        </td>
                                        <td>
                                            <span class="status-badge <?php echo $row['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                                <?php echo $row['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn btn btn-sm btn-primary" onclick="viewSupplier(<?php echo $row['supplier_id']; ?>)" title="View Details">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="action-btn btn btn-sm btn-warning" onclick="editSupplier(<?php echo $row['supplier_id']; ?>)" title="Edit">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <?php if($row['is_active']): ?>
                                                    <button class="action-btn btn btn-sm btn-danger" onclick="deactivateSupplier(<?php echo $row['supplier_id']; ?>)" title="Deactivate">
                                                        <i class="bi bi-x-circle"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button class="action-btn btn btn-sm btn-success" onclick="activateSupplier(<?php echo $row['supplier_id']; ?>)" title="Activate">
                                                        <i class="bi bi-check-circle"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Recent Activities -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Supplier Activities</h3>
                            <a href="supplier_activities.php" class="btn btn-outline-primary btn-sm">View All</a>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Supplier</th>
                                        <th>Activity Type</th>
                                        <th>Reference</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if($result_activities->num_rows > 0): ?>
                                        <?php while($row = $result_activities->fetch_assoc()): ?>
                                        <tr>
                                            <td style="color: #64748b;">
                                                <?php echo date('M j, Y g:i A', strtotime($row['activity_date'])); ?>
                                            </td>
                                            <td>
                                                <div style="font-weight: 600;"><?php echo htmlspecialchars($row['supplier_name']); ?></div>
                                            </td>
                                            <td>
                                                <span class="status-badge status-active">
                                                    <?php echo $row['activity_type']; ?>
                                                </span>
                                            </td>
                                            <td style="font-weight: 500; color: #059669;">
                                                <?php echo htmlspecialchars($row['reference']); ?>
                                            </td>
                                            <td style="font-weight: 600;">
                                                <?php if($row['amount']): ?>
                                                    KES <?php echo number_format($row['amount'], 2); ?>
                                                <?php else: ?>
                                                    <span style="color: #64748b;">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php 
                                                $status_class = match(strtolower($row['status'])) {
                                                    'completed' => 'status-completed',
                                                    'pending' => 'status-pending',
                                                    'sent' => 'status-sent',
                                                    'cancelled' => 'status-cancelled',
                                                    'active' => 'status-active',
                                                    default => 'status-active'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst($row['status']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center" style="color: #64748b; padding: 2rem;">
                                                No recent activities found
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Supplier Modal -->
    <div class="modal fade" id="addSupplierModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Supplier</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addSupplierForm">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Supplier Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="supplier_name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Contact Person</label>
                                    <input type="text" class="form-control" name="contact_person">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Email</label>
                                    <input type="email" class="form-control" name="email">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Phone</label>
                                    <input type="text" class="form-control" name="phone">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Address</label>
                            <textarea class="form-control" name="address" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Terms</label>
                            <select class="form-select" name="payment_terms">
                                <option value="">Select payment terms...</option>
                                <option value="Cash on Delivery">Cash on Delivery</option>
                                <option value="Net 7 Days">Net 7 Days</option>
                                <option value="Net 15 Days">Net 15 Days</option>
                                <option value="Net 30 Days">Net 30 Days</option>
                                <option value="Net 60 Days">Net 60 Days</option>
                                <option value="Prepaid">Prepaid</option>
                                <option value="Credit">Credit</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Supplier</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Supplier Modal -->
    <div class="modal fade" id="editSupplierModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Supplier</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="editSupplierForm">
                    <input type="hidden" name="supplier_id" id="edit_supplier_id">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Supplier Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="supplier_name" id="edit_supplier_name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Contact Person</label>
                                    <input type="text" class="form-control" name="contact_person" id="edit_contact_person">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Email</label>
                                    <input type="email" class="form-control" name="email" id="edit_email">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Phone</label>
                                    <input type="text" class="form-control" name="phone" id="edit_phone">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Address</label>
                            <textarea class="form-control" name="address" id="edit_address" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Terms</label>
                            <select class="form-select" name="payment_terms" id="edit_payment_terms">
                                <option value="">Select payment terms...</option>
                                <option value="Cash on Delivery">Cash on Delivery</option>
                                <option value="Net 7 Days">Net 7 Days</option>
                                <option value="Net 15 Days">Net 15 Days</option>
                                <option value="Net 30 Days">Net 30 Days</option>
                                <option value="Net 60 Days">Net 60 Days</option>
                                <option value="Prepaid">Prepaid</option>
                                <option value="Credit">Credit</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Supplier</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Global variable to store suppliers data
    let suppliersData = <?php 
        $result_suppliers->data_seek(0);
        $suppliers = [];
        while($row = $result_suppliers->fetch_assoc()) {
            $suppliers[] = $row;
        }
        echo json_encode($suppliers);
    ?>;

    // Form submission handlers
    document.getElementById('addSupplierForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'add_supplier');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('addSupplierModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while adding supplier');
        });
    });

    document.getElementById('editSupplierForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'update_supplier');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('editSupplierModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while updating supplier');
        });
    });

    // Utility functions
    function showAlert(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        document.getElementById('alertContainer').innerHTML = alertHtml;
        
        setTimeout(() => {
            const alert = document.querySelector('#alertContainer .alert');
            if (alert) {
                bootstrap.Alert.getInstance(alert).close();
            }
        }, 5000);
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        const table = document.getElementById('suppliersTable');
        const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            let show = true;
            const row = rows[i];
            const cells = row.getElementsByTagName('td');
            
            // Search filter
            if (searchTerm) {
                const supplierName = cells[0].textContent.toLowerCase();
                const contactPerson = cells[1].textContent.toLowerCase();
                const contactInfo = cells[2].textContent.toLowerCase();
                
                if (!supplierName.includes(searchTerm) && 
                    !contactPerson.includes(searchTerm) && 
                    !contactInfo.includes(searchTerm)) {
                    show = false;
                }
            }
            
            // Status filter
            if (statusFilter && show) {
                const statusCell = cells[7];
                const isActive = statusCell.textContent.trim().toLowerCase() === 'active';
                
                if ((statusFilter === 'active' && !isActive) || 
                    (statusFilter === 'inactive' && isActive)) {
                    show = false;
                }
            }
            
            row.style.display = show ? '' : 'none';
        }
    }

    function viewSupplier(supplierId) {
        window.location.href = `view_supplier.php?id=${supplierId}`;
    }

    function editSupplier(supplierId) {
        const supplier = suppliersData.find(s => s.supplier_id == supplierId);
        if (!supplier) return;
        
        // Populate edit form
        document.getElementById('edit_supplier_id').value = supplier.supplier_id;
        document.getElementById('edit_supplier_name').value = supplier.supplier_name;
        document.getElementById('edit_contact_person').value = supplier.contact_person || '';
        document.getElementById('edit_email').value = supplier.email || '';
        document.getElementById('edit_phone').value = supplier.phone || '';
        document.getElementById('edit_address').value = supplier.address || '';
        document.getElementById('edit_payment_terms').value = supplier.payment_terms || '';
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('editSupplierModal'));
        modal.show();
    }

    function deactivateSupplier(supplierId) {
        if (confirm('Are you sure you want to deactivate this supplier?')) {
            const formData = new FormData();
            formData.append('action', 'deactivate_supplier');
            formData.append('supplier_id', supplierId);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('success', data.message);
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    showAlert('error', data.message);
                }
            })
            .catch(error => {
                showAlert('error', 'An error occurred while deactivating supplier');
            });
        }
    }

    function activateSupplier(supplierId) {
        if (confirm('Are you sure you want to activate this supplier?')) {
            const formData = new FormData();
            formData.append('action', 'activate_supplier');
            formData.append('supplier_id', supplierId);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('success', data.message);
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    showAlert('error', data.message);
                }
            })
            .catch(error => {
                showAlert('error', 'An error occurred while activating supplier');
            });
        }
    }

    function refreshTable() {
        window.location.reload();
    }

    function exportSuppliers() {
        const table = document.getElementById('suppliersTable');
        const rows = table.querySelectorAll('tr');
        let csv = [];
        
        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const cols = row.querySelectorAll('td, th');
            let csvRow = [];
            
            for (let j = 0; j < cols.length - 1; j++) { // Exclude actions column
                csvRow.push('"' + cols[j].textContent.trim().replace(/"/g, '""') + '"');
            }
            csv.push(csvRow.join(','));
        }
        
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'suppliers_' + new Date().toISOString().split('T')[0] + '.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }

    // Real-time search
    document.getElementById('searchInput').addEventListener('input', filterTable);
    document.getElementById('statusFilter').addEventListener('change', filterTable);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>