<?php
// File: subscription_callback.php (SERVER WEBHOOK - Final Version)

require_once 'db.php';
require_once 'phonepe_config.php';
require_once 'email_helper.php';

// --- 1. Add polyfill for getallheaders() for hosts like GoDaddy ---
if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            // Look for headers starting with HTTP_
            if (substr($name, 0, 5) == 'HTTP_') {
                $header_key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                $headers[$header_key] = $value;
            }
        }
        return $headers;
    }
}
// --- END OF POLYFILL ---

// --- 2. Get RAW POST Data from PhonePe Server ---
$raw_post = file_get_contents('php://input');
if (!$raw_post) {
    http_response_code(400); 
    echo "No data received.";
    exit();
}

$data = json_decode($raw_post, true);
$decoded_response_str = $data['response'] ?? ''; // This is the base64 string
if (!$decoded_response_str) {
    http_response_code(400);
    echo "Empty response payload.";
    exit();
}

// --- 3. Verify PhonePe's Signature (Security Check) ---
$salt_key = $PHONEPE_SALT_KEY;
$salt_index = $PHONEPE_SALT_INDEX;
// The correct hash is the base64 response string + salt key
$expected_hash = hash('sha256', $decoded_response_str . $salt_key) . '###' . $salt_index;

$headers = getallheaders();
// Check for both common variations of the header key
$x_verify_header = $headers['x-verify'] ?? $headers['X-Verify'] ?? null;

if ($x_verify_header !== $expected_hash) {
    http_response_code(401); // Unauthorized
    error_log("PhonePe Webhook Hash Mismatch. Got: [$x_verify_header], Expected: [$expected_hash]");
    echo "Invalid signature.";
    exit();
}
// --- END OF SECURITY CHECK ---

// --- 4. Decode the Data ---
// Now that we've verified the hash, we can trust the data
$response = json_decode(base64_decode($decoded_response_str), true);

$merchantTransactionId = $response['data']['merchantTransactionId'] ?? null;
$payment_status = $response['code'] ?? 'PAYMENT_ERROR';
$amount_paid_paise = $response['data']['amount'] ?? 0;
$amount_paid_rupees = $amount_paid_paise / 100;

if (!$merchantTransactionId) {
    http_response_code(400);
    echo "Missing merchantTransactionId.";
    exit();
}

// --- 5. Process the Payment ---
if ($payment_status === 'PAYMENT_SUCCESS') {
    
    // --- 6. Fetch Registration Data from DB ---
    $stmt_pending = $conn->prepare("SELECT registration_data FROM pending_registrations WHERE merchant_transaction_id = ?");
    $stmt_pending->bind_param("s", $merchantTransactionId);
    $stmt_pending->execute();
    $result_pending = $stmt_pending->get_result();
    
    if ($result_pending->num_rows === 0) {
        // This can happen if the webhook arrives before the DB is updated.
        // Or, if it's a duplicate webhook call after we've deleted the record.
        error_log("Webhook Warning: No pending registration found for TXN ID: $merchantTransactionId. Might be duplicate call.");
        http_response_code(200); // Acknowledge success, but do nothing.
        echo "Pending registration not found (or already processed).";
        exit();
    }
    
    $row = $result_pending->fetch_assoc();
    $registration_data = unserialize($row['registration_data']);
    $stmt_pending->close();

    // --- 7. Verify Amount ---
    $expected_price = (float)$registration_data['pack_details']['price'];
    if (floatval($amount_paid_rupees) < $expected_price) {
        error_log("Webhook Error: Amount mismatch for TXN ID: $merchantTransactionId. Expected: $expected_price, Paid: $amount_paid_rupees");
        http_response_code(400); // Bad request (amount mismatch)
        echo "Amount mismatch.";
        exit();
    }

    // --- 8. SUCCESS! Create the user ---
    $conn->begin_transaction();
    try {
        $pack_id = $registration_data['subscription_pack_id'];
        $duration = (int)$registration_data['pack_details']['duration_days'];

        // --- ⭐️ LOGIN FIX IS HERE ---
        // Clean the password of any whitespace before hashing
        $password_to_hash = trim($registration_data['password']);
        $password_hash = password_hash($password_to_hash, PASSWORD_DEFAULT);
        // --- END OF LOGIN FIX ---
        
        $stmt_user = $conn->prepare("INSERT INTO users (username, email, password_hash, role, is_verified) VALUES (?, ?, ?, 'artist', 1)");
        $stmt_user->bind_param("sss", $registration_data['username'], $registration_data['email'], $password_hash);
        $stmt_user->execute();
        $user_id = $conn->insert_id;
        $stmt_user->close();

        $profile_image_path = $registration_data['profile_photo_path'];
        $stmt_artist = $conn->prepare("INSERT INTO artist_profiles (user_id, first_name, last_name, shop_name, shop_slug, phone, address, profile_image_path, subscription_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active')");
        $stmt_artist->bind_param("isssssss", $user_id, $registration_data['first_name'], $registration_data['last_name'], $registration_data['username'], $registration_data['username'], $registration_data['phone'], $registration_data['address'], $profile_image_path);
        $stmt_artist->execute();
        $stmt_artist->close();

        $start_date = date("Y-m-d");
        $end_date = date("Y-m-d", strtotime("+$duration days"));
        
        $stmt_sub = $conn->prepare("INSERT INTO artist_subscriptions (user_id, pack_id, payment_gateway_txn_id, amount_paid, payment_status, start_date, end_date) VALUES (?, ?, ?, ?, 'completed', ?, ?)");
        $stmt_sub->bind_param("iisdss", $user_id, $pack_id, $merchantTransactionId, $amount_paid_rupees, $start_date, $end_date);
        $stmt_sub->execute();
        $stmt_sub->close();

        // Delete the pending record *after* everything is successful
        $stmt_delete = $conn->prepare("DELETE FROM pending_registrations WHERE merchant_transaction_id = ?");
        $stmt_delete->bind_param("s", $merchantTransactionId);
        $stmt_delete->execute();
        $stmt_delete->close();

        // Commit all changes to the database
        $conn->commit();
        
        // --- 9. Send Welcome Email ---
        try {
            sendEmail($registration_data['email'], "Welcome! Your Artist Profile is Active", "<h1>Congratulations!</h1><p>Your subscription was successful and your artist profile on United Cultural Forum is now active.</p>");
        } catch (Exception $email_e) {
            // Log the email error, but don't fail the transaction
            error_log("PhonePe Webhook Email Error: " . $email_e->getMessage() . " | TXN ID: " . $merchantTransactionId);
        }
        
        http_response_code(200); // Tell PhonePe "OK"
        echo "User created successfully.";

    } catch (Exception $e) {
        $conn->rollback(); // Undo all database changes
        
        // Check if it's a "Duplicate Entry" error
        if ($e->getCode() == 1062 || strpos($e->getMessage(), 'Duplicate entry') !== false) {
            error_log("PhonePe Webhook DB Error: Duplicate entry for TXN ID: $merchantTransactionId");
             
             // Delete the pending registration so it doesn't get stuck
             $stmt_delete = $conn->prepare("DELETE FROM pending_registrations WHERE merchant_transaction_id = ?");
             $stmt_delete->bind_param("s", $merchantTransactionId);
             $stmt_delete->execute();
             $stmt_delete->close();
             
             // Send an email to the user letting them know
             try {
                sendEmail($registration_data['email'], "Action Required: Your Payment Was Successful", "<h1>Payment Successful!</h1><p>Your payment for an artist subscription was successful, but an account with that username or email already exists. Please contact support with transaction ID <strong>$merchantTransactionId</strong> to apply the subscription to your account.</p>");
             } catch (Exception $email_e) {
                error_log("PhonePe Webhook Email Error (Duplicate): " . $email_e->getMessage() . " | TXN ID: " . $merchantTransactionId);
             }
        } else {
            // For all other errors, log them. The pending record stays for review.
            error_log("PhonePe Webhook DB Error: " . $e->getMessage() . " | TXNID: " . $merchantTransactionId);
        }
        
        http_response_code(500); // Tell PhonePe something went wrong
        echo "Database error.";
    }
} else {
    // Payment was not successful (e.g., FAILED)
    // Clear the pending registration
    $stmt_delete = $conn->prepare("DELETE FROM pending_registrations WHERE merchant_transaction_id = ?");
    $stmt_delete->bind_param("s", $merchantTransactionId);
    $stmt_delete->execute();
    $stmt_delete->close();
    
    http_response_code(200); // Tell PhonePe "OK"
    echo "Payment failed, pending registration cleared.";
}
?>