<?php
require_once '../config.php';
require_once '../middleware.php';

### API Blueprint: /admin/promo_codes
# GET /admin/promo_codes?action=list
# Description: Lists all promo codes.
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, value: list)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Promo codes fetched",
#       "data": {
#         "promo_codes": [
#           {
#             "id": 1,
#             "code": "PROMO2025",
#             "coins": 100,
#             "usage_limit": 500,
#             "expiry_date": "2025-12-31 23:59:59",
#             "created_at": "2025-06-01 10:00:00"
#           }
#         ]
#       }
#     }
#   - 400: Invalid action
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/promo_codes?action={add|edit|delete}
# Description: Adds, edits, or deletes a promo code.
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, one of: add, edit, delete)
# Request Body (for add/edit):
#   - code: string (required)
#   - coins: integer (required)
#   - usage_limit: integer (required)
#   - expiry_date: string (required, format: YYYY-MM-DD HH:MM:SS)
# Request Body (for delete):
#   - promo_id: integer (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Add successful"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

$token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
authenticateAdmin(str_replace('Bearer ', '', $token));

$action = $_GET['action'] ?? '';

$conn = getDbConnection();

if ($action === 'list') {
    $result = $conn->query("SELECT id, code, coins, usage_limit, expiry_date, created_at FROM promo_codes ORDER BY created_at DESC");
    $promo_codes = [];
    while ($row = $result->fetch_assoc()) {
        $promo_codes[] = $row;
    }
    sendResponse(200, 'Promo codes fetched', ['promo_codes' => $promo_codes]);
} elseif (in_array($action, ['add', 'edit', 'delete'])) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method === 'POST') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (in_array($action, ['add', 'edit'])) {
            validateInput($data, ['code', 'coins', 'usage_limit', 'expiry_date']);
            $code = $data['code'];
            $coins = $data['coins'];
            $usage_limit = $data['usage_limit'];
            $expiry_date = $data['expiry_date'];

            if ($coins <= 0) {
                sendResponse(400, 'Coins must be a positive integer');
            }

            if ($usage_limit <= 0) {
                sendResponse(400, 'Usage limit must be a positive integer');
            }

            if (!strtotime($expiry_date)) {
                sendResponse(400, 'Invalid expiry_date format');
            }

            if ($action === 'add') {
                $stmt = $conn->prepare("INSERT INTO promo_codes (code, coins, usage_limit, expiry_date) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("siis", $code, $coins, $usage_limit, $expiry_date);
            } else {
                validateInput($data, ['promo_id']);
                $promo_id = $data['promo_id'];

                $stmt = $conn->prepare("UPDATE promo_codes SET code = ?, coins = ?, usage_limit = ?, expiry_date = ? WHERE id = ?");
                $stmt->bind_param("siisi", $code, $coins, $usage_limit, $expiry_date, $promo_id);
            }
            $stmt->execute();
            sendResponse(200, ucfirst($action) . ' successful');
        } elseif ($action === 'delete') {
            validateInput($data, ['promo_id']);
            $promo_id = $data['promo_id'];

            $stmt = $conn->prepare("DELETE FROM promo_codes WHERE id = ?");
            $stmt->bind_param("i", $promo_id);
            $stmt->execute();

            sendResponse(200, 'Delete successful');
        }
    } else {
        sendResponse(405, 'Method not allowed');
    }
} else {
    sendResponse(400, 'Invalid action');
}

$stmt->close();
$conn->close();
?>