<?php

namespace Database\Seeders;

use App\Models\BlogPost;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class BlogPostSeeder extends Seeder
{
    public function run(): void
    {
        // Find the super-admin as the author (created by UserSeeder)
        $author = User::where('email', 'admin@inventino.shop')->first();
        if (! $author) {
            $this->command->warn('No admin user found. Skipping blog post seeder.');
            return;
        }

        $posts = [
            // ── FEATURED ────────────────────────────────────────────────
            [
                'title'            => '10 Inventory Mistakes Nigerian SMEs Make (And How to Fix Them)',
                'category'         => 'business',
                'tags'             => ['inventory', 'sme', 'nigeria', 'stock management'],
                'published_at'     => Carbon::parse('2025-01-15'),
                'excerpt'          => 'Between stockouts, overstocking, and shrinkage, poor inventory management is costing Nigerian businesses millions every year. Here\'s how to identify and fix the most common pitfalls.',
                'meta_title'       => '10 Inventory Mistakes Nigerian SMEs Make & How to Fix Them',
                'meta_description' => 'Discover the top 10 inventory mistakes costing Nigerian small businesses money — from stockouts to poor reorder tracking — and learn how to fix each one with practical tips.',
                'content'          => <<<MD
Managing inventory is one of the most critical — and most mismanaged — aspects of running a small or medium-sized business in Nigeria.

Whether you sell electronics in Onitsha, run a supermarket in Abuja, or operate a fashion store on Lagos Island, these mistakes could be quietly eating into your margins.

## 1. Not Tracking Stock in Real Time

Many SMEs still rely on notebooks or Excel spreadsheets updated once a week. By the time you realise you've run out of a product, you've already lost sales.

**Fix:** Use a point-of-sale system like Inventino that automatically deducts stock with every sale, so your count is always current.

## 2. Ignoring Reorder Points

Waiting until a shelf is empty before ordering is a reactive — and costly — approach. It results in stockouts and dissatisfied customers.

**Fix:** Set a minimum reorder quantity for every product. When stock hits that level, your system should alert you — or even trigger a purchase order automatically.

## 3. Lumping All Products Under One Category

When every product is just "goods purchased," your reports are useless. You can't see which categories are driving profit.

**Fix:** Structure your products into clear categories (Electronics, Groceries, Clothing, etc.) so you can analyse performance by category.

## 4. Ignoring Expiry Dates

This is especially critical for food, cosmetics, and pharmaceuticals. Selling expired goods risks your customers' health and your business licence.

**Fix:** Track expiry dates for every perishable SKU. Set alerts for items approaching expiry so you can run promotions before they're wasted.

## 5. Over-Ordering "Safe Stock"

Trying to avoid stockouts by ordering excess inventory ties up capital and creates storage costs — especially during Nigeria's unstable FX environment when import purchases are involved.

**Fix:** Use historical sales data to forecast demand accurately. Inventino's reports show you average daily sales per product so you can order smarter.

## 6. Skipping Regular Stock Counts

Some businesses only do a physical stock count annually. Discrepancies caused by theft, breakage, or recording errors go undetected for months.

**Fix:** Schedule monthly mini stock counts — or spot-check your top 20 products weekly. Reconcile with your system records.

## 7. Not Tracking Units of Measure

Buying in cartons but selling in units without proper conversion tracking leads to inaccurate stock levels and incorrect COGS calculations.

**Fix:** Set up unit-of-measure conversions in your inventory system (e.g., 1 carton = 24 pieces).

## 8. Forgetting to Account for Returns

Returned items often get placed back on shelves without being re-entered into the system, causing a mismatch between physical and system stock.

**Fix:** Always process returns through your POS. Inventino's return flow automatically restores stock to the correct quantity.

## 9. Ignoring Supplier Lead Times

If your supplier takes 2 weeks to deliver but you only reorder when you're completely out of stock, you'll have 2 weeks of zero sales on that product.

**Fix:** Factor lead time into your reorder point calculation: Reorder Point = (Average Daily Sales × Lead Time) + Safety Stock.

## 10. Not Locking Down Access

Allowing all staff to adjust stock quantities or delete transactions is an open invitation to fraud and errors.

**Fix:** Use role-based access control. Cashiers should only record sales; only managers should be able to approve adjustments.

---

Getting inventory right doesn't require a huge investment — it requires consistency and the right tools. [Start your free Inventino trial](/register) today and stop leaving money on the shelf.
MD,
            ],

            // ── POS & SALES ─────────────────────────────────────────────
            [
                'title'            => 'How to Set Up Your POS for Market Day Success',
                'category'         => 'pos',
                'tags'             => ['pos', 'market day', 'sales', 'setup'],
                'published_at'     => Carbon::parse('2025-01-10'),
                'excerpt'          => 'Speed matters on market day. Here\'s how to configure Inventino\'s POS to handle high-volume sales without slowing down.',
                'meta_title'       => 'POS Setup Guide for Market Day | Inventino',
                'meta_description' => 'Learn how to configure Inventino\'s point-of-sale for high-traffic market days — fast checkout flows, offline mode, split payments, and more.',
                'content'          => <<<MD
Market days in Nigeria can be a goldmine — but only if your POS keeps up with the foot traffic. Nothing kills momentum faster than a slow, crashing, or confusing checkout system.

Here's how to set Inventino up for a smooth, lightning-fast market day.

## 1. Pre-load Your Product Catalogue

Don't waste time searching for products mid-transaction. Before the market day:

- Add all items you plan to sell with accurate prices
- Set up barcodes or short SKU codes for your top sellers
- Use descriptive product names that cashiers can recognise instantly

## 2. Configure Quick-Sale Items

Pin your top 10 most frequently sold items to the POS quick-access grid. This eliminates search entirely for common products.

## 3. Set Up Multiple Payment Methods

Nigerian customers pay in all sorts of ways — cash, POS card terminals, bank transfers, and even USSD codes. Configure all accepted payment methods in Inventino in advance so cashiers can select them instantly.

Inventino supports:
- Cash
- Bank transfer
- POS card terminal
- Mobile money
- Split payments (part cash, part transfer)

## 4. Enable Offline Mode

Internet connectivity in open-air markets can be unreliable. Ensure Inventino's offline mode is enabled — it allows you to record sales locally and sync when connectivity is restored.

## 5. Pre-print Price Tags

Reduce price queries by printing or writing price tags for all items. Customers who know the price before reaching the checkout move faster.

## 6. Brief Your Cashiers

Even with perfect software, untrained staff cause slowdowns. Before the market opens:

- Run a 10-minute walkthrough of the checkout flow
- Confirm they know how to handle refunds and "no sale" drawer opens
- Assign one person to handle only cash, another to handle transfers

## 7. Check Your Receipt Printer

Nothing frustrates a customer more than waiting for a receipt that won't print. Test your printer or configure WhatsApp/email digital receipts as a backup.

---

A well-prepared POS is the difference between serving 300 customers and serving 150 in the same time window. [Sign up for Inventino free](/register) and get market-day ready today.
MD,
            ],

            // ── INVENTORY ───────────────────────────────────────────────
            [
                'title'            => 'Understanding FIFO vs LIFO for Nigerian Retailers',
                'category'         => 'inventory',
                'tags'             => ['fifo', 'lifo', 'costing', 'accounting', 'retail'],
                'published_at'     => Carbon::parse('2025-01-05'),
                'excerpt'          => 'Your costing method affects profitability calculations. We break down which approach makes sense for food, fashion, and electronics retailers in Nigeria.',
                'meta_title'       => 'FIFO vs LIFO for Nigerian Retailers: Which to Choose?',
                'meta_description' => 'A clear guide to FIFO and LIFO inventory costing methods for Nigerian retailers — including real examples in food, fashion, and electronics and how each affects your profit.',
                'content'          => <<<MD
The way you value your inventory directly affects your reported profit, your tax liability, and your pricing decisions. Two of the most common methods are **FIFO** (First In, First Out) and **LIFO** (Last In, First Out).

This guide explains both methods in plain English, using examples relevant to Nigerian business contexts.

## What is FIFO?

FIFO assumes the *first items purchased* are the *first items sold*. So when you sell a product, you deduct the cost of your oldest units first.

**Example:** A supermarket in Abuja buys 100 bags of rice in January at ₦35,000/bag. In March, prices rise and they buy another 100 at ₦42,000/bag. Under FIFO, the first bags sold are costed at ₦35,000.

### Pros of FIFO
- Matches physical reality (older stock usually sold first)
- Gives higher closing inventory value (great for attracting investors or loans)
- Legally required for perishables in many countries

### Cons of FIFO
- Reports higher profit during inflation → higher tax
- May not accurately reflect current replacement cost

---

## What is LIFO?

LIFO assumes the *last items purchased* are the *first ones sold*. Using the same example, rice sold is costed at ₦42,000/bag (the most recent purchase price).

### Pros of LIFO
- Closer to current replacement cost
- Reports lower profit during inflation → lower tax
- Useful for non-perishables (e.g., electronics, hardware)

### Cons of LIFO
- Not permitted under IFRS (the standard used in Nigeria)
- Closes inventory valued at very old — sometimes unrealistically low — prices
- Can mislead lenders reviewing your balance sheet

---

## Which Should You Use?

| Business type        | Recommended method |
|----------------------|--------------------|
| Food & beverages     | FIFO (perishables must go first) |
| Fashion & clothing   | FIFO (trends change, older stock loses value) |
| Electronics          | FIFO (tech depreciates fast) |
| Hardware/construction| Weighted average cost is often more practical |
| Pharmaceuticals      | FIFO (expiry compliance) |

For most Nigerian retailers, **FIFO** or a **Weighted Average Cost (WAC)** method is most practical and compliant with Nigerian GAAP and IFRS standards.

---

Make sure your inventory system records purchase costs accurately. Inventino tracks cost per unit on every purchase so your gross margin reports are always reliable.
MD,
            ],

            // ── PRODUCT UPDATE ───────────────────────────────────────────
            [
                'title'            => 'New Feature: Multi-Payment Split at Checkout',
                'category'         => 'updates',
                'tags'             => ['feature', 'payments', 'pos', 'split payment'],
                'published_at'     => Carbon::parse('2024-12-28'),
                'excerpt'          => 'Customers can now pay part cash, part transfer in a single transaction. Here\'s how to enable and use split payments in your POS.',
                'meta_title'       => 'Inventino Feature Update: Split Payments at POS Checkout',
                'meta_description' => 'Inventino now supports multi-payment split checkout — accept cash + bank transfer in a single transaction. Learn how to enable it and record split payments correctly.',
                'content'          => <<<MD
We're excited to announce one of our most-requested features: **split payment support at checkout**.

As any Nigerian retailer knows, customers often want to pay part of a bill in cash and cover the rest with a bank transfer — especially on larger purchases. Until now, this required awkward workarounds. Not anymore.

## What's New

Starting today, cashiers can:

1. Enter the full sale amount as normal
2. Select **"Split Payment"** at checkout
3. Enter the cash amount received
4. Enter the transfer amount (or vice versa)
5. Complete the sale — the system automatically reconciles both legs

### Multiple payment methods supported in a split:
- Cash + Bank transfer
- Cash + POS card terminal
- Bank transfer + Loyalty wallet credit
- Any combination of your configured payment methods

## How to Enable Split Payments

Split payments are available to all plans. No configuration needed — just select "Split" on the payment screen.

## Reporting

Every split payment is fully auditable. In your daily sales report:
- The total transaction value is recorded against the sale
- Each payment leg is tracked separately under its method
- Cash drawer totals remain accurate

## Why This Matters

Split payments reduce friction at checkout, improve customer satisfaction, and eliminate cashier errors that come from trying to manage multiple receipts for one purchase.

---

As always, update to the latest version of Inventino to access this feature. Questions? Reach out to our support team via the in-app chat.
MD,
            ],

            // ── BUSINESS TIPS ────────────────────────────────────────────
            [
                'title'            => 'How Loyalty Programmes Drive Repeat Sales in Nigerian Retail',
                'category'         => 'business',
                'tags'             => ['loyalty', 'customer retention', 'repeat sales', 'marketing'],
                'published_at'     => Carbon::parse('2024-12-20'),
                'excerpt'          => 'Data shows loyal customers spend 67% more than new ones. Here\'s how to build a points system that actually works for your Nigerian retail business.',
                'meta_title'       => 'Loyalty Programmes for Nigerian Retailers: A Practical Guide',
                'meta_description' => 'Loyal customers spend 67% more. Discover how to design and launch a loyalty points programme for your Nigerian retail store using Inventino.',
                'content'          => <<<MD
Customer acquisition is expensive. Customer retention is not. Yet most Nigerian retailers invest almost nothing in keeping the customers they already have.

Research consistently shows that loyal customers spend **67% more** than new customers, refer others, and forgive occasional service lapses. Here's how to design a programme that works.

## Start Simple: A Points System

The simplest and most effective loyalty structure for retail is a points-for-purchase system:

- Customer earns 1 point for every ₦100 spent
- 100 points = ₦100 discount on future purchase
- No tiers, no complexity

This is the model Inventino supports natively. Every sale automatically credits the customer's point balance.

## Set a Minimum Redemption Threshold

Require a minimum of 500 or 1,000 points before redemption. This:
- Encourages repeat visits before a reward is available
- Reduces cashier friction from micro-redemptions
- Creates a sense of accumulation and reward

## Communicate the Programme Clearly

Your programme only works if customers know about it. At the point of sale:

1. Tell every customer their current points balance on the receipt
2. Display a "Points balance" prompt at checkout
3. Use WhatsApp or SMS to remind dormant customers of their balance

Inventino automatically prints the loyalty balance on every receipt — no extra setup required.

## Run Bonus-Point Campaigns

On slow days or to clear old stock, offer double points. Example: "Every Wednesday this month, earn 2x points on all purchases." This drives midweek foot traffic without discounting your margins.

## Don't Over-Discount

Loyalty rewards should feel valuable to the customer but sustainable for your business. A 1% reward rate (₦1 back for every ₦100 spent) is typically the sweet spot — generous enough to motivate, modest enough to protect margins.

## Track, Measure, Adjust

Review your loyalty metrics monthly:
- **Redemption rate** — are points actually being used?
- **Repeat purchase rate** — are loyalty members returning more often?
- **Average transaction value** — do members spend more per visit?

Inventino's customer reports show all of this at a glance.

---

A well-run loyalty programme turns one-time buyers into lifetime customers. [Get started with Inventino's built-in loyalty tools →](/register)
MD,
            ],

            // ── INVENTORY ───────────────────────────────────────────────
            [
                'title'            => 'Year-End Stock Count: A Checklist for Small Businesses',
                'category'         => 'inventory',
                'tags'             => ['stock count', 'year end', 'audit', 'checklist'],
                'published_at'     => Carbon::parse('2024-12-15'),
                'excerpt'          => 'End-of-year stocktaking doesn\'t have to be painful. Use this checklist to reconcile your physical count with Inventino\'s records in under a day.',
                'meta_title'       => 'Year-End Stock Count Checklist for Small Businesses',
                'meta_description' => 'A practical year-end stocktaking checklist for Nigerian small businesses — covering preparation, counting, reconciliation, and posting adjustments in Inventino.',
                'content'          => <<<MD
The year-end stock count is one of those tasks every business owner dreads — but it doesn't have to be a multi-day nightmare. With the right preparation and a clear process, a small-to-medium business can complete a full stock count in a single day.

Here's a proven checklist.

## One Week Before Count Day

- [ ] **Freeze purchases.** Stop receiving new stock at least 3 days before the count date so incoming goods don't blur your picture.
- [ ] **Process all outstanding sales.** Every sale up to the count date should be entered into Inventino before you count.
- [ ] **Print your stock report.** Generate the full stock list from Inventino. This is your expected ("book") count.
- [ ] **Organise the stockroom.** Group products by category, ensure items are clearly labelled. Unknown or unlabelled items will slow you down.
- [ ] **Assign counting teams.** Each team of 2 handles a section — one counts, one records.

## On Count Day

- [ ] **Count before opening.** Ideally do this before the business opens or after it closes to avoid movement during the count.
- [ ] **Use printed count sheets.** Give each team a pre-printed sheet with product names and spaces to record physical count.
- [ ] **Count twice.** Each section should be counted by two independent people. Discrepancies trigger a third count.
- [ ] **Note condition.** Flag any damaged, expired, or unsaleable items separately.

## After the Count

- [ ] **Enter physical counts into Inventino's stock adjustment screen.**
- [ ] **Review variances.** The system will highlight items where physical and book counts differ.
- [ ] **Investigate large variances** before posting. Common causes: theft, breakage, double-entry, unprocessed returns.
- [ ] **Post adjustments.** Once satisfied, post the inventory adjustment. This updates your stock levels and records a gain or loss.
- [ ] **Write off damaged/expired goods.** Create a separate adjustment entry for unsaleable items.
- [ ] **File your count sheets.** Keep physical records for audit purposes for at least 5 years.

## Common Causes of Stock Discrepancies

| Cause | Prevention |
|----------------------------------------|--------------------------------------|
| Unrecorded returns from customers | Always process returns in the system |
| Staff consumption / breakage           | Use internal transfer records        |
| Theft (internal or external)           | Restrict POS access by role          |
| Supplier short-shipping                | Count deliveries on arrival          |
| System error / duplicate entries       | Audit purchase and sale records      |

---

A clean year-end stock count gives you accurate closing inventory for your accounts, a clear view of shrinkage, and a solid starting point for the new year. Inventino's inventory adjustment module makes the posting process fast and fully auditable.
MD,
            ],

            // ── PRODUCT UPDATE ───────────────────────────────────────────
            [
                'title'            => 'Inventino v2.1: Branch Dashboard, Bulk Import & More',
                'category'         => 'updates',
                'tags'             => ['release', 'branches', 'bulk import', 'v2.1'],
                'published_at'     => Carbon::parse('2024-12-08'),
                'excerpt'          => 'Our latest release brings a per-branch dashboard overview, CSV bulk product import, and improved expense categorization. See what\'s new.',
                'meta_title'       => 'Inventino v2.1 Release Notes: Branch Dashboard & Bulk Import',
                'meta_description' => 'Inventino v2.1 is live — new per-branch sales dashboard, CSV bulk product import, expense category management, and several bug fixes. Full release notes inside.',
                'content'          => <<<MD
We've been heads-down building for the past two months, and today we're shipping Inventino v2.1. Here's everything that's new.

## Branch Dashboard Overview

Multi-location businesses can now view a consolidated performance summary across all branches on a single screen:

- Total sales per branch (today, this week, this month)
- Top-performing staff per branch
- Low-stock alerts per branch
- Expense breakdown per branch

This is especially useful for owners who aren't always on-site — you get an at-a-glance view without logging into each branch account separately.

## CSV Bulk Product Import

Setting up a new business or migrating from another system? You can now import your entire product catalogue via CSV upload.

**The template includes:**
- Product name
- SKU/barcode
- Category
- Cost price
- Selling price
- Initial stock quantity
- Unit of measure
- Expiry date (optional)

Download the template from Settings → Products → Import.

## Improved Expense Categorisation

Expense categories now support colour coding and per-branch assignment, making it significantly easier to run branch-by-branch expense reports. Pre-loaded default categories: Rent, Salary, Utilities, Logistics, Marketing, Sundry.

## Other Improvements

- **Receipt customisation:** Add your social media handles, WhatsApp number, or a custom footer message to all printed receipts.
- **Keyboard shortcuts on POS:** Power users can now add products and complete sales without touching the mouse.
- **Improved search:** Product search on the POS now searches across SKU, name, and barcode simultaneously.
- **Bug fixes:** Fixed a rare issue where split-payment totals were rounded incorrectly on receipts.

---

All updates are live immediately for all users — no action required. As always, reach out via in-app chat if you encounter any issues. Thank you for building with Inventino.
MD,
            ],
        ];

        foreach ($posts as $data) {
            $data['author_id'] = $author->id;
            $data['status']    = 'published';
            $data['slug']      = Str::slug($data['title']) . '-' . Str::lower(Str::random(5));

            BlogPost::create($data);
        }

        $this->command->info('✔  Created ' . count($posts) . ' blog posts.');
    }
}
