# Store Management System - Implementation Guide

## Overview
The Store Management system allows your client to manage multiple stores (locations) through a single e-commerce platform. Each store can be assigned products and orders independently.

## Database Structure
- **stores** table: Stores master data (id, name, code, address, phone, timestamps)
- **products.store_id**: Foreign key to stores (nullable, for multi-store support)
- **orders.store_id**: Foreign key to stores (nullable, for multi-store support)
- **carts.store_id**: Foreign key to stores (nullable, for multi-store support)

## Admin CRUD Routes
All routes are located at `/admin/stores`:

```
GET  /admin/stores                  - List all stores (StoreController@index)
GET  /admin/stores/create           - Create new store form (StoreController@create)
POST /admin/stores                  - Store new store (StoreController@store)
GET  /admin/stores/{id}             - Show store details (StoreController@show)
GET  /admin/stores/{id}/edit        - Edit store form (StoreController@edit)
PUT  /admin/stores/{id}             - Update store (StoreController@update)
GET  /admin/stores/destroy/{id}     - Delete store (StoreController@destroy)
POST /admin/bulk-store-delete       - Bulk delete stores (StoreController@bulk_store_delete)
```

## Usage Examples

### 1. Showing Store Name on Product Pages

#### In Product List View (Backend)
```blade
@foreach($products as $product)
    <tr>
        <td>{{ $product->name }}</td>
        <td>
            @if($product->store)
                <span class="badge badge-primary">{{ $product->store->name }}</span>
            @else
                <span class="badge badge-secondary">No Store</span>
            @endif
        </td>
        <!-- other columns -->
    </tr>
@endforeach
```

#### In Product Controller
```php
// Always eager-load store relationship for performance
$products = Product::with('store')->paginate(15);
```

#### In Frontend Product Display
```blade
<div class="product-card">
    <h3>{{ $product->name }}</h3>
    <p class="store-info">
        Store: <strong>{{ $product->store->name ?? 'Main Store' }}</strong>
    </p>
    <p class="store-details">
        @if($product->store)
            <small>{{ $product->store->address }}</small>
            <br>
            <small>{{ $product->store->phone }}</small>
        @endif
    </p>
    <!-- Product details -->
</div>
```

### 2. Showing Store Name on Order Pages

#### In Order List View (Backend)
```blade
@foreach($orders as $order)
    <tr>
        <td>{{ $order->id }}</td>
        <td>{{ $order->user->name }}</td>
        <td>
            @if($order->store)
                <span class="badge badge-info">{{ $order->store->name }}</span>
            @else
                <span class="badge badge-secondary">No Store</span>
            @endif
        </td>
        <!-- other columns -->
    </tr>
@endforeach
```

#### In Order Controller
```php
// Always eager-load store and user relationships
$orders = Order::with('store', 'user', 'orderDetails')->paginate(15);

// Filter orders by store
$orders = Order::with('store', 'user', 'orderDetails')
    ->where('store_id', $storeId)
    ->paginate(15);
```

#### In Order Show/Details Page
```blade
<div class="order-details">
    <h2>Order #{{ $order->id }}</h2>
    
    <div class="row">
        <div class="col-md-6">
            <h4>Order From Store</h4>
            @if($order->store)
                <p><strong>Store Name:</strong> {{ $order->store->name }}</p>
                <p><strong>Address:</strong> {{ $order->store->address }}</p>
                <p><strong>Phone:</strong> {{ $order->store->phone }}</p>
                <p><strong>Code:</strong> {{ $order->store->code }}</p>
            @else
                <p>No store assigned</p>
            @endif
        </div>
        <div class="col-md-6">
            <h4>Customer Information</h4>
            <p><strong>Name:</strong> {{ $order->user->name }}</p>
            <!-- other customer details -->
        </div>
    </div>
</div>
```

### 3. Showing Store Name on Cart Pages

#### In Shopping Cart View (Frontend)
```blade
<div class="cart-container">
    @php
        $cartItems = auth()->user()->carts()->with('store', 'product')->get();
        $groupedByStore = $cartItems->groupBy('store_id');
    @endphp
    
    @foreach($groupedByStore as $storeId => $items)
        <div class="store-section">
            <h3>
                @if($items->first()->store)
                    {{ $items->first()->store->name }}
                @else
                    Main Store
                @endif
            </h3>
            
            <table class="cart-table">
                @foreach($items as $item)
                    <tr>
                        <td>{{ $item->product->name }}</td>
                        <td>{{ $item->quantity }}</td>
                        <td>${{ $item->price }}</td>
                    </tr>
                @endforeach
            </table>
        </div>
    @endforeach
</div>
```

#### In Cart Controller
```php
// Always eager-load store and product relationships
$cartItems = Cart::with('store', 'product', 'address')
    ->where('user_id', $userId)
    ->get();

// Group cart items by store
$cartByStore = $cartItems->groupBy('store_id');
```

#### In Cart Model
```php
public function getStoreNameAttribute()
{
    return $this->store ? $this->store->name : 'Main Store';
}
```

## 4. Reporting Suggestions

### Store-wise Sales Report
```php
// In ReportController
public function store_wise_sales_report(Request $request)
{
    $query = Order::with('store', 'orderDetails');
    
    if ($request->has('store_id') && $request->store_id != '') {
        $query->where('store_id', $request->store_id);
    }
    
    if ($request->has('date_from')) {
        $query->where('created_at', '>=', $request->date_from);
    }
    
    if ($request->has('date_to')) {
        $query->where('created_at', '<=', $request->date_to);
    }
    
    $reports = $query->paginate(15);
    $stores = Store::all();
    
    return view('backend.reports.store_sales', compact('reports', 'stores'));
}

// SQL Query for aggregate
$storeReport = DB::table('orders')
    ->leftJoin('stores', 'orders.store_id', '=', 'stores.id')
    ->select('stores.name', 
        DB::raw('COUNT(orders.id) as total_orders'),
        DB::raw('SUM(orders.grand_total) as total_revenue'))
    ->groupBy('stores.name')
    ->orderBy('total_revenue', 'DESC')
    ->get();
```

### Store Product Inventory Report
```php
public function store_inventory_report()
{
    $inventoryByStore = Store::with(['products' => function($query) {
        $query->select('products.id', 'products.name', 'products.store_id', 'products.unit_price');
        $query->with('stocks');
    }])->get();
    
    return view('backend.reports.store_inventory', compact('inventoryByStore'));
}
```

### Store Performance Dashboard
```blade
<div class="dashboard-section">
    <h2>Store Performance</h2>
    
    <div class="row">
        @foreach($stores as $store)
            @php
                $totalOrders = $store->orders()->count();
                $totalRevenue = $store->orders()->sum('grand_total');
                $totalProducts = $store->products()->count();
            @endphp
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-body">
                        <h5>{{ $store->name }}</h5>
                        <p>Orders: <strong>{{ $totalOrders }}</strong></p>
                        <p>Revenue: <strong>${{ $totalRevenue }}</strong></p>
                        <p>Products: <strong>{{ $totalProducts }}</strong></p>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</div>
```

## 5. Product Assignment to Stores

### Update Product Controller to Support Store Assignment
```php
// In ProductController@create
public function create()
{
    $stores = Store::all();
    return view('backend.product.create', compact('stores'));
}

// In ProductController@store
public function store(Request $request)
{
    $product = new Product();
    $product->store_id = $request->store_id; // Add this
    // ... other product assignments
    $product->save();
}

// In create.blade.php
<div class="form-group row">
    <label class="col-md-3 col-form-label">{{translate('Store')}}</label>
    <div class="col-md-9">
        <select name="store_id" class="form-control aiz-selectpicker">
            <option value="">{{translate('Select Store (Optional)')}}</option>
            @foreach($stores as $store)
                <option value="{{ $store->id }}">{{ $store->name }}</option>
            @endforeach
        </select>
    </div>
</div>
```

## 6. Order Assignment to Stores (During Checkout)

### Update Checkout Logic
```php
// In CartController or CheckoutController
public function checkout(Request $request)
{
    // Get store from session or default
    $storeId = session('selected_store_id') ?? 1;
    
    // Get cart items
    $cartItems = Cart::where('user_id', auth()->id())->get();
    
    // Create order
    $order = new Order();
    $order->user_id = auth()->id();
    $order->store_id = $storeId; // Assign store
    // ... other order details
    $order->save();
    
    // Create order details from cart items
    foreach ($cartItems as $item) {
        OrderDetail::create([
            'order_id' => $order->id,
            'product_id' => $item->product_id,
            'store_id' => $item->store_id ?? $storeId,
            // ... other details
        ]);
    }
}
```

### Update Cart to Include Store Selection
```blade
{{-- In cart page --}}
<form method="POST" action="{{ route('checkout') }}">
    @csrf
    <div class="form-group">
        <label>{{translate('Select Fulfillment Store')}}</label>
        <select name="store_id" class="form-control">
            @foreach($stores as $store)
                <option value="{{ $store->id }}">{{ $store->name }}</option>
            @endforeach
        </select>
    </div>
    
    <button type="submit" class="btn btn-primary">{{translate('Proceed to Checkout')}}</button>
</form>
```

## 7. Filtering/Searching by Store

### In Admin Products List
```blade
<div class="filter-section">
    <form method="GET" action="{{ route('products.all') }}">
        <select name="store_id" class="form-control" onchange="this.form.submit()">
            <option value="">{{translate('All Stores')}}</option>
            @foreach($stores as $store)
                <option value="{{ $store->id }}" {{ request('store_id') == $store->id ? 'selected' : '' }}>
                    {{ $store->name }}
                </option>
            @endforeach
        </select>
    </form>
</div>

@php
    $query = Product::query();
    if(request('store_id')) {
        $query->where('store_id', request('store_id'));
    }
    $products = $query->paginate(15);
@endphp
```

### In Admin Orders List
```blade
<div class="filter-section">
    <form method="GET" action="{{ route('all_orders.index') }}">
        <select name="store_id" class="form-control" onchange="this.form.submit()">
            <option value="">{{translate('All Stores')}}</option>
            @foreach($stores as $store)
                <option value="{{ $store->id }}" {{ request('store_id') == $store->id ? 'selected' : '' }}>
                    {{ $store->name }}
                </option>
            @endforeach
        </select>
    </form>
</div>

@php
    $query = Order::query();
    if(request('store_id')) {
        $query->where('store_id', request('store_id'));
    }
    $orders = $query->paginate(15);
@endphp
```

## 8. Safety Notes
- Store IDs are nullable, so existing products/orders/carts are not affected
- Deleting a store sets all related records' store_id to NULL (not cascade delete)
- Always use `with('store')` for eager loading to avoid N+1 queries
- Use proper authorization/middleware to restrict store management to admin only

## 9. Seeding Initial Stores
```php
// Create a seeder
php artisan make:seeder StoreSeeder

// In database/seeds/StoreSeeder.php
public function run()
{
    Store::create([
        'name' => 'Main Store',
        'code' => 'MAIN',
        'address' => '123 Main Street, City',
        'phone' => '123-456-7890',
    ]);
    
    Store::create([
        'name' => 'Downtown Branch',
        'code' => 'DOWNTOWN',
        'address' => '456 Downtown Ave, City',
        'phone' => '098-765-4321',
    ]);
    
    Store::create([
        'name' => 'Mall Branch',
        'code' => 'MALL',
        'address' => '789 Mall Road, City',
        'phone' => '555-123-4567',
    ]);
}

// Run: php artisan db:seed --class=StoreSeeder
```

## Files Modified/Created
1. `app/Store.php` - Store model
2. `app/Http/Controllers/StoreController.php` - CRUD controller
3. `database/migrations/2025_11_26_000001_create_stores_table.php` - Create stores table
4. `database/migrations/2025_11_26_000002_add_store_id_to_products_orders_carts.php` - Add store_id columns
5. `resources/views/backend/store/index.blade.php` - List view
6. `resources/views/backend/store/create.blade.php` - Create form
7. `resources/views/backend/store/edit.blade.php` - Edit form
8. `resources/views/backend/store/show.blade.php` - Show details
9. `resources/views/backend/inc/admin_sidenav.blade.php` - Menu link added
10. `routes/admin.php` - Routes already configured
