<?php
/**
 * Plugin Name: BdCalls Voice Order Automation
 * Plugin URI:  https://automation.bdcalls.com
 * Description: Automatically place voice confirmation calls for new WooCommerce / WordPress orders using the BdCalls platform.
 * Version:     1.0.0
 * Author:      BdCalls
 * Author URI:  https://bdcalls.com
 * License:     GPL-2.0+
 */

if (!defined('ABSPATH')) { exit; }

define('BDCALLS_API_BASE', 'https://automation-api.bdcalls.com');

/* ---------- Settings page ---------- */
add_action('admin_menu', function () {
    add_options_page('BdCalls Voice Order', 'BdCalls Voice Order', 'manage_options', 'bdcalls-voice-order', 'bdcalls_settings_page');
});

add_action('admin_init', function () {
    register_setting('bdcalls_settings', 'bdcalls_api_key');
    register_setting('bdcalls_settings', 'bdcalls_caller_id');
    register_setting('bdcalls_settings', 'bdcalls_enabled');
});

function bdcalls_settings_page() {
    ?>
    <div class="wrap">
        <h1>BdCalls Voice Order Automation</h1>
        <p>Connect your store with BdCalls so every new order gets an automatic confirmation call.</p>
        <form method="post" action="options.php">
            <?php settings_fields('bdcalls_settings'); ?>
            <table class="form-table">
                <tr>
                    <th>API Key</th>
                    <td><input type="text" name="bdcalls_api_key" value="<?php echo esc_attr(get_option('bdcalls_api_key')); ?>" size="60" placeholder="bdc_live_..." /></td>
                </tr>
                <tr>
                    <th>Caller ID (optional)</th>
                    <td><input type="text" name="bdcalls_caller_id" value="<?php echo esc_attr(get_option('bdcalls_caller_id')); ?>" size="30" placeholder="+8809..." /></td>
                </tr>
                <tr>
                    <th>Enabled</th>
                    <td><input type="checkbox" name="bdcalls_enabled" value="1" <?php checked(1, get_option('bdcalls_enabled'), true); ?> /></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

/* ---------- Webhook trigger on new WooCommerce order ---------- */
add_action('woocommerce_new_order', 'bdcalls_dispatch_call', 10, 1);

function bdcalls_dispatch_call($order_id) {
    if (!get_option('bdcalls_enabled')) return;
    $api_key = trim((string) get_option('bdcalls_api_key'));
    if (!$api_key) return;

    if (!function_exists('wc_get_order')) return;
    $order = wc_get_order($order_id);
    if (!$order) return;

    $phone = $order->get_billing_phone();
    if (!$phone) return;

    $payload = array(
        'order_id'       => (string) $order->get_id(),
        'customer_name'  => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
        'customer_phone' => $phone,
        'amount'         => (string) $order->get_total(),
    );

    wp_remote_post(BDCALLS_API_BASE . '/api/orders/create', array(
        'timeout' => 15,
        'headers' => array(
            'Content-Type'  => 'application/json',
            'x-api-key'     => $api_key,
        ),
        'body' => wp_json_encode($payload),
    ));
}

/* ---------- Webhook receiver for call results ---------- */
add_action('rest_api_init', function () {
    register_rest_route('bdcalls/v1', '/webhook', array(
        'methods'  => 'POST',
        'callback' => 'bdcalls_handle_webhook',
        'permission_callback' => '__return_true',
    ));
});

function bdcalls_handle_webhook(WP_REST_Request $req) {
    $data = $req->get_json_params();
    if (empty($data['order_id'])) {
        return new WP_REST_Response(array('ok' => false, 'error' => 'missing order_id'), 400);
    }
    if (!function_exists('wc_get_order')) return new WP_REST_Response(array('ok' => true), 200);

    $order = wc_get_order($data['order_id']);
    if (!$order) return new WP_REST_Response(array('ok' => false), 404);

    $result = isset($data['result']) ? strtolower($data['result']) : '';
    if ($result === 'confirmed') {
        $order->update_status('processing', 'BdCalls: customer confirmed via voice call.');
    } elseif ($result === 'cancelled') {
        $order->update_status('cancelled', 'BdCalls: customer cancelled via voice call.');
    } else {
        $order->add_order_note('BdCalls voice call result: ' . sanitize_text_field((string) $result));
    }
    return new WP_REST_Response(array('ok' => true), 200);
}