<?php
/**
 * Admin Suppliers Page
 * Manage suppliers
 */

$pageTitle = 'Furnizori';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';

$db = Database::getInstance();

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_supplier':
                $name = $_POST['name'] ?? '';
                $contactPerson = $_POST['contact_person'] ?? '';
                $email = $_POST['email'] ?? '';
                $phone = $_POST['phone'] ?? '';
                $address = $_POST['address'] ?? '';
                
                if ($name) {
                    $db->execute(
                        "INSERT INTO suppliers (name, contact_person, email, phone, address, created_at)
                         VALUES (?, ?, ?, ?, ?, NOW())",
                        [$name, $contactPerson, $email, $phone, $address]
                    );
                    $message = 'Furnizorul a fost adăugat cu succes!';
                } else {
                    $error = 'Numele este obligatoriu!';
                }
                break;
            case 'update_supplier':
                $supplierId = intval($_POST['supplier_id'] ?? 0);
                $name = $_POST['name'] ?? '';
                $contactPerson = $_POST['contact_person'] ?? '';
                $email = $_POST['email'] ?? '';
                $phone = $_POST['phone'] ?? '';
                $address = $_POST['address'] ?? '';
                
                if ($supplierId && $name) {
                    $db->execute(
                        "UPDATE suppliers SET name = ?, contact_person = ?, email = ?, phone = ?, address = ?, updated_at = NOW() WHERE id = ?",
                        [$name, $contactPerson, $email, $phone, $address, $supplierId]
                    );
                    $message = 'Furnizorul a fost actualizat cu succes!';
                }
                break;
            case 'delete_supplier':
                $supplierId = intval($_POST['supplier_id'] ?? 0);
                if ($supplierId) {
                    // Check if supplier has products
                    $productCount = $db->fetchOne("SELECT COUNT(*) as count FROM products WHERE supplier_id = ?", [$supplierId])['count'] ?? 0;
                    if ($productCount > 0) {
                        $error = 'Nu poți șterge acest furnizor deoarece are ' . $productCount . ' produse asociate!';
                    } else {
                        $db->execute("DELETE FROM suppliers WHERE id = ?", [$supplierId]);
                        $message = 'Furnizorul a fost șters cu succes!';
                    }
                }
                break;
        }
    }
}

// Get all suppliers
$suppliers = $db->fetchAll(
    "SELECT s.*, COUNT(p.id) as product_count
     FROM suppliers s
     LEFT JOIN products p ON s.id = p.supplier_id
     GROUP BY s.id
     ORDER BY s.created_at DESC"
);
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-header">
        <div class="row flex-between-center">
          <div class="col-auto">
            <h5 class="mb-0">Furnizori</h5>
          </div>
          <div class="col-auto">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addSupplierModal">
              <span class="fas fa-plus me-1"></span>Adaugă furnizor
            </button>
          </div>
        </div>
      </div>
      <div class="card-body">
        <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($message); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($error); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="bg-body-tertiary">
              <tr>
                <th>Nume</th>
                <th>Persoană de contact</th>
                <th>Email</th>
                <th>Telefon</th>
                <th>Produse</th>
                <th>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($suppliers)): ?>
              <tr>
                <td colspan="6" class="text-center py-4">Nu există furnizori.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($suppliers as $supplier): ?>
              <tr>
                <td><?php echo htmlspecialchars($supplier['name']); ?></td>
                <td><?php echo htmlspecialchars($supplier['contact_person'] ?? 'N/A'); ?></td>
                <td><?php echo htmlspecialchars($supplier['email'] ?? 'N/A'); ?></td>
                <td><?php echo htmlspecialchars($supplier['phone'] ?? 'N/A'); ?></td>
                <td><?php echo number_format($supplier['product_count'] ?? 0); ?></td>
                <td>
                  <button class="btn btn-sm btn-falcon-default" data-bs-toggle="modal" data-bs-target="#editSupplierModal<?php echo $supplier['id']; ?>">
                    <span class="fas fa-edit"></span>
                  </button>
                  <form method="POST" class="d-inline" onsubmit="return confirm('Ești sigur că vrei să ștergi acest furnizor?');">
                    <input type="hidden" name="action" value="delete_supplier">
                    <input type="hidden" name="supplier_id" value="<?php echo $supplier['id']; ?>">
                    <button type="submit" class="btn btn-sm btn-falcon-default text-danger">
                      <span class="fas fa-trash"></span>
                    </button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Supplier Modal -->
<div class="modal fade" id="addSupplierModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Adaugă furnizor</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="add_supplier">
          <div class="mb-3">
            <label class="form-label">Nume furnizor <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="name" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Persoană de contact</label>
            <input type="text" class="form-control" name="contact_person">
          </div>
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input type="email" class="form-control" name="email">
          </div>
          <div class="mb-3">
            <label class="form-label">Telefon</label>
            <input type="text" class="form-control" name="phone">
          </div>
          <div class="mb-3">
            <label class="form-label">Adresă</label>
            <textarea class="form-control" name="address" rows="3"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Adaugă</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Supplier Modals -->
<?php foreach ($suppliers as $supplier): ?>
<div class="modal fade" id="editSupplierModal<?php echo $supplier['id']; ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editează furnizor</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="update_supplier">
          <input type="hidden" name="supplier_id" value="<?php echo $supplier['id']; ?>">
          <div class="mb-3">
            <label class="form-label">Nume furnizor <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($supplier['name']); ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Persoană de contact</label>
            <input type="text" class="form-control" name="contact_person" value="<?php echo htmlspecialchars($supplier['contact_person'] ?? ''); ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($supplier['email'] ?? ''); ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Telefon</label>
            <input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($supplier['phone'] ?? ''); ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Adresă</label>
            <textarea class="form-control" name="address" rows="3"><?php echo htmlspecialchars($supplier['address'] ?? ''); ?></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Salvează</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endforeach; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

