<?php
// File: admin/phonepe_callback.php (Webhook)

// ✅ FIX: Include the MAIN config file from the root directory
require_once __DIR__ . '/../phonepe_config.php'; 
require_once 'phonepe_helper.php'; // Helper is no longer used here, but safe to keep
require_once '../db.php';
require_once 'email_helper.php'; // For sending confirmation emails

// --- 1. GET RAW DATA FROM WEBHOOK ---
$raw = file_get_contents('php://input');

// --- 2. ✅ CRITICAL SECURITY CHECK: VERIFY THE WEBHOOK HASH ---
$headers = getallheaders();
$x_verify = $headers['x-verify'] ?? $headers['X-Verify'] ?? ''; // Get the hash from PhonePe

// Calculate our own hash to compare
$salt_key = $PHONEPE_SALT_KEY; // From config
$salt_index = $PHONEPE_SALT_INDEX; // From config
$local_hash = hash('sha256', $raw . $PHONEPE_WEBHOOK_ENDPOINT) . '###' . $salt_index;

// if ($x_verify !== $local_hash) {
//     // NOTE: Enable this check once you are sure your endpoint in config is correct.
//     // http_response_code(401); // Unauthorized
//     // error_log("PhonePe Webhook: Invalid hash. Got: $x_verify, Expected: $local_hash");
//     // die("Invalid signature.");
// }
// --- End Security Check ---


// --- 3. PROCESS THE DATA ---
$data = json_decode(base64_decode($raw), true);
if (!$data || !isset($data['response'])) {
    http_response_code(400); // Bad Request
    die("Invalid callback data.");
}

$decoded_response = json_decode(base64_decode($data['response']), true);

// Extract details
$txn_id = $decoded_response['merchantTransactionId'] ?? '';
$status_code = $decoded_response['responseCode'] ?? '';
$phonepe_txn_id = $decoded_response['transactionId'] ?? '';
$amount = intval($decoded_response['amount'] ?? 0) / 100; // Get amount in rupees

$type = $_GET['type'] ?? '';

if (!$txn_id || !$type) {
    http_response_code(400); // Bad Request
    die("Invalid callback parameters.");
}

// Determine payment status
$success = ($status_code === 'PAYMENT_SUCCESS');

// --- 4. UPDATE DATABASE ---
try {
    if ($type === "subscription") {
        $status = $success ? 'Success' : 'Failed';
        $stmt = $conn->prepare("UPDATE artist_subscriptions SET payment_status=?, phonepe_txn_id=?, updated_at=NOW() WHERE txn_id=?");
    } else {
        $status = $success ? 'Paid' : 'Failed';
        $stmt = $conn->prepare("UPDATE competition_entries SET payment_status=?, phonepe_txn_id=? WHERE txn_id=?");
    }
    $stmt->bind_param("sss", $status, $phonepe_txn_id, $txn_id);
    $stmt->execute();
    $stmt->close();
} catch (Exception $e) {
    error_log("PhonePe Webhook DB Error: " . $e->getMessage());
    http_response_code(500); // Internal Server Error
    die("Database update failed.");
}


// --- 5. SEND EMAIL (ONLY ON SUCCESS) ---
if ($success) {
    try {
        if ($type === "subscription") {
            $q = $conn->query("SELECT u.email, u.full_name FROM users u JOIN artist_subscriptions s ON s.user_id=u.id WHERE s.txn_id='$txn_id'");
            $user = $q->fetch_assoc();
            $subject = "🎨 Subscription Activated - United Cultural Forum";
            $body = "<p>Dear {$user['full_name']},</p>
            <p>Your artist subscription payment of ₹$amount has been successfully received.</p>
            <p>Thank you for being part of the United Cultural Forum!</p>";
            admin_send_email($user['email'], $subject, $body);
        } else {
            $q = $conn->query("SELECT name, email, competition_id FROM competition_entries WHERE txn_id='$txn_id'");
            $entry = $q->fetch_assoc();
            $subject = "🏆 Competition Entry Confirmed - United Cultural Forum";
            $body = "<p>Dear {$entry['name']},</p>
            <p>Your competition entry payment of ₹$amount for competition ID #{$entry['competition_id']} was successful.</p>
            <p>Best of luck!</p>";
            admin_send_email($entry['email'], $subject, $body);
        }
    } catch (Exception $e) {
        error_log("PhonePe Webhook Email Error: " . $e->getMessage());
    }
}

// --- 6. RESPOND TO PHONEPE ---
// The webhook should just return a 200 OK, not HTML.
http_response_code(200);
echo json_encode(['status' => 'success']);
?>