<?php
header('Content-Type: application/json; charset=utf-8');
require_once 'db_config.php';
require_once 'whatsapp_config.php';

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

if ($action === 'reply' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // Send a message via Meta API
    $phone = $input['phone'] ?? '';
    $messageText = $input['message'] ?? '';
    
    if (!$phone || !$messageText) {
        http_response_code(400);
        echo json_encode(["error" => "Phone and message required"]);
        exit;
    }
    
    $payload = [
        "messaging_product" => "whatsapp",
        "to" => $phone,
        "type" => "text",
        "text" => ["body" => $messageText]
    ];
    
    $ch = curl_init($wa_api_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $wa_token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode >= 200 && $httpcode < 300) {
        echo json_encode(["success" => true, "response" => json_decode($result, true)]);
    } else {
        http_response_code($httpcode);
        echo json_encode(["error" => "Failed to send message", "details" => json_decode($result, true)]);
    }
    exit;
}

if ($action === 'items_list') {
    // Return items to use in webhook
    $stmt = $db->query("SELECT data FROM items");
    $items = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data = json_decode($row['data'], true);
        if(is_array($data)) {
            $items[] = $data;
        }
    }
    echo json_encode($items);
    exit;
}

// Any other action
http_response_code(400);
echo json_encode(["error" => "Invalid action"]);
