<?php
include '../config.php';
include '../auth.php';
checkRole('manager');

// Handle supplier operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_supplier'])) {
        $name = $_POST['name'];
        $contact_person = $_POST['contact_person'];
        $phone = $_POST['phone'];
        $email = $_POST['email'];
        $address = $_POST['address'];
        
        $stmt = $conn->prepare("INSERT INTO suppliers (name, contact_person, phone, email, address) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $name, $contact_person, $phone, $email, $address);
        
        if ($stmt->execute()) {
            $message = "Supplier added successfully!";
        } else {
            $error = "Error adding supplier: " . $stmt->error;
        }
    }
    
    if (isset($_POST['create_po'])) {
        $supplier_id = $_POST['supplier_id'];
        $order_date = $_POST['order_date'];
        $expected_date = $_POST['expected_date'];
        $notes = $_POST['notes'];
        
        $stmt = $conn->prepare("INSERT INTO purchase_orders (supplier_id, order_date, expected_date, notes, created_by) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("isssi", $supplier_id, $order_date, $expected_date, $notes, $_SESSION['user_id']);
        
        if ($stmt->execute()) {
            $po_id = $conn->insert_id;
            $message = "Purchase Order #$po_id created successfully!";
        } else {
            $error = "Error creating purchase order: " . $stmt->error;
        }
    }
}

// Get suppliers
$suppliers = $conn->query("SELECT * FROM suppliers ORDER BY name")->fetch_all(MYSQLI_ASSOC);

// Get recent purchase orders
$recent_pos = $conn->query("
    SELECT po.*, s.name as supplier_name, u.full_name as created_by_name 
    FROM purchase_orders po 
    JOIN suppliers s ON po.supplier_id = s.id 
    JOIN users u ON po.created_by = u.id 
    ORDER BY po.created_at DESC 
    LIMIT 10
")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Supplier Management - Dilrukshi Tex</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .container { margin-top: 40px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="fw-bold"><i class="fas fa-truck"></i> Supplier Management</h1>
            <div>
                <a href="../inventory/" class="btn btn-warning me-2"><i class="fas fa-warehouse"></i> Inventory</a>
                <a href="../" class="btn btn-secondary"><i class="fas fa-home"></i> Dashboard</a>
            </div>
        </div>

        <?php if (isset($message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?= $error ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="row">
            <!-- Add Supplier -->
            <div class="col-lg-6 mb-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <i class="fas fa-plus"></i> Add New Supplier
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="add_supplier" value="1">
                            <div class="mb-3">
                                <label class="form-label">Company Name *</label>
                                <input type="text" name="name" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Contact Person</label>
                                <input type="text" name="contact_person" class="form-control">
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Phone</label>
                                    <input type="tel" name="phone" class="form-control">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Email</label>
                                    <input type="email" name="email" class="form-control">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea name="address" class="form-control" rows="3"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-save"></i> Add Supplier
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Create Purchase Order -->
            <div class="col-lg-6 mb-4">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <i class="fas fa-file-invoice"></i> Create Purchase Order
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="create_po" value="1">
                            <div class="mb-3">
                                <label class="form-label">Supplier *</label>
                                <select name="supplier_id" class="form-select" required>
                                    <option value="">Select Supplier...</option>
                                    <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?= $supplier['id'] ?>">
                                        <?= htmlspecialchars($supplier['name']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Order Date *</label>
                                    <input type="date" name="order_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Expected Date</label>
                                    <input type="date" name="expected_date" class="form-control">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" class="form-control" rows="3"></textarea>
                            </div>
                            <button type="submit" class="btn btn-success w-100">
                                <i class="fas fa-file-plus"></i> Create Purchase Order
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Suppliers List -->
        <div class="card mb-4">
            <div class="card-header bg-info text-white">
                <i class="fas fa-building"></i> Suppliers Directory
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>Company</th>
                                <th>Contact Person</th>
                                <th>Phone</th>
                                <th>Email</th>
                                <th>Address</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($suppliers as $supplier): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($supplier['name']) ?></strong></td>
                                <td><?= htmlspecialchars($supplier['contact_person'] ?? '') ?></td>
                                <td><?= htmlspecialchars($supplier['phone'] ?? '') ?></td>
                                <td><?= htmlspecialchars($supplier['email'] ?? '') ?></td>
                                <td><small><?= htmlspecialchars($supplier['address'] ?? '') ?></small></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-success" 
                                            onclick="createPO(<?= $supplier['id'] ?>, '<?= htmlspecialchars($supplier['name']) ?>')">
                                        <i class="fas fa-file-plus"></i> New PO
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Recent Purchase Orders -->
        <div class="card">
            <div class="card-header bg-warning text-dark">
                <i class="fas fa-clipboard-list"></i> Recent Purchase Orders
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped mb-0">
                        <thead class="table-dark">
                            <tr>
                                <th>PO #</th>
                                <th>Supplier</th>
                                <th>Order Date</th>
                                <th>Expected Date</th>
                                <th>Status</th>
                                <th>Created By</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_pos as $po): ?>
                            <tr>
                                <td><strong>#<?= $po['id'] ?></strong></td>
                                <td><?= htmlspecialchars($po['supplier_name']) ?></td>
                                <td><?= date('M d, Y', strtotime($po['order_date'])) ?></td>
                                <td><?= $po['expected_date'] ? date('M d, Y', strtotime($po['expected_date'])) : 'N/A' ?></td>
                                <td>
                                    <span class="badge bg-<?= $po['status'] === 'pending' ? 'warning' : ($po['status'] === 'received' ? 'success' : 'danger') ?>">
                                        <?= ucfirst($po['status']) ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($po['created_by_name']) ?></td>
                                <td>
                                    <a href="view_po.php?id=<?= $po['id'] ?>" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function createPO(supplierId, supplierName) {
            document.querySelector('select[name="supplier_id"]').value = supplierId;
            document.querySelector('select[name="supplier_id"]').scrollIntoView({ behavior: 'smooth' });
        }
    </script>
</body>
</html>
