<?php

include('includes/session.php');

include('includes/dbconnection.php');

require_once 'vendor/autoload.php';



if (isset($_POST['activate'])) {

    $student_id = $_SESSION['student_id'];

    $tabSessionID = $_GET['tab_id'];



    // --- STEP 1: Fetch Student Details ---

    $stmt = $con->prepare("SELECT studentName, email, contactno FROM students WHERE id = ?");

    $stmt->bind_param("i", $student_id);

    $stmt->execute();

    $student = $stmt->get_result()->fetch_assoc();

    $stmt->close();



    if (!$student) {
        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode("Student details not found. Please contact support."));
        exit;
    }

    if (empty($student['email'])) {
        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode("Student email is missing. Please update your profile with a valid email address."));
        exit;
    }

    if (empty($student['contactno'])) {
        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode("Phone number is missing. Please update your profile with a valid phone number."));
        exit;
    }



    $fullName = trim($student['studentName']);

    // Normalize phone to international format (+234...)
    $rawPhone = trim($student['contactno']);
    if (preg_match('/^0(\d{10})$/', $rawPhone, $m)) {
        $phone = '+234' . $m[1];
    } elseif (preg_match('/^234(\d{10})$/', $rawPhone, $m)) {
        $phone = '+234' . $m[1];
    } else {
        $phone = $rawPhone; // already +234... or other format
    }

    $originalEmail = $student['email'];



    // --- NEW: Create Unique Email for Paystack ---

    // Example: parent@gmail.com becomes parent+101@gmail.com

    $emailParts = explode('@', $originalEmail);

    $paystackEmail = $emailParts[0] . '+' . $student_id . '@' . $emailParts[1];



    $nameParts = explode(" ", $fullName, 2); 

    $firstName = $nameParts[0];

    $lastName = isset($nameParts[1]) ? $nameParts[1] : 'Student';



    // --- STEP 2: Load Paystack Key ---

    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);

    $dotenv->load();

    $secret_key = $_ENV['PAYSTACK_SECRET_KEY'];


    // --- STEP 3: Create/Update Paystack Customer ---

    

    $customer_data = [

        "email" => $paystackEmail, // Using the unique tagged email

        "first_name" => $firstName,

        "last_name" => $lastName,

        "phone" => $phone

    ];



    $ch = curl_init('https://api.paystack.co/customer');

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_POST, true);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customer_data));

    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $secret_key", "Content-Type: application/json"]);



    $cust_response = json_decode(curl_exec($ch), true);

    if (!$cust_response['status']) {

        curl_close($ch);

        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode("Paystack Customer Error: " . $cust_response['message']));

        exit;

    }



    $customer_code = $cust_response['data']['customer_code'];

    // --- STEP 3b: Update Customer to ensure phone is set ---
    $update_data = [
        "first_name" => $firstName,
        "last_name"  => $lastName,
        "phone"      => $phone
    ];

    $ch2 = curl_init("https://api.paystack.co/customer/$customer_code");
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($update_data));
    curl_setopt($ch2, CURLOPT_HTTPHEADER, ["Authorization: Bearer $secret_key", "Content-Type: application/json"]);
    $update_response = json_decode(curl_exec($ch2), true);
    curl_close($ch2);

    if (!$update_response['status']) {
        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode("Failed to update customer: " . $update_response['message']));
        exit;
    }

    // --- STEP 4: Generate Dedicated Virtual Account ---

    $account_data = [

        "customer" => $customer_code,

        "preferred_bank" => "wema-bank"

        // Note: 'name' is removed to avoid doubling names

    ];


    curl_setopt($ch, CURLOPT_URL, 'https://api.paystack.co/dedicated_account');

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($account_data));



    $acc_response = json_decode(curl_exec($ch), true);

    curl_close($ch);



    if (!$acc_response['status']) {

        header("Location: wallet_details.php?status=error&tab_id=$tabSessionID&message=" . urlencode($acc_response['message']));

        exit;

    }



    $bank_name = $acc_response['data']['bank']['name'];

    $account_no = $acc_response['data']['account_number'];

    $account_name = $acc_response['data']['account_name']; 



    // --- STEP 5: Save/Update Wallet ---

    $stmt = $con->prepare("

        INSERT INTO wallets (student_id, customer_code, account_number, bank_name, account_name) 

        VALUES (?, ?, ?, ?, ?) 

        ON DUPLICATE KEY UPDATE account_number = ?, bank_name = ?, account_name = ?

    ");



    $stmt->bind_param("isssssss", $student_id, $customer_code, $account_no, $bank_name, $account_name, $account_no, $bank_name, $account_name);



    if ($stmt->execute()) {

        $stmt->close();

        header("Location: wallet_details.php?status=success&tab_id=$tabSessionID");

        exit;

    }

}

?>