# Week 11: Syllabus Planner & Wallet Enhancements - API Documentation

## Overview
This document provides comprehensive API documentation for Week 11 features including:
- Auto-Generate Weekly Tests
- Syllabus Progress Dashboard
- Subscription Plans (Monthly, 6-Month, Yearly)
- Razorpay Webhook Integration

---

## Day 1-2: Auto-Generate Weekly Tests

### Generate Weekly Test from Completed Topics

**Endpoint:** `POST /api/v2/tutor/syllabus/{id}/generate-weekly-test`

**Description:** Automatically generates a test from all completed topics for a specific week

**Authentication:** Required (Bearer Token)

**Request Body:**
```json
{
  "week_number": 1,
  "questions_per_topic": 5,
  "duration_minutes": 60,
  "total_marks": 50
}
```

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/tutor/syllabus/1/generate-weekly-test' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--data '{
  "week_number": 1,
  "questions_per_topic": 5,
  "duration_minutes": 60,
  "total_marks": 50
}'
```

**Success Response (201):**
```json
{
  "status": true,
  "message": "Weekly test generated successfully",
  "data": {
    "test_series_id": 123,
    "test_name": "JEE Preparation - Week 1 Test",
    "scheduled_at": "2025-11-21 18:00:00",
    "duration_minutes": 60,
    "total_questions": 15,
    "total_marks": 50,
    "topics_covered": [
      {
        "topic_id": 45,
        "topic_name": "Algebra"
      },
      {
        "topic_id": 46,
        "topic_name": "Trigonometry"
      }
    ]
  }
}
```

**Error Response - No Completed Topics (422):**
```json
{
  "status": false,
  "message": "No completed topics found for week 1",
  "error_code": "NO_COMPLETED_TOPICS"
}
```

**Error Response - Insufficient Questions (422):**
```json
{
  "status": false,
  "message": "Insufficient questions available for selected topics",
  "error_code": "INSUFFICIENT_QUESTIONS",
  "details": {
    "required": 15,
    "available": 8,
    "shortage": 7
  }
}
```

---

## Day 3: Progress Tracking Dashboard

### Get Syllabus Dashboard

**Endpoint:** `GET /api/v2/tutor/syllabus/{id}/dashboard`

**Description:** Get comprehensive dashboard data including progress, timeline, test status, and student engagement

**Authentication:** Required (Bearer Token)

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/tutor/syllabus/1/dashboard' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```

**Success Response (200):**
```json
{
  "status": true,
  "data": {
    "syllabus_info": {
      "id": 1,
      "title": "JEE Preparation 2024",
      "batch_name": "JEE Advanced Batch",
      "batch_id": 5,
      "created_by": {
        "id": 2,
        "name": "Prof. Sharma"
      }
    },
    "overall_progress": {
      "total_topics": 30,
      "completed_topics": 12,
      "pending_topics": 18,
      "completion_percentage": 40.00,
      "total_weeks": 12,
      "weeks_elapsed": 5,
      "current_week": 5,
      "status": "On Track",
      "is_on_track": true,
      "expected_completion_percentage": 41.67,
      "start_date": "2025-10-01",
      "end_date": "2025-12-31"
    },
    "topic_timeline": {
      "completed": [
        {
          "syllabus_topic_id": 101,
          "topic_id": 45,
          "topic_name": "Algebra",
          "week_number": 1,
          "scheduled_date": "2025-10-05",
          "is_completed": true,
          "completed_at": "2025-10-05 10:30:00"
        }
      ],
      "pending": [
        {
          "syllabus_topic_id": 115,
          "topic_id": 60,
          "topic_name": "Calculus",
          "week_number": 6,
          "scheduled_date": "2025-11-20",
          "is_completed": false,
          "completed_at": null
        }
      ],
      "overdue": [
        {
          "syllabus_topic_id": 108,
          "topic_id": 52,
          "topic_name": "Coordinate Geometry",
          "week_number": 3,
          "scheduled_date": "2025-10-18",
          "is_completed": false,
          "completed_at": null
        }
      ],
      "summary": {
        "completed_count": 12,
        "pending_count": 15,
        "overdue_count": 3
      }
    },
    "test_status": {
      "topics_with_tests": 8,
      "completed_topics_without_tests": 4,
      "tests_generated_count": 2,
      "tests_generated": [
        {
          "test_id": 123,
          "test_name": "JEE Preparation - Week 1 Test",
          "scheduled_at": "2025-10-08 18:00:00",
          "status": "active"
        }
      ],
      "test_opportunities": [
        {
          "week_number": 2,
          "completed_topics": 4,
          "ready_for_test": true
        }
      ],
      "pending_test_opportunities": 1
    },
    "student_engagement": {
      "total_students": 45,
      "total_tests": 2,
      "unique_participants": 38,
      "average_participation_rate": 84.44,
      "average_test_score": 72.50,
      "total_test_attempts": 76,
      "completed_test_attempts": 70
    },
    "insights": [
      {
        "type": "warning",
        "message": "3 topic(s) are overdue and need attention",
        "action": "Review and mark overdue topics as completed"
      },
      {
        "type": "info",
        "message": "1 week(s) have completed topics ready for test generation",
        "action": "Generate weekly tests for completed topics"
      },
      {
        "type": "success",
        "message": "Syllabus progress is on track!",
        "action": "Keep up the good work"
      }
    ]
  }
}
```

---

## Day 4: Subscription Plans

### Get All Subscription Plans

**Endpoint:** `GET /api/v2/plans`

**Description:** Retrieve all available subscription plans with pricing and benefits

**Authentication:** Not Required (Public endpoint)

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/plans'
```

**Success Response (200):**
```json
{
  "status": true,
  "message": "Subscription plans retrieved successfully",
  "data": [
    {
      "id": 1,
      "name": "Monthly Plan",
      "slug": "monthly",
      "description": "Access all features for 30 days",
      "price": 299.00,
      "duration_days": 30,
      "coins": 50,
      "savings": null,
      "price_per_day": 9.97
    },
    {
      "id": 2,
      "name": "6-Month Plan",
      "slug": "6-months",
      "description": "Access all features for 6 months",
      "price": 1499.00,
      "duration_days": 180,
      "coins": 300,
      "savings": 295.00,
      "price_per_day": 8.33
    },
    {
      "id": 3,
      "name": "Yearly Plan",
      "slug": "yearly",
      "description": "Access all features for 1 year",
      "price": 2499.00,
      "duration_days": 365,
      "coins": 600,
      "savings": 1089.00,
      "price_per_day": 6.85
    }
  ]
}
```

---

### Purchase Subscription Plan

**Endpoint:** `POST /api/v2/subscriptions/purchase`

**Description:** Create a Razorpay order for subscription purchase

**Authentication:** Required (Bearer Token)

**Request Body:**
```json
{
  "subscription_plan_id": 1,
  "payment_method": "razorpay"
}
```

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/subscriptions/purchase' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--data '{
  "subscription_plan_id": 1,
  "payment_method": "razorpay"
}'
```

**Success Response (201):**
```json
{
  "status": true,
  "message": "Subscription order created successfully",
  "data": {
    "order_id": "order_P8Q9R0S1T2U3V4",
    "amount": 299.00,
    "currency": "INR",
    "plan": {
      "id": 1,
      "name": "Monthly Plan",
      "duration_days": 30
    },
    "razorpay_key": "rzp_test_XXXXXXXXXXX"
  }
}
```

---

### Verify Subscription Payment

**Endpoint:** `POST /api/v2/subscriptions/verify`

**Description:** Verify payment and activate subscription after successful payment

**Authentication:** Required (Bearer Token)

**Request Body:**
```json
{
  "order_id": "order_P8Q9R0S1T2U3V4",
  "payment_id": "pay_X1Y2Z3A4B5C6D7",
  "subscription_plan_id": 1
}
```

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/subscriptions/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--data '{
  "order_id": "order_P8Q9R0S1T2U3V4",
  "payment_id": "pay_X1Y2Z3A4B5C6D7",
  "subscription_plan_id": 1
}'
```

**Success Response (200):**
```json
{
  "status": true,
  "message": "Subscription activated successfully",
  "data": {
    "subscription_id": 42,
    "plan_name": "Monthly Plan",
    "start_date": "2025-11-14",
    "end_date": "2025-12-14",
    "coins_credited": 50
  }
}
```

---

### Get My Subscriptions

**Endpoint:** `GET /api/v2/subscriptions/my-subscriptions`

**Description:** Get all subscriptions for the authenticated user

**Authentication:** Required (Bearer Token)

**cURL Example:**
```bash
curl --location 'http://localhost:8000/api/v2/subscriptions/my-subscriptions' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```

**Success Response (200):**
```json
{
  "status": true,
  "message": "Subscriptions retrieved successfully",
  "data": [
    {
      "id": 42,
      "plan_name": "Monthly Plan",
      "amount_paid": 299.00,
      "start_date": "2025-11-14",
      "end_date": "2025-12-14",
      "status": "active",
      "is_active": true,
      "days_remaining": 30
    },
    {
      "id": 35,
      "plan_name": "6-Month Plan",
      "amount_paid": 1499.00,
      "start_date": "2025-05-01",
      "end_date": "2025-10-28",
      "status": "expired",
      "is_active": false,
      "days_remaining": 0
    }
  ]
}
```

---

## Day 5: Razorpay Webhooks

### Webhook Handler

**Endpoint:** `POST /api/webhooks/razorpay`

**Description:** Handle Razorpay webhook events for payment verification and automation

**Authentication:** Verified via webhook signature (no Bearer token required)

**Webhook URL to Configure in Razorpay Dashboard:**
```
https://your-domain.com/api/webhooks/razorpay
```

**Supported Events:**
- `payment.captured` - Payment successfully captured
- `payment.failed` - Payment failed
- `subscription.cancelled` - Subscription cancelled
- `refund.created` - Refund initiated

**Example Webhook Payload (payment.captured):**
```json
{
  "entity": "event",
  "account_id": "acc_XXXXXXXXXXX",
  "event": "payment.captured",
  "contains": ["payment"],
  "payload": {
    "payment": {
      "entity": {
        "id": "pay_X1Y2Z3A4B5C6D7",
        "entity": "payment",
        "amount": 29900,
        "currency": "INR",
        "status": "captured",
        "order_id": "order_P8Q9R0S1T2U3V4",
        "method": "card",
        "captured": true,
        "created_at": 1699876543
      }
    }
  },
  "created_at": 1699876545
}
```

**Testing Webhook Locally:**
```bash
curl --location 'http://localhost:8000/api/webhooks/razorpay' \
--header 'Content-Type: application/json' \
--header 'X-Razorpay-Signature: SIGNATURE_HASH' \
--data '{
  "entity": "event",
  "event": "payment.captured",
  "payload": {
    "payment": {
      "entity": {
        "id": "pay_X1Y2Z3A4B5C6D7",
        "amount": 29900,
        "currency": "INR",
        "status": "captured",
        "order_id": "order_P8Q9R0S1T2U3V4"
      }
    }
  }
}'
```

**Success Response (200):**
```json
{
  "status": true,
  "message": "Webhook processed successfully"
}
```

**Error Response - Invalid Signature (401):**
```json
{
  "status": false,
  "message": "Invalid signature"
}
```

---

## Setup Instructions

### 1. Run Migrations
```bash
php artisan migrate
```

This will create the following tables:
- `subscription_plans` - Stores subscription plan details
- `user_subscriptions` - Tracks user subscription history
- `webhook_events` - Logs all webhook events for idempotency

### 2. Configure Environment Variables

Add the following to your `.env` file:

```env
# Razorpay Configuration
RAZORPAY_KEY=rzp_test_XXXXXXXXXXX
RAZORPAY_SECRET=your_razorpay_secret
RAZORPAY_WEBHOOK_SECRET=your_webhook_secret
RAZORPAY_MODE=test

# Database (ensure proper configuration)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
```

### 3. Configure Razorpay Webhook

1. Log in to [Razorpay Dashboard](https://dashboard.razorpay.com)
2. Navigate to **Settings** → **Webhooks**
3. Click **Create New Webhook**
4. Enter webhook URL: `https://your-domain.com/api/webhooks/razorpay`
5. Select events to listen:
   - `payment.captured`
   - `payment.failed`
   - `subscription.cancelled`
   - `refund.created`
6. Set a **Secret** and add it to `.env` as `RAZORPAY_WEBHOOK_SECRET`
7. Save the webhook

### 4. Test Webhook Signature Verification

The webhook controller automatically verifies the signature using:
```php
hash_hmac('sha256', $webhookBody, $webhookSecret)
```

This ensures webhooks are authentic and from Razorpay.

---

## Security Features

### Webhook Security
- ✅ **Signature Verification**: All webhooks are verified using HMAC SHA256
- ✅ **Idempotency**: Duplicate webhook events are automatically detected and ignored
- ✅ **Event Logging**: All webhook events are logged in `webhook_events` table
- ✅ **Error Handling**: Failed events are marked and can be retried

### Payment Security
- ✅ **Razorpay Payment Verification**: All payments are verified with Razorpay API
- ✅ **Transaction Logging**: All payment transactions are logged
- ✅ **Automatic Coin Credit**: Coins are credited only after successful payment verification

---

## Error Codes Reference

| Code | Description | HTTP Status |
|------|-------------|-------------|
| `NO_COMPLETED_TOPICS` | No topics completed for the specified week | 422 |
| `INSUFFICIENT_QUESTIONS` | Not enough questions available in database | 422 |
| `QUESTION_SELECTION_FAILED` | Failed to select questions | 500 |
| `INVALID_SIGNATURE` | Webhook signature verification failed | 401 |

---

## Best Practices

1. **Test Generation**:
   - Generate tests only after completing at least 3-4 topics in a week
   - Review generated questions before sharing with students
   - Use appropriate difficulty distribution (40% Easy, 40% Medium, 20% Hard)

2. **Subscription Management**:
   - Always verify payment status before activating subscription
   - Handle failed payments gracefully with user notifications
   - Log all subscription changes for audit trail

3. **Webhook Handling**:
   - Never disable signature verification in production
   - Monitor webhook logs regularly for failed events
   - Set up retry mechanism for failed webhook processing

---

## Support

For issues or questions:
- Check logs: `storage/logs/laravel.log`
- Review webhook events: Query `webhook_events` table
- Contact: support@pathshalaa.com

---

**Last Updated:** November 14, 2025
**Version:** 1.0
**Author:** Pathshalaa Development Team
