# 🔌 Checkout API - Complete Reference

## Base URL
```
http://localhost/interior/auth-system/checkout-api.php
```

---

## 📝 Endpoint 1: Place Order

### Request
```
POST /checkout-api.php?action=place_order
Content-Type: application/json
```

### Request Body (JSON)
```json
{
  "first_name": "John",
  "last_name": "Doe",
  "email": "john@example.com",
  "phone": "+923001234567",
  "country": "Pakistan",
  "address": "123 Main Street",
  "city": "Karachi",
  "postcode": "75000",
  "company": "ABC Company",
  "order_notes": "Please deliver after 5 PM",
  "payment_method": "credit_card",
  "ship_to_different": false,
  "shipping_country": "Pakistan",
  "shipping_address": "456 Oak Avenue",
  "shipping_city": "Lahore",
  "shipping_postcode": "54000"
}
```

### Response (Success)
```json
{
  "success": true,
  "message": "Order placed successfully",
  "order_id": 1,
  "total": 22500
}
```

### Response (Error)
```json
{
  "success": false,
  "message": "Missing required field: first_name"
}
```

### Status Codes
- `200` - Success
- `400` - Validation error
- `401` - Not authenticated
- `500` - Server error

---

## 📊 Endpoint 2: Get Order Summary

### Request
```
GET /checkout-api.php?action=get_order_summary
```

### Response
```json
{
  "success": true,
  "items": [
    {
      "id": 1,
      "product_id": 1,
      "product_name": "Nordic Wooden Chair",
      "price": "10000",
      "quantity": 2,
      "total": "20000"
    },
    {
      "id": 2,
      "product_id": 6,
      "product_name": "Coffee Table",
      "price": "8000",
      "quantity": 1,
      "total": "8000"
    }
  ],
  "subtotal": 28000,
  "shipping": 500,
  "tax": 2800,
  "total": 31300
}
```

---

## ✅ Endpoint 3: Validate Address

### Request
```
POST /checkout-api.php?action=validate_address
Content-Type: application/json
```

### Request Body
```json
{
  "email": "john@example.com",
  "phone": "+923001234567",
  "postcode": "75000",
  "address": "123 Main Street",
  "city": "Karachi"
}
```

### Response (Valid)
```json
{
  "success": true,
  "message": "Address is valid"
}
```

### Response (Invalid)
```json
{
  "success": false,
  "errors": [
    "Invalid email address",
    "Invalid phone number",
    "Postcode is required"
  ]
}
```

---

## 🎟️ Endpoint 4: Apply Coupon

### Request
```
POST /checkout-api.php?action=apply_coupon
Content-Type: application/json
```

### Request Body
```json
{
  "coupon_code": "WELCOME10"
}
```

### Response (Valid)
```json
{
  "success": true,
  "message": "Coupon applied successfully",
  "discount_type": "percentage",
  "discount_value": 10
}
```

### Response (Invalid)
```json
{
  "success": false,
  "message": "Invalid or expired coupon"
}
```

---

## 🔐 Authentication

All endpoints require session authentication.

### Required:
```php
session_start();
// User must be logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect to login
}
```

---

## 📦 Request Examples (JavaScript)

### Place Order
```javascript
const orderData = {
  first_name: "John",
  last_name: "Doe",
  email: "john@example.com",
  phone: "+923001234567",
  country: "Pakistan",
  address: "123 Main Street",
  city: "Karachi",
  postcode: "75000",
  payment_method: "credit_card",
  ship_to_different: false
};

fetch('/interior/auth-system/checkout-api.php?action=place_order', {
  method: 'POST',
  body: JSON.stringify(orderData)
})
.then(res => res.json())
.then(data => {
  if (data.success) {
    console.log('Order ID:', data.order_id);
    window.location.href = '/interior/order-confirmation.php?order_id=' + data.order_id;
  }
});
```

### Get Summary
```javascript
fetch('/interior/auth-system/checkout-api.php?action=get_order_summary')
  .then(res => res.json())
  .then(data => {
    console.log('Total:', data.total);
    console.log('Tax:', data.tax);
    console.log('Shipping:', data.shipping);
  });
```

### Validate Address
```javascript
const addressData = {
  email: "john@example.com",
  phone: "+923001234567",
  postcode: "75000",
  address: "123 Main Street",
  city: "Karachi"
};

fetch('/interior/auth-system/checkout-api.php?action=validate_address', {
  method: 'POST',
  body: JSON.stringify(addressData)
})
.then(res => res.json())
.then(data => {
  if (!data.success) {
    console.log('Errors:', data.errors);
  }
});
```

### Apply Coupon
```javascript
const couponData = {
  coupon_code: "WELCOME10"
};

fetch('/interior/auth-system/checkout-api.php?action=apply_coupon', {
  method: 'POST',
  body: JSON.stringify(couponData)
})
.then(res => res.json())
.then(data => {
  if (data.success) {
    console.log('Discount:', data.discount_value + '%');
  }
});
```

---

## 🔍 Request Examples (PHP cURL)

### Place Order
```php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/interior/auth-system/checkout-api.php?action=place_order');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => 'john@example.com',
    'phone' => '+923001234567',
    'country' => 'Pakistan',
    'address' => '123 Main Street',
    'city' => 'Karachi',
    'postcode' => '75000',
    'payment_method' => 'credit_card'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
```

---

## 🛠️ Database Structure Used

### orders table
```sql
Column            | Type           | Note
─────────────────────────────────────────
id                | INT            | Primary Key
user_id           | INT            | FK to users
first_name        | VARCHAR(100)   |
last_name         | VARCHAR(100)   |
email             | VARCHAR(100)   |
phone             | VARCHAR(20)    |
billing_country   | VARCHAR(100)   |
billing_address   | VARCHAR(255)   |
billing_city      | VARCHAR(100)   |
billing_postcode  | VARCHAR(20)    |
shipping_country  | VARCHAR(100)   |
shipping_address  | VARCHAR(255)   |
shipping_city     | VARCHAR(100)   |
shipping_postcode | VARCHAR(20)    |
company           | VARCHAR(100)   |
order_notes       | TEXT           |
payment_method    | VARCHAR(50)    |
subtotal          | DECIMAL(10,2)  |
tax               | DECIMAL(10,2)  |
shipping          | DECIMAL(10,2)  |
total             | DECIMAL(10,2)  |
status            | VARCHAR(50)    | pending, processing, shipped, delivered
tracking_number   | VARCHAR(100)   |
created_at        | TIMESTAMP      |
updated_at        | TIMESTAMP      |
```

### order_items table
```sql
Column       | Type           | Note
──────────────────────────────────────
id           | INT            | Primary Key
order_id     | INT            | FK to orders
product_id   | INT            |
product_name | VARCHAR(255)   |
price        | DECIMAL(10,2)  |
quantity     | INT            |
total        | DECIMAL(10,2)  |
created_at   | TIMESTAMP      |
```

---

## ⚠️ Error Codes Reference

| Code | Meaning | Solution |
|------|---------|----------|
| 400 | Bad Request | Check request format |
| 401 | Unauthorized | Login first |
| 500 | Server Error | Check database connection |

---

## 🚀 Integration Checklist

- [ ] Session authentication enabled
- [ ] Cart table has items
- [ ] Database migration completed
- [ ] User logged in as customer
- [ ] API endpoints accessible
- [ ] Payment methods configured
- [ ] Coupon codes created
- [ ] Email service ready (optional)
- [ ] SMS service ready (optional)

---

## 💡 Common Issues

### Issue: 401 Unauthorized
```
Cause: User not logged in
Solution: Login first at /auth-system/login.php
```

### Issue: Cart is empty
```
Cause: No items in cart
Solution: Add items at /shop.php first
```

### Issue: Database connection failed
```
Cause: MySQL not running or wrong credentials
Solution: Check database name, user, password
```

### Issue: Coupon not working
```
Cause: Invalid code or expired
Solution: Check coupon code and expiry date
```

---

## 📞 Testing Commands

### Test with curl
```bash
curl -X POST http://localhost/interior/auth-system/checkout-api.php?action=place_order \
  -H "Content-Type: application/json" \
  -d '{"first_name":"John","last_name":"Doe",...}'
```

### Test with Postman
1. Set method to POST
2. Set URL: `http://localhost/interior/auth-system/checkout-api.php?action=place_order`
3. Set headers: `Content-Type: application/json`
4. Add JSON body with order data
5. Send request

---

## 📊 Response Formats

All responses are JSON format:

**Success:**
```json
{
  "success": true,
  "message": "Operation successful",
  "data": { ... }
}
```

**Error:**
```json
{
  "success": false,
  "message": "Error description",
  "errors": [ ... ]
}
```

---

## 🔐 Security Headers

Recommended headers to add:

```php
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
```

---

**Last Updated:** December 18, 2025
**API Version:** 1.0
**Status:** Production Ready ✅
