<?php
// admin/accounts/vendors.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Handle Add Vendor
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_vendor'])) {
    $name = sanitize($_POST['name'] ?? '');
    $company = sanitize($_POST['company'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $address = sanitize($_POST['address'] ?? '');
    $city = sanitize($_POST['city'] ?? '');
    $tax_id = sanitize($_POST['tax_id'] ?? '');
    $opening_balance = floatval($_POST['opening_balance'] ?? 0);
    $payment_terms = sanitize($_POST['payment_terms'] ?? 'net30');
    $status = isset($_POST['status']) ? 1 : 0;
    
    // Validate
    if (empty($name)) {
        $error_msg = 'Vendor name is required';
    } else {
        // Generate vendor code
        $vendor_code = 'VND-' . date('Ymd') . '-' . rand(1000, 9999);
        
        try {
            $stmt = $pdo->prepare("INSERT INTO vendors 
                (vendor_code, name, company, email, phone, address, city, tax_id, opening_balance, payment_terms, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            
            $stmt->execute([
                $vendor_code, 
                $name, 
                $company, 
                $email, 
                $phone, 
                $address, 
                $city, 
                $tax_id, 
                $opening_balance, 
                $payment_terms, 
                $status
            ]);
            
            $_SESSION['success_msg'] = 'Vendor "' . $name . '" added successfully!';
            header('Location: vendors.php');
            exit;
            
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Delete via AJAX
if (isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);
    try {
        $stmt = $pdo->prepare("DELETE FROM vendors WHERE id = ?");
        $stmt->execute([$delete_id]);
        echo json_encode(['success' => true, 'message' => 'Vendor deleted']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// Handle Edit Vendor via AJAX
if (isset($_POST['edit_vendor'])) {
    $id = intval($_POST['vendor_id'] ?? 0);
    $name = sanitize($_POST['name'] ?? '');
    $company = sanitize($_POST['company'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $address = sanitize($_POST['address'] ?? '');
    $city = sanitize($_POST['city'] ?? '');
    $tax_id = sanitize($_POST['tax_id'] ?? '');
    $opening_balance = floatval($_POST['opening_balance'] ?? 0);
    $payment_terms = sanitize($_POST['payment_terms'] ?? 'net30');
    $status = isset($_POST['status']) ? 1 : 0;
    
    if ($id > 0 && !empty($name)) {
        try {
            $stmt = $pdo->prepare("UPDATE vendors SET 
                name = ?, company = ?, email = ?, phone = ?, address = ?, 
                city = ?, tax_id = ?, opening_balance = ?, payment_terms = ?, status = ? 
                WHERE id = ?");
            $stmt->execute([
                $name, $company, $email, $phone, $address, 
                $city, $tax_id, $opening_balance, $payment_terms, $status, 
                $id
            ]);
            $_SESSION['success_msg'] = 'Vendor updated successfully!';
        } catch (Exception $e) {
            $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
        }
    }
    header('Location: vendors.php');
    exit;
}

// Get vendors
$stmt = $pdo->query("SELECT v.*, 
                     (SELECT COUNT(*) FROM purchase_orders WHERE vendor_id = v.id) as po_count,
                     (SELECT COALESCE(SUM(due_amount), 0) FROM purchase_orders WHERE vendor_id = v.id AND status NOT IN ('paid', 'cancelled')) as total_due
                     FROM vendors v 
                     ORDER BY v.created_at DESC");
$vendors = $stmt->fetchAll();

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include '../header.php';
?>

<style>
.vendor-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.vendor-card .card-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.account-nav a {
    padding: 8px 20px;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
    transition: all 0.3s ease;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.active {
    background: #86efac;
    color: #166534;
}

.status-badge.inactive {
    background: #fca5a5;
    color: #991b1b;
}

.alert-container {
    margin-bottom: 20px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-building me-2"></i> Vendors</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#vendorModal">
            <i class="fa-solid fa-plus"></i> Add Vendor
        </button>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php" class="active"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Vendor List -->
    <div class="vendor-card">
        <h5 class="card-title">All Vendors (<?php echo count($vendors); ?>)</h5>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Name</th>
                        <th>Company</th>
                        <th>Phone</th>
                        <th>PO Count</th>
                        <th>Total Due</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="vendorsTableBody">
                    <?php if (empty($vendors)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fa-regular fa-building fa-2x text-muted d-block mb-2"></i>
                            No vendors found. Click "Add Vendor" to create one.
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($vendors as $vendor): ?>
                    <tr id="vendorRow_<?php echo $vendor['id']; ?>">
                        <td><code><?php echo $vendor['vendor_code']; ?></code></td>
                        <td><strong><?php echo htmlspecialchars($vendor['name']); ?></strong></td>
                        <td><?php echo htmlspecialchars($vendor['company'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($vendor['phone'] ?? '-'); ?></td>
                        <td><span class="badge bg-info"><?php echo $vendor['po_count']; ?></span></td>
                        <td class="text-danger"><?php echo number_format($vendor['total_due']); ?> TK</td>
                        <td>
                            <span class="status-badge <?php echo $vendor['status'] ? 'active' : 'inactive'; ?>">
                                <?php echo $vendor['status'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <button onclick="editVendor(<?php echo $vendor['id']; ?>)" class="btn btn-sm btn-warning">
                                <i class="fa-solid fa-edit"></i>
                            </button>
                            <button onclick="deleteVendor(<?php echo $vendor['id']; ?>, '<?php echo addslashes($vendor['name']); ?>')" class="btn btn-sm btn-danger">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Vendor Modal -->
<div class="modal fade" id="vendorModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-plus-circle me-2"></i> Add Vendor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="vendorForm">
                <input type="hidden" name="add_vendor" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Vendor Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" required placeholder="Enter vendor name">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Company</label>
                                <input type="text" name="company" class="form-control" placeholder="Company name">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" class="form-control" placeholder="vendor@example.com">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" class="form-control" placeholder="+880 17XXXXXXXX">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" class="form-control" rows="2" placeholder="Full address"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">City</label>
                                <input type="text" name="city" class="form-control" placeholder="City name">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Tax ID / VAT</label>
                                <input type="text" name="tax_id" class="form-control" placeholder="Tax identification number">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Opening Balance</label>
                                <input type="number" name="opening_balance" class="form-control" step="0.01" value="0">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Terms</label>
                                <select name="payment_terms" class="form-control">
                                    <option value="net15">Net 15</option>
                                    <option value="net30" selected>Net 30</option>
                                    <option value="net45">Net 45</option>
                                    <option value="net60">Net 60</option>
                                    <option value="cod">Cash on Delivery</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" name="status" class="form-check-input" id="vendorStatus" checked>
                                    <label class="form-check-label" for="vendorStatus">Active</label>
                                </div>
                            </div>
                        </div>
                    </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">
                        <i class="fa-solid fa-save"></i> Save Vendor
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Vendor Modal -->
<div class="modal fade" id="editVendorModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-edit me-2"></i> Edit Vendor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editVendorForm">
                <input type="hidden" name="edit_vendor" value="1">
                <input type="hidden" name="vendor_id" id="edit_vendor_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Vendor Name <span class="text-danger">*</span></label>
                                <input type="text" name="name" id="edit_name" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Company</label>
                                <input type="text" name="company" id="edit_company" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <input type="email" name="email" id="edit_email" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" name="phone" id="edit_phone" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" id="edit_address" class="form-control" rows="2"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">City</label>
                                <input type="text" name="city" id="edit_city" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Tax ID / VAT</label>
                                <input type="text" name="tax_id" id="edit_tax_id" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Opening Balance</label>
                                <input type="number" name="opening_balance" id="edit_opening_balance" class="form-control" step="0.01">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Terms</label>
                                <select name="payment_terms" id="edit_payment_terms" class="form-control">
                                    <option value="net15">Net 15</option>
                                    <option value="net30">Net 30</option>
                                    <option value="net45">Net 45</option>
                                    <option value="net60">Net 60</option>
                                    <option value="cod">Cash on Delivery</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input type="checkbox" name="status" id="edit_status" class="form-check-input">
                                    <label class="form-check-label" for="edit_status">Active</label>
                                </div>
                            </div>
                        </div>
                    </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">
                        <i class="fa-solid fa-save"></i> Update Vendor
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ========================================
// EDIT VENDOR
// ========================================
function editVendor(id) {
    // Fetch vendor data
    fetch('get-vendor.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data) {
                document.getElementById('edit_vendor_id').value = data.id;
                document.getElementById('edit_name').value = data.name;
                document.getElementById('edit_company').value = data.company || '';
                document.getElementById('edit_email').value = data.email || '';
                document.getElementById('edit_phone').value = data.phone || '';
                document.getElementById('edit_address').value = data.address || '';
                document.getElementById('edit_city').value = data.city || '';
                document.getElementById('edit_tax_id').value = data.tax_id || '';
                document.getElementById('edit_opening_balance').value = data.opening_balance || 0;
                document.getElementById('edit_payment_terms').value = data.payment_terms || 'net30';
                document.getElementById('edit_status').checked = data.status == 1;
                
                var modal = new bootstrap.Modal(document.getElementById('editVendorModal'));
                modal.show();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', 'Failed to load vendor data');
        });
}

// ========================================
// DELETE VENDOR
// ========================================
function deleteVendor(id, name) {
    if (!confirm('Are you sure you want to delete vendor "' + name + '"?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('vendors.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('vendorRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    // Update count
                    var count = document.querySelectorAll('#vendorsTableBody tr').length - 1;
                    if (count === 0) {
                        document.getElementById('vendorsTableBody').innerHTML = `
                            <tr><td colspan="8" class="text-center py-4">
                                <i class="fa-regular fa-building fa-2x text-muted d-block mb-2"></i>
                                No vendors found. Click "Add Vendor" to create one.
                            </td></tr>
                        `;
                    }
                }, 500);
            }
            showAlert('success', 'Vendor deleted successfully!');
        } else {
            showAlert('danger', data.message || 'Failed to delete vendor');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong');
    });
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
});
</script>

<?php include '../footer.php'; ?>