<?php
// File: register_handler.php (Debug Fix)

require_once 'session_init.php';
require_once 'db.php';
require_once 'phonepe_config.php'; // For Artist payment
require_once 'email_helper.php'; // For Customer activation

// --- 1. Get Common Data ---
$role = $_POST['role'] ?? '';
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = $_POST['password']; // Will be hashed

// --- 2. Check if user exists in the MAIN 'users' table ---
$stmt_check_users = $conn->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
$stmt_check_users->bind_param("ss", $username, $email);
$stmt_check_users->execute();
$result_check_users = $stmt_check_users->get_result();
if ($result_check_users->num_rows > 0) {
    $stmt_check_users->close();
    header('Location: register.php?error=user_exists'); // New, clearer error
    exit();
}
$stmt_check_users->close();

// --- 3. Check if user exists in the 'pending_registrations' table ---
// ⭐️ FIX: This query now correctly checks the 'serialized' data
$like_username = '%"username"%"' . $conn->real_escape_string($username) . '"%';
$like_email = '%"email"%"' . $conn->real_escape_string($email) . '"%';
$stmt_check_pending = $conn->prepare("SELECT id FROM pending_registrations WHERE registration_data LIKE ? OR registration_data LIKE ?");
$stmt_check_pending->bind_param("ss", $like_username, $like_email);
$stmt_check_pending->execute();
$result_check_pending = $stmt_check_pending->get_result();
if ($result_check_pending->num_rows > 0) {
    $stmt_check_pending->close();
    header('Location: register.php?error=pending_exists'); // New, clearer error
    exit();
}
$stmt_check_pending->close();
// --- END OF 'EXISTS' FIX ---

// --- 4. Handle Registration Based on Role ---
try {
    if ($role === 'artist') {
        // --- ARTIST PAYMENT FLOW ---
        
        $upload_dir = 'uploads/profiles/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // 4a. Get artist data
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        $subscription_pack_id = $_POST['subscription_pack'];

        // 4b. Handle File Upload
        $profile_photo_path = ''; // Initialize
        if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
            if ($_FILES['profile_photo']['size'] > 100 * 1024) {
                 header('Location: register.php?error=filesize');
                 exit();
            }
            $file_extension = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
            $safe_filename = 'profile_' . uniqid() . '.' . $file_extension;
            $target_path = $upload_dir . $safe_filename;
            if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $target_path)) {
                $profile_photo_path = $target_path;
            } else {
                 throw new Exception("File upload failed to move.");
            }
        } else {
            throw new Exception("Profile photo is required or upload failed.");
        }

        // 4c. Fetch Pack Details
        $stmt_pack = $conn->prepare("SELECT id, price, pack_name, duration_days FROM subscription_packs WHERE id = ?");
        $stmt_pack->bind_param("i", $subscription_pack_id);
        $stmt_pack->execute();
        $pack = $stmt_pack->get_result()->fetch_assoc();
        $stmt_pack->close();
        if (!$pack) {
            header("Location: register.php?error=invalid_pack");
            exit();
        }

        // 4d. Store all data for the pending table
        $data_to_store = [
            'role' => $role,
            'username' => $username,
            'email' => $email,
            'password' => $password,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'phone' => $phone,
            'address' => $address,
            'profile_photo_path' => $profile_photo_path,
            'subscription_pack_id' => $subscription_pack_id,
            'pack_details' => $pack
        ];
        $serialized_data = serialize($data_to_store);
        $merchantTransactionId = "UCF-SUB-" . uniqid();

        // 4e. Save to 'pending_registrations' table
        $stmt_pending = $conn->prepare("INSERT INTO pending_registrations (merchant_transaction_id, registration_data) VALUES (?, ?)");
        $stmt_pending->bind_param("ss", $merchantTransactionId, $serialized_data);
        $stmt_pending->execute();
        $stmt_pending->close();

        // 4f. Initiate PhonePe Payment
        $amount_in_rupees = $pack['price'];
        $amount_in_paise = $amount_in_rupees * 100;
        $redirect_url = "https://unitedculturalforum.com/payment_status.php?txn_id=" . $merchantTransactionId;
        $callback_url = "https://unitedculturalforum.com/subscription_callback.php";

        $payload = [
            'merchantId' => $PHONEPE_MERCHANT_ID,
            'merchantTransactionId' => $merchantTransactionId,
            'merchantUserId' => $username,
            'amount' => $amount_in_paise,
            'redirectUrl' => $redirect_url,
            'redirectMode' => 'GET',
            'callbackUrl' => $callback_url, 
            'mobileNumber' => $phone,
            'paymentInstrument' => [ 'type' => 'PAY_PAGE' ],
        ];

        $base64_payload = base64_encode(json_encode($payload));
        $hash_string = $base64_payload . $PHONEPE_PAY_ENDPOINT . $PHONEPE_SALT_KEY;
        $sha256_hash = hash('sha256', $hash_string);
        $x_verify_header = $sha256_hash . '###' . $PHONEPE_SALT_INDEX;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $PHONEPE_HOST_URL . $PHONEPE_PAY_ENDPOINT);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['request' => $base64_payload]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'X-VERIFY: ' . $x_verify_header ]);
        $response = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $json_response = json_decode($response, true);

        if ($http_status == 200 && isset($json_response['success']) && $json_response['success'] === true) {
            $payment_page_url = $json_response['data']['instrumentResponse']['redirectInfo']['url'];
            header('Location: ' . $payment_page_url);
            exit();
        } else {
            throw new Exception("PhonePe initiation failed. Response: " . $response);
        }

    } else {
        // --- CUSTOMER / INSTITUTION EMAIL ACTIVATION FLOW ---
        
        // 4a. Generate activation token
        $token = bin2hex(random_bytes(32));
        $password_hash = password_hash($password, PASSWORD_DEFAULT);
        
        // 4b. Insert user as 'not verified'
        $stmt_insert = $conn->prepare("INSERT INTO users (username, email, password_hash, role, is_verified, activation_token) VALUES (?, ?, ?, ?, 0, ?)");
        $stmt_insert->bind_param("sssss", $username, $email, $password_hash, $role, $token);
        
        if (!$stmt_insert->execute()) {
            throw new Exception("Database insertion failed for user.");
        }
        $stmt_insert->close();
        
        // 4c. Send activation email
        $activation_link = "https://unitedculturalforum.com/activate.php?token=" . $token;
        $subject = "Activate Your Account - United Cultural Forum";
        $message_body = "
            <h1>Welcome to United Cultural Forum!</h1>
            <p>Hi {$username},</p>
            <p>Thank you for registering. Please click the link below to activate your account:</p>
            <p><a href='{$activation_link}'>{$activation_link}</a></p>
            <p>If you did not register, please ignore this email.</p>
        ";
        
        if (function_exists('sendEmail')) {
            sendEmail($email, $subject, $message_body);
        } else {
            // Fallback or error log if email helper isn't found
            error_log("sendEmail function not found.");
        }
        
        // 4d. Redirect to the "check email" page
        header("Location: check_email.php");
        exit();
    }

} catch (Exception $e) {
    // 5. Handle any errors
    error_log("Registration Error: " . $e->getMessage());
    header('Location: register.php?error=dberror');
    exit();
}
?>