# Compare Count Fix Plan

## Current Status ✅
- Compare JS handlers exist in `detailpagescript.blade.php`
- Header badges (`#comparecount`) show server-rendered counts
- `HomeController@comparecount()` works correctly

## Problem Identified ❌
- JS only loads on **product detail pages**
- Homepage/category pages have badges but **no real-time updates**
- Missing global AJAX handler for header updates

## Detailed Implementation Plan

### Phase 1: Backend - Fix Controller Responses
**File:** `app/Http/Controllers/MainController.php`

```
**docomparison():** (end of method)
$count = app('App\Http\Controllers\Web\HomeController')->comparecount(false);
return response()->json([
    'status' => 'success',
    'message' => 'Product added to comparison!',
    'count' => $count
]);

**removeFromComparsion():** (end of method)
$count = app('App\Http\Controllers\Web\HomeController')->comparecount(false);
return response()->json([
    'status' => 'success',
    'message' => 'Product removed from comparison!',
    'count' => $count
]);
```

### Phase 2: Global JS Handler
**File:** `resources/views/front/layout/master.blade.php`

```
**Add before closing </body>:**
<script>
$(document).ready(function() {
    // Global compare count updater
    window.updateCompareCount = function(count) {
        $('#comparecount').text(count);
        // Update all compare badges (header, sticky, mobile)
        $('[id="comparecount"]').text(count);
        console.log('Compare count updated:', count);
    };

    // Auto-fetch count on page load (for non-detail pages)
    if (!$('#detailpagescript').length) {
        $.get('/vue/compare/count', function(data) {
            window.updateCompareCount(data);
        });
    }
});
</script>
```

### Phase 3: Update Detail Page JS
**File:** `resources/views/front/detailpagescript.blade.php`

```
**Replace existing handlers:**

function addToCompare(id) {
    var addToCompareUrl = '{{ route("compare.product", ":id") }}'.replace(':id', id);
    $.ajax({
        url: addToCompareUrl,
        type: 'GET',
        success: function(response) {
            if (response.status === 'success') {
                window.updateCompareCount(response.count); // ✅ Global update
                Swal.fire({
                    title: "Added",
                    text: response.message,
                    icon: 'success'
                });
            } else {
                Swal.fire({
                    title: "Oops!",
                    text: response.message || 'Error adding product.',
                    icon: 'warning'
                });
            }
        },
        error: function(xhr) {
            Swal.fire({
                title: "Error",
                text: 'Failed to connect to server!',
                icon: 'error'
            });
        }
    });
}

function removeFromCompare(id) {
    var removeFromCompareUrl = '{{ route("remove.compare.product", ":id") }}'.replace(':id', id);
    $.ajax({
        url: removeFromCompareUrl,
        type: 'GET',
        success: function(response) {
            if (response.status === 'success') {
                window.updateCompareCount(response.count); // ✅ Global update
                Swal.fire({
                    title: "Removed",
                    text: response.message,
                    icon: 'success'
                });
            } else {
                Swal.fire({
                    title: "Oops!",
                    text: response.message || 'Error removing product.',
                    icon: 'warning'
                });
            }
        },
        error: function(xhr) {
            Swal.fire({
                title: "Error",
                text: 'Failed to connect to server!',
                icon: 'error'
            });
        }
    });
}
```

## Dependent Files to Edit
| Phase | File | Changes |
|-------|------|---------|
| 1 | `app/Http/Controllers/MainController.php` | Add `count` to JSON responses |
| 2 | `resources/views/front/layout/master.blade.php` | Add global `updateCompareCount()` |
| 3 | `resources/views/front/detailpagescript.blade.php` | Call global updater |

## Follow-up Steps
1. **Test**: Add/remove compare from homepage → header/mobile badges update instantly
2. **No installations needed**
3. **Browser cache**: Hard refresh after changes

**Ready to implement? Confirm to proceed →**

<ask_followup_question>
Confirm this plan looks good? Ready to edit the 3 files above?
</ask_followup_question>

