# Comprehensive Guide: Laravel Lead Capture Package

This document serves as the master guide for the `ekatra/laravel-lead-capture` package. It details not only *how* to use the package, but *why* specific architectural decisions were made during development, and provides step-by-step instructions for configuring the necessary Laravel infrastructure (Queues and Schedulers).

---

## 1. Architectural Decisions & Project History

We made several specific design choices during development to ensure this package is robust, secure, and production-ready.

### The Queue System vs. Synchronous Processing
**The Problem:** Services like Meta and Google Ads require your server to respond to their webhooks with a `200 OK` status within seconds. If your application takes too long (e.g., taking time to save to the database, send a welcome email, or push to an external CRM), Meta will assume your server is broken and will permanently disable your webhook.
**The Solution:** The package controllers do absolutely zero processing. They instantly return a `200 OK` to the provider and push the heavy lifting to a **Laravel Queue**. This allows your server to process the lead in the background without keeping Meta waiting.

### IndiaMart: Polling vs. Webhooks
While Meta and Google push data to us via Webhooks, we configured IndiaMart to use their **Pull API**. The package registers an Artisan command (`leads:fetch-indiamart`) that reaches out to IndiaMart on a schedule to download leads. 

### Local Installation & The Antivirus Block
**The Problem:** When attempting to link the package locally using the standard `composer require` command, we encountered a persistent `curl error 60: SSL certificate problem`. Standard fixes (updating `cacert.pem` in `php.ini`) failed. 
**The Solution:** We discovered that **Avast Antivirus's Web Shield** was intercepting the connection and injecting its own SSL certificates, which PHP strictly rejected as a Man-in-the-Middle attack. 
To resolve this, we bypassed the computer's old, broken global Composer installation by exclusively using **Laravel Herd's internal Composer binary**, which successfully resolved the issue.

### Security: Cryptographic Signatures
**The Problem:** A malicious hacker could easily send a fake POST request to your `/webhooks/leads/meta` URL pretending to be Facebook.
**The Solution:** We updated the package to include a `VerifyMetaWebhookSignature` middleware. When Meta sends a webhook, they sign it using your `FB_APP_SECRET`. Our middleware takes the raw request, hashes it using your secret, and compares it to Meta's signature. If they don't match perfectly, the request is blocked.

---

## 2. Installation & Setup

If you are installing this on a new server or a different local machine:

1. **Place the Package:** Ensure the package folder is located at `packages/LaravelLeadCapture` within your main app.
2. **Link in `composer.json`:** Add the local path repository to your main application's `composer.json` with symlinking enabled:
```json
    "repositories": [
        {
            "type": "path",
            "url": "packages/LaravelLeadCapture",
            "options": {
                "symlink": true
            }
        }
    ],
```
3. **Install the Package:**
The standard command to install the package is:
```bash
composer require ekatra/laravel-lead-capture @dev
```
> [!NOTE]
> **Antivirus / SSL Troubleshooting:** If you run the standard command above locally on Windows and get a `curl error 60 (SSL certificate problem)`, it is likely because your Antivirus Web Shield is blocking the connection. To bypass this, temporarily pause your Antivirus Web Shield and force the use of Laravel Herd's internal Composer by running this exact command instead:
> `& "C:\Users\Ekatra Infotech\.config\herd\bin\composer" require ekatra/laravel-lead-capture:*@dev`

4. **Publish Config & Migrate:**
Publish both the configuration file (so you can edit it) and the migration files (so they are copied to your main app's database folder), then run the migrations.
```bash
php artisan vendor:publish --tag=lead-capture-config
php artisan vendor:publish --tag=lead-capture-migrations
php artisan migrate
```

---

## 3. Environment Configuration (`.env`)

Add the following to your main application's `.env` file:

```env
# -----------------------------
# META (FACEBOOK/INSTAGRAM)
# -----------------------------
FB_APP_ID=your_facebook_app_id
FB_APP_SECRET=your_facebook_app_secret
FB_API_VERSION=v24.0

META_WEBHOOK_VERIFY_TOKEN=your_random_secure_string_for_challenge
META_PAGE_ACCESS_TOKEN=your_long_lived_page_access_token

# -----------------------------
# GOOGLE ADS
# -----------------------------
GOOGLE_ADS_WEBHOOK_KEY=your_google_ads_shared_secret

# -----------------------------
# INDIAMART
# -----------------------------
INDIAMART_CRM_KEY=your_glusr_crm_key
INDIAMART_POLLING_INTERVAL=5 # Check for leads every 5 minutes
```

---

## 4. Configuring Laravel Queues (CRITICAL)

Because the Meta and Google webhooks push jobs to a queue, **you must configure a queue worker**, otherwise, the leads will just sit in memory and never be processed or saved to the database! You can use either a Database or Redis queue driver.

### Option A: Database Queue (Easiest Setup)
1. Set your queue connection in `.env`:
```env
QUEUE_CONNECTION=database
```
2. Create the queue table and migrate:
```bash
php artisan queue:table
php artisan migrate
```

### Option B: Redis Queue (High Performance, Recommended for Production)
If you expect a massive volume of leads, Redis is much faster than a standard database.
1. Ensure your server has Redis installed and running (Herd Pro includes Redis, or you can install it on your Ubuntu server via `sudo apt install redis-server`).
2. Set your queue connection in `.env`:
```env
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```
3. Ensure you have the Redis PHP extension installed in your project:
```bash
composer require predis/predis
```

### Running the Queue Worker (Local Testing)
Regardless of whether you chose Database or Redis, you can start the worker locally to process leads by running:
```bash
php artisan queue:work
```

### Running the Queue Worker (Production via Supervisor)
When you deploy to your Ubuntu server, you cannot just run `queue:work` in the terminal because it will stop when you close your SSH session. You must configure **Supervisor** to keep the queue worker running permanently in the background and automatically restart it if it crashes.

**1. Install Supervisor:**
```bash
sudo apt-get install supervisor
```

**2. Create a Configuration File:**
Create a new configuration file for your queue worker:
```bash
sudo nano /etc/supervisor/conf.d/laravel-lead-worker.conf
```

**3. Add the Configuration:**
Paste the following configuration into the file. Make sure to replace `/path/to/your/project` and `your_ubuntu_user` with your actual server details:
```ini
[program:laravel-lead-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/your/project/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=your_ubuntu_user
numprocs=8
redirect_stderr=true
stdout_logfile=/path/to/your/project/storage/logs/worker.log
stopwaitsecs=3600
```
> [!NOTE]
> If you are using the `database` queue driver instead of `redis`, simply remove the `redis` keyword from the `command=` line in the configuration above.

**4. Start Supervisor:**
Instruct Supervisor to read the new configuration and immediately start the background workers:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-lead-worker:*
```

---

## 5. Configuring the Task Scheduler (CRITICAL)

Because IndiaMart uses the Pull API, we built the `leads:fetch-indiamart` command. Our package automatically tells Laravel to run this command every 5 minutes. **However, Laravel's scheduler does not run by itself.**

### Step 1: Test the Command Manually
You can test the IndiaMart fetcher at any time by running:
```bash
php artisan leads:fetch-indiamart
```

### Step 2: Start the Scheduler Locally
While testing locally in Herd, run this command in a separate terminal window to start the clock:
```bash
php artisan schedule:work
```

### Step 3: Configure Cron for Production
When you deploy this to your Ubuntu production server, you must add a single Cron job that ticks the Laravel scheduler every minute.
1. SSH into your Ubuntu server.
2. Type `crontab -e`.
3. Add this exact line to the bottom of the file (replace `/path/to/your/project` with your actual server path):
```bash
* * * * * cd /path/to/your/project && php artisan schedule:run >> /dev/null 2>&1
```
Once this Cron job is added, Laravel will automatically poll IndiaMart exactly every 5 minutes (as defined in your `.env`) without any human intervention.

---

## 6. Listening for Leads

The package handles everything from receiving the webhook to verifying signatures, fetching data, and saving it to the `leads` database table. 

If you want your main application to do something else when a lead arrives (like send an email to the sales team), listen for the package's event:

```php
namespace App\Listeners;

use Ekatra\LeadCapture\Events\LeadReceived;

class SendSalesNotification
{
    public function handle(LeadReceived $event)
    {
        $lead = $event->leadData;

        // $lead['first_name']
        // $lead['source'] ('meta', 'google', 'indiamart')
        
        // Mail::to('sales@company.com')->send(new NewLeadEmail($lead));
    }
}
```
