<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit();
}

$target_phone = trim($_POST['phone'] ?? '');
if (empty($target_phone)) {
    echo json_encode(['status' => 'error', 'message' => 'Phone number is required.']);
    exit();
}

// Basic validation (only digits, remove +, space, etc)
$clean_phone = preg_replace('/[^0-9]/', '', $target_phone);
if (strlen($clean_phone) < 10) {
    echo json_encode(['status' => 'error', 'message' => 'Please provide a valid phone number with country code.']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    $stmt = $pdo->prepare("SELECT employee_code, first_name, last_name FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
    
    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => 'User not found.']);
        exit();
    }
    
    $employee_code = $user['employee_code'];
    $full_name = trim($user['first_name'] . ' ' . $user['last_name']);
    if (empty($full_name)) $full_name = "A team member";

    $ref_url_raw = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . rtrim(dirname(dirname($_SERVER['PHP_SELF'])), '/\\') . "/register/ref/" . urlencode($employee_code);

    // Fetch WhatsApp channel config
    $stmt_c = $pdo->prepare("SELECT config_json, is_enabled FROM notification_channels WHERE channel_name = 'whatsapp'");
    $stmt_c->execute();
    $wa_config_row = $stmt_c->fetch();

    if (!$wa_config_row || !$wa_config_row['is_enabled']) {
        echo json_encode(['status' => 'error', 'message' => 'WhatsApp API channel is currently disabled or not configured.']);
        exit();
    }

    $wa_config = json_decode($wa_config_row['config_json'], true);
    $api_url = $wa_config['api_url'] ?? '';
    $token = $wa_config['token'] ?? '';

    if (empty($api_url) || empty($token)) {
        echo json_encode(['status' => 'error', 'message' => 'WhatsApp API credentials are not set.']);
        exit();
    }

    // Construct the interactive message payload (CTA URL Button)
    $payload = [
        'messaging_product' => 'whatsapp',
        'to' => $clean_phone,
        'type' => 'interactive',
        'interactive' => [
            'type' => 'cta_url',
            'body' => [
                'text' => "$full_name has invited you to join EventPortal using their Employee Referral Code: *$employee_code*!\nClick the button below to register."
            ],
            'action' => [
                'name' => 'cta_url',
                'parameters' => [
                    'display_text' => 'Register Now',
                    'url' => $ref_url_raw
                ]
            ]
        ]
    ];

    // Check if it's the mock setup
    if (strpos($api_url, 'mock') !== false || $token === 'wa_mock_token_xyz_123') {
        // Log it to simulate successful sending
        error_log("MOCKED WhatsApp API Interactive Share to $clean_phone : " . json_encode($payload));
        echo json_encode(['status' => 'success', 'message' => 'Invitation sent successfully (Mocked).']);
        exit();
    }

    // Send real request
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        echo json_encode(['status' => 'error', 'message' => 'cURL Error: ' . curl_error($ch)]);
    } else {
        $resp_data = json_decode($response, true);
        if ($http_code >= 200 && $http_code < 300) {
            echo json_encode(['status' => 'success', 'message' => 'Invitation sent successfully!']);
        } else {
            $err_msg = $resp_data['error']['message'] ?? 'Unknown API Error';
            echo json_encode(['status' => 'error', 'message' => 'WhatsApp API Error: ' . $err_msg]);
        }
    }
    curl_close($ch);

} catch (PDOException $e) {
    error_log("DB Error in share_whatsapp: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => 'Database error occurred.']);
}
