<?php
// File: competition_callback.php (SERVER WEBHOOK)

require_once 'db.php';
require_once 'phonepe_config.php';
require_once 'email_helper.php';

// 1. Polyfill for getallheaders (for GoDaddy/Hostinger)
if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $header_key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                $headers[$header_key] = $value;
            }
        }
        return $headers;
    }
}

// 2. Get RAW POST Data from PhonePe Server
$raw_post = file_get_contents('php://input');
$data = json_decode($raw_post, true);
$decoded_response_str = $data['response'] ?? '';

if (!$decoded_response_str) {
    http_response_code(400);
    echo "Empty response payload.";
    exit();
}

// 3. Verify PhonePe's Signature
$salt_key = $PHONEPE_SALT_KEY;
$salt_index = $PHONEPE_SALT_INDEX;
$expected_hash = hash('sha256', $decoded_response_str . $salt_key) . '###' . $salt_index;
$headers = getallheaders();
// Check both header variations just in case
$x_verify_header = $headers['x-verify'] ?? $headers['X-Verify'] ?? null;

if ($x_verify_header !== $expected_hash) {
    http_response_code(401); 
    error_log("PhonePe (Competition) Webhook Hash Mismatch. Got: $x_verify_header");
    echo "Invalid signature.";
    exit();
}

// 4. Decode & Process
$response = json_decode(base64_decode($decoded_response_str), true);
$merchantTransactionId = $response['data']['merchantTransactionId'] ?? null;
$payment_status_code = $response['code'] ?? 'PAYMENT_ERROR';
$phonepe_txn_id = $response['data']['transactionId'] ?? null;

if (!$merchantTransactionId) {
    http_response_code(400);
    echo "Missing merchantTransactionId.";
    exit();
}

if ($payment_status_code === 'PAYMENT_SUCCESS') {
    // Note: Using 'Success' to match your competition_entries ENUM in DB
    $new_status = 'Success'; 
    
    try {
        // Update the entry in the database
        $stmt = $conn->prepare("UPDATE competition_entries SET payment_status = ?, phonepe_txn_id = ? WHERE merchant_transaction_id = ?");
        $stmt->bind_param("sss", $new_status, $phonepe_txn_id, $merchantTransactionId);
        $stmt->execute();
        
        // If the update was successful (or row already updated), send the email
        if ($stmt->affected_rows >= 0) {
            // Fetch details for email
            // Uses 'name' column based on your DB schema
            $stmt_fetch = $conn->prepare("SELECT email, name, competition_id FROM competition_entries WHERE merchant_transaction_id = ?");
            $stmt_fetch->bind_param("s", $merchantTransactionId);
            $stmt_fetch->execute();
            $result_fetch = $stmt_fetch->get_result();
            $entry = $result_fetch->fetch_assoc();
            $stmt_fetch->close();
            
            if ($entry) {
                $upload_link = "https://unitedculturalforum.com/upload_entry.php?code=" . $merchantTransactionId;
                $subject = "Competition Registration Confirmed!";
                $body = "
                    <h1>Registration Confirmed!</h1>
                    <p>Dear {$entry['name']},</p>
                    <p>You have successfully registered for the competition.</p>
                    <p><strong>Your Registration Code:</strong> {$merchantTransactionId}</p>
                    <hr>
                    <h3>Next Step: Upload Your Artwork</h3>
                    <p>Please click the link below to upload your artwork and profile photo using your Registration Code:</p>
                    <p><a href='{$upload_link}' style='background-color: #5A8B48; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Upload Artwork</a></p>
                    <p>Or visit this link directly: {$upload_link}</p>
                ";
                
                try { 
                    sendEmail($entry['email'], $subject, $body); 
                } catch (Exception $e) {
                    error_log("Competition Email Error: " . $e->getMessage());
                }
            }
        }
        $stmt->close();
    } catch (Exception $e) {
        error_log("Competition Webhook DB Error: " . $e->getMessage());
        http_response_code(500);
        exit();
    }

} else {
    // Payment Failed
    $stmt = $conn->prepare("UPDATE competition_entries SET payment_status = 'Failed' WHERE merchant_transaction_id = ?");
    $stmt->bind_param("s", $merchantTransactionId);
    $stmt->execute();
    $stmt->close();
}

http_response_code(200);
echo "Webhook processed.";
?>