<?php
// member_mpesa_b2c.php - Member Portal B2C Payments
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Custom session initialization
if (session_status() === PHP_SESSION_NONE) {

    // Optional: Define your custom session name
    $customSessionName = 'MEMBER_PORTAL_SESSION';

    // Check if a session cookie already exists
    $hasCustomSession = isset($_COOKIE[$customSessionName]);
    $hasDefaultSession = isset($_COOKIE[session_name()]); // usually PHPSESSID

    // --- Decide which session name to use ---
    if ($hasCustomSession) {
        // Resume existing MEMBER_PORTAL_SESSION
        session_name($customSessionName);
    } elseif ($hasDefaultSession) {
        // Stick to the existing PHPSESSID
        // (no change needed)
    } else {
        // Optional: Use custom session for new logins
        session_name($customSessionName);
    }

    // --- Secure session configuration ---
    ini_set('session.cookie_secure', 1);
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_strict_mode', 1);
    ini_set('session.cookie_samesite', 'Lax');
    ini_set('session.use_only_cookies', 1);
    ini_set('session.gc_maxlifetime', 1800); // 30 mins

    // --- Start session ---
    if (ob_get_level()) ob_clean();
    session_start();

    // --- Optional debug ---
    error_log("Session started → name: " . session_name() . " | ID: " . session_id());
}

// Check if member is logged in
if (!isset($_SESSION['member_id']) || !isset($_SESSION['member_logged_in']) || $_SESSION['member_logged_in'] !== true) {
    header('Location: member_login.php');
    exit;
}

require_once './includes/config.php';
require_once './includes/audit_helper.php';
require_once './includes/sms_helper.php';
require_once './includes/logging_helper.php';
require_once './b2c/b2c_config.php';

$memberId = $_SESSION['member_id'];
$title = 'Withdraw Funds via M-Pesa';
$subTitle = 'Transfer to your M-Pesa account';

/**
 * M-Pesa B2C Integration Class - Member Version
 */
class MemberMpesaB2CIntegration {
    private $consumerKey;
    private $consumerSecret;
    private $env;
    private $baseUrl;
    private $callbackUrl;
    private $initiatorName;
    private $securityCredential;
    private $shortCode;
    private $passKey;
    private $queueTimeoutUrl;
    private $resultUrl;
    private $assetLedgerId;
    private $ledgerCode;

    public function __construct() {
        $this->consumerKey = MPESA_CONSUMER_KEY;
        $this->consumerSecret = MPESA_CONSUMER_SECRET;
        $this->env = MPESA_ENVIRONMENT;
        $this->baseUrl = $this->env === 'sandbox' 
            ? 'https://sandbox.safaricom.co.ke' 
            : 'https://api.safaricom.co.ke';
        $this->callbackUrl = MPESA_CALLBACK_URL;
        $this->initiatorName = MPESA_INITIATOR_NAME;
        $this->securityCredential = $this->generateSecurityCredential();
        $this->shortCode = MPESA_SHORTCODE;
        $this->passKey = MPESA_PASSKEY;
        $this->queueTimeoutUrl = $this->callbackUrl . '/b2c_queue_timeout.php';
        $this->resultUrl = $this->callbackUrl . '/b2c_result.php';
        $this->assetLedgerId = MPESA_ASSET_LEDGER_ID;
        $this->ledgerCode = MPESA_LEDGER_CODE;
    }

    private function generateSecurityCredential() {
        $certPath = $this->env === 'sandbox'
            ? './b2c/SandboxCertificate.cer'
            : './b2c/production_cert.cer';
        
        if (!file_exists($certPath)) {
            throw new Exception("Certificate file not found: " . $certPath);
        }
        
        $publicKey = file_get_contents($certPath);
        if (!$publicKey) {
            throw new Exception("Failed to read certificate file");
        }
        
        $encrypted = '';
        $success = openssl_public_encrypt(MPESA_INITIATOR_PASSWORD, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
        
        if (!$success) {
            throw new Exception("Failed to encrypt security credential: " . openssl_error_string());
        }
        
        return base64_encode($encrypted);
    }

    private function getAccessToken() {
        $url = $this->baseUrl . '/oauth/v1/generate?grant_type=client_credentials';
        $credentials = base64_encode($this->consumerKey . ':' . $this->consumerSecret);
        
        $headers = ['Authorization: Basic ' . $credentials];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);

        if ($status != 200) {
            throw new Exception('Failed to get access token. Status: ' . $status . ' Error: ' . $error);
        }

        $result = json_decode($response);
        if (!$result || !isset($result->access_token)) {
            throw new Exception('Invalid response from access token request');
        }
        
        return $result->access_token;
    }

    /**
     * Initiate B2C payment only
     */
    public function b2cPayment($phoneNumber, $amount, $commandID, $remarks) {
        $payload = [
            'InitiatorName' => $this->initiatorName,
            'SecurityCredential' => $this->securityCredential,
            'CommandID' => $commandID,
            'Amount' => $amount,
            'PartyA' => $this->shortCode,
            'PartyB' => $phoneNumber,
            'Remarks' => $remarks,
            'QueueTimeOutURL' => $this->queueTimeoutUrl,
            'ResultURL' => $this->resultUrl,
            'Occasion' => 'Member Withdrawal'
        ];

        $url = $this->baseUrl . '/mpesa/b2c/v1/paymentrequest';
        $response = $this->makeApiRequest($url, $payload);
        
        return [
            'ConversationID' => $response['ConversationID'] ?? '',
            'OriginatorConversationID' => $response['OriginatorConversationID'] ?? '',
            'ResponseCode' => $response['ResponseCode'] ?? '0',
            'ResponseDescription' => $response['ResponseDescription'] ?? 'Success. Request accepted for processing'
        ];
    }

    private function makeApiRequest($url, $payload) {
        $token = $this->getAccessToken();
        $headers = [
            'Authorization: Bearer ' . $token,
            'Content-Type: ' . 'application/json'
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);

        if ($status != 200) {
            throw new Exception('M-Pesa API request failed. Status: ' . $status . ' Error: ' . $error);
        }

        $result = json_decode($response, true);
        if (!$result) {
            throw new Exception('Invalid JSON response from M-Pesa API');
        }

        return $result;
    }
}

/**
 * B2C Payment Validator Class - Member Version
 */
class MemberB2CValidator {
    public static function validatePhoneNumber($phone) {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        
        if (strlen($phone) === 9 && substr($phone, 0, 1) === '7') {
            return '254' . $phone;
        } elseif (strlen($phone) === 10 && substr($phone, 0, 1) === '0') {
            return '254' . substr($phone, 1);
        } elseif (strlen($phone) === 12 && substr($phone, 0, 3) === '254') {
            return $phone;
        } else {
            return false;
        }
    }

    public static function validateAmount($amount) {
        if ($amount < 10) {
            throw new Exception("Minimum withdrawal amount is KES 10");
        }
        if ($amount > 150000) {
            throw new Exception("Maximum withdrawal amount is KES 150,000");
        }
        return true;
    }

    public static function getDisplayPhone($phone) {
        $formatted = self::validatePhoneNumber($phone);
        if ($formatted && preg_match('/^2547(\d{8})$/', $formatted, $matches)) {
            return '0' . $matches[1];
        }
        return $phone;
    }
}

/**
 * Database Wrapper Class
 */
class Database {
    private $pdo;
    private $transactionCount = 0;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function getPdo() {
        return $this->pdo;
    }

    public function fetchAll($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function fetchOne($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function execute($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute($params);
    }

    public function beginTransaction() {
        if ($this->transactionCount === 0) {
            $this->pdo->beginTransaction();
        }
        $this->transactionCount++;
        return true;
    }

    public function commit() {
        if ($this->transactionCount === 1) {
            $this->pdo->commit();
        }
        $this->transactionCount = max(0, $this->transactionCount - 1);
        return true;
    }

    public function rollBack() {
        if ($this->transactionCount === 1) {
            $this->pdo->rollBack();
        }
        $this->transactionCount = max(0, $this->transactionCount - 1);
        return true;
    }

    public function lastInsertId() {
        return $this->pdo->lastInsertId();
    }
}

/**
 * Member B2C Initiation Handler
 */
class MemberB2CInitiationHandler {
    private $db;
    private $pdo;
    private $assetLedgerId;

    public function __construct(Database $db) {
        $this->db = $db;
        $this->pdo = $db->getPdo();
        $this->assetLedgerId = MPESA_ASSET_LEDGER_ID;
    }

    /**
     * Process B2C payment initiation for member
     */
    public function processMemberB2CPayment($memberId, $amount, $phone, $remarks) {
        $required = ['amount', 'phone', 'remarks'];
        foreach ($required as $field) {
            if (empty($$field)) {
                throw new Exception("Missing required field: $field");
            }
        }

        $amount = floatval($amount);
        $accountTypeId = $this->getDefaultAccountType();
        $commandId = 'BusinessPayment'; // Default for member withdrawals

        // Validate member and account
        $this->validateMemberAccount($memberId, $accountTypeId);

        // Check sufficient balance
        if (!$this->hasSufficientBalance($memberId, $accountTypeId, $amount)) {
            $balance = $this->getMemberAvailableBalance($memberId, $accountTypeId);
            throw new Exception("Insufficient balance. Available: KES " . number_format($balance, 2));
        }

        // Reserve funds (temporary hold without reducing available balance)
        $this->reserveFunds($memberId, $accountTypeId, $amount, $memberId);

        // Initiate M-Pesa B2C payment
        $mpesaB2C = new MemberMpesaB2CIntegration();
        $mpesaResponse = $mpesaB2C->b2cPayment($phone, $amount, $commandId, $remarks);

        // Record B2C transaction as PENDING only
        $b2cRecordId = $this->recordB2CTransaction([
            'conversation_id' => $mpesaResponse['ConversationID'],
            'originator_conversation_id' => $mpesaResponse['OriginatorConversationID'],
            'command_id' => $commandId,
            'amount' => $amount,
            'phone_number' => $phone,
            'remarks' => $remarks,
            'initiator_id' => $memberId, // Using member ID as initiator
            'member_id' => $memberId,
            'transaction_status' => 'pending',
            'account_type_id' => $accountTypeId,
            'asset_ledger_id' => $this->assetLedgerId,
            'response_code' => $mpesaResponse['ResponseCode'],
            'response_description' => $mpesaResponse['ResponseDescription']
        ]);

        // Send initiation notification
        $this->sendInitiationNotification($memberId, $amount, $phone);

        return [
            'status' => 'success',
            'message' => 'Withdrawal request submitted successfully. You will receive confirmation via SMS shortly.',
            'conversation_id' => $mpesaResponse['ConversationID'],
            'record_id' => $b2cRecordId
        ];
    }

    /**
     * Reserve funds temporarily without reducing available balance
     */
    private function reserveFunds($memberId, $accountTypeId, $amount, $initiatorId) {
        $this->db->beginTransaction();
        
        try {
            // Check and reserve funds in single atomic operation
            $stmt = $this->pdo->prepare(
                "UPDATE member_accounts 
                 SET reserved_balance = COALESCE(reserved_balance, 0) + ?,
                     updated_at = NOW()
                 WHERE member_id = ? AND account_type_id = ? 
                 AND available_balance >= ?"
            );
            
            $result = $stmt->execute([$amount, $memberId, $accountTypeId, $amount]);
            $affectedRows = $stmt->rowCount();
            
            if ($affectedRows === 0) {
                $this->db->rollBack();
                $balance = $this->getMemberAvailableBalance($memberId, $accountTypeId);
                throw new Exception("Insufficient available balance. Available: KES " . number_format($balance, 2));
            }

            // Log the reservation
            $this->db->execute(
                "INSERT INTO fund_reservations (member_id, account_type_id, amount, reserved_by, created_at) 
                 VALUES (?, ?, ?, ?, NOW())",
                [$memberId, $accountTypeId, $amount, $initiatorId]
            );

            $this->db->commit();
            return true;
            
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    /**
     * Record B2C transaction as PENDING
     */
    private function recordB2CTransaction($data) {
        $this->db->execute(
            "INSERT INTO b2c_transactions (
                conversation_id,
                originator_conversation_id,
                command_id,
                amount,
                phone_number,
                remarks,
                transaction_status,
                initiator_id,
                member_id,
                account_type_id,
                asset_ledger_id,
                response_code,
                response_description,
                created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())",
            [
                $data['conversation_id'],
                $data['originator_conversation_id'],
                $data['command_id'],
                $data['amount'],
                $data['phone_number'],
                $data['remarks'],
                'pending',
                $data['initiator_id'],
                $data['member_id'],
                $data['account_type_id'],
                $data['asset_ledger_id'],
                $data['response_code'] ?? '',
                $data['response_description'] ?? ''
            ]
        );
        return $this->db->lastInsertId();
    }

    /**
     * Send initiation notification only
     */
    private function sendInitiationNotification($memberId, $amount, $phone) {
        try {
            $member = $this->db->fetchOne(
                "SELECT first_name, last_name, phone_number FROM members WHERE id = ?",
                [$memberId]
            );

            if ($member) {
                $message = "Dear {$member['first_name']}, your withdrawal request of KES " . 
                          number_format($amount, 2) . " has been received and is being processed. " .
                          "You will receive a confirmation message shortly.";
                
                $smsResult = sendSms($this->pdo, $phone, $message, null, true);
                
                if ($smsResult['type'] === 'error') {
                    error_log("Failed to send initiation SMS: " . $smsResult['message']);
                }
            }
        } catch (Exception $e) {
            error_log("Failed to send initiation notification: " . $e->getMessage());
        }
    }

    private function validateMemberAccount($memberId, $accountTypeId) {
        $account = $this->db->fetchOne(
            "SELECT 1 FROM member_accounts WHERE member_id = ? AND account_type_id = ?",
            [$memberId, $accountTypeId]
        );
        
        if (!$account) {
            throw new Exception("Member account not found");
        }
    }

    private function hasSufficientBalance($memberId, $accountTypeId, $amount) {
        $balance = $this->getMemberAvailableBalance($memberId, $accountTypeId);
        return $balance >= $amount;
    }

    public function getMemberAvailableBalance($memberId, $accountTypeId) {
        $result = $this->db->fetchOne(
            "SELECT available_balance FROM member_accounts WHERE member_id = ? AND account_type_id = ?",
            [$memberId, $accountTypeId]
        );
        
        return $result ? floatval($result['available_balance']) : 0;
    }

    public function getMemberReservedBalance($memberId, $accountTypeId) {
        $result = $this->db->fetchOne(
            "SELECT reserved_balance FROM member_accounts WHERE member_id = ? AND account_type_id = ?",
            [$memberId, $accountTypeId]
        );
        
        return $result ? floatval($result['reserved_balance']) : 0;
    }

    public function getMemberBalanceInfo($memberId) {
        $accountTypeId = $this->getDefaultAccountType();
        return $this->db->fetchOne("
            SELECT 
                ma.available_balance,
                COALESCE(ma.reserved_balance, 0) as reserved_balance,
                ma.running_balance,
                at.account_name,
                (ma.available_balance - COALESCE(ma.reserved_balance, 0)) as net_available_balance
            FROM member_accounts ma
            INNER JOIN account_types at ON ma.account_type_id = at.id
            WHERE ma.member_id = ? AND ma.account_type_id = ?
        ", [$memberId, $accountTypeId]);
    }

    public function getMemberDetails($memberId) {
        return $this->db->fetchOne("
            SELECT first_name, last_name, personal_number, phone_number 
            FROM members 
            WHERE id = ? AND status = 'active'
        ", [$memberId]);
    }

    private function getDefaultAccountType() {
        $config = $this->db->fetchOne(
            "SELECT config_value FROM system_config WHERE config_key = 'default_withdrawal_account_type'"
        );
        
        if ($config) {
            return intval($config['config_value']);
        }
        
        $accountType = $this->db->fetchOne(
            "SELECT id FROM account_types WHERE account_name LIKE '%savings%' OR account_name LIKE '%Savings%' LIMIT 1"
        );
        
        if ($accountType) {
            return $accountType['id'];
        }
        
        throw new Exception("No default account type configured for withdrawals");
    }

    public function getMemberRecentTransactions($memberId, $limit = 10) {
        $limit = intval($limit);
        return $this->db->fetchAll("
            SELECT bt.*, at.account_name
            FROM b2c_transactions bt
            LEFT JOIN account_types at ON bt.account_type_id = at.id
            WHERE bt.member_id = ?
            ORDER BY bt.created_at DESC 
            LIMIT $limit
        ", [$memberId]);
    }

    public function getMemberTransactionStats($memberId) {
        $stats = [];
        
        $result = $this->db->fetchOne("
            SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as total 
            FROM b2c_transactions 
            WHERE member_id = ? AND transaction_status = 'completed'
        ", [$memberId]);
        $stats['total_processed'] = $result ? $result : ['count' => 0, 'total' => 0];
        
        $result = $this->db->fetchOne("
            SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as total 
            FROM b2c_transactions 
            WHERE member_id = ? AND transaction_status = 'pending'
        ", [$memberId]);
        $stats['pending'] = $result ? $result : ['count' => 0, 'total' => 0];
        
        $result = $this->db->fetchOne("
            SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as total 
            FROM b2c_transactions 
            WHERE member_id = ? AND transaction_status = 'failed'
        ", [$memberId]);
        $stats['failed'] = $result ? $result : ['count' => 0, 'total' => 0];
        
        return $stats;
    }
}

// Initialize classes
$db = new Database($pdo);
$memberB2CHandler = new MemberB2CInitiationHandler($db);

// Handle AJAX requests for initiating payments only
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: ' . 'application/json');
    
    try {
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            throw new Exception("Invalid CSRF token");
        }

        if ($_POST['action'] === 'withdraw_funds') {
            $required = ['amount', 'phone', 'remarks'];
            foreach ($required as $field) {
                if (empty($_POST[$field])) {
                    throw new Exception("$field is required");
                }
            }
            
            $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
            MemberB2CValidator::validateAmount($amount);
            
            $phone = MemberB2CValidator::validatePhoneNumber($_POST['phone']);
            if (!$phone) {
                throw new Exception("Invalid phone number format");
            }
            
            $response = $memberB2CHandler->processMemberB2CPayment(
                $memberId,
                $amount,
                $phone,
                $_POST['remarks']
            );
            
            echo json_encode([
                'status' => 'success',
                'message' => 'Withdrawal request submitted successfully. You will receive confirmation via SMS shortly.',
                'data' => $response
            ]);
            
        } elseif ($_POST['action'] === 'get_balance') {
            $balanceInfo = $memberB2CHandler->getMemberBalanceInfo($memberId);
            
            echo json_encode([
                'status' => 'success',
                'balance' => $balanceInfo['net_available_balance'],
                'available_balance' => $balanceInfo['available_balance'],
                'reserved_balance' => $balanceInfo['reserved_balance'],
                'account_name' => $balanceInfo['account_name']
            ]);
            
        } else {
            throw new Exception("Invalid action");
        }
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
    exit;
}

// Fetch data for the member
$memberDetails = $memberB2CHandler->getMemberDetails($memberId);
$balanceInfo = $memberB2CHandler->getMemberBalanceInfo($memberId);
$recentTransactions = $memberB2CHandler->getMemberRecentTransactions($memberId, 5);
$stats = $memberB2CHandler->getMemberTransactionStats($memberId);

// Generate CSRF token if not set
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($title); ?> - Member Portal</title>
    <link rel="stylesheet" href="./assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="./assets/css/toastr.min.css">
    <link rel="stylesheet" href="./assets/css/font-awesome.min.css">
    <link rel="stylesheet" href="./assets/css/styles.css">
    <style>
        .balance-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .stats-card {
            transition: transform 0.2s;
            border: none;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            color: white;
            flex-direction: column;
        }
        
        .transaction-status-completed { color: #28a745; }
        .transaction-status-pending { color: #ffc107; }
        .transaction-status-failed { color: #dc3545; }
        
        .withdrawal-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #007bff;
            margin-bottom: 20px;
        }
        
        .session-info {
            background: #e8f5e8;
            padding: 10px 15px;
            border-radius: 5px;
            border-left: 4px solid #28a745;
            margin-bottom: 15px;
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p class="mt-2" id="loadingText">Processing withdrawal request...</p>
    </div>
    
    <!-- Session Info (for debugging) -->
    <?php if (MPESA_ENVIRONMENT === 'sandbox'): ?>
    <div class="session-info">
        <small>
            <strong>Session:</strong> <?php echo session_name(); ?> | 
            <strong>Environment:</strong> <?php echo MPESA_ENVIRONMENT; ?> | 
            <strong>Member:</strong> <?php echo htmlspecialchars($memberDetails['first_name'] . ' ' . $memberDetails['last_name']); ?>
        </small>
    </div>
    <?php endif; ?>

    <!-- Member Header -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="member_dashboard.php">
                <i class="fa fa-university"></i> SACCO Member Portal
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="member_dashboard.php">Dashboard</a>
                <a class="nav-link active" href="member_mpesa_b2c.php">Withdraw Funds</a>
                <a class="nav-link" href="member_transactions.php">Transactions</a>
                <a class="nav-link" href="member_logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h2 class="mb-1"><?php echo htmlspecialchars($title); ?></h2>
                        <p class="text-muted mb-0"><?php echo htmlspecialchars($subTitle); ?></p>
                    </div>
                    <div class="text-end">
                        <span class="text-muted">Welcome,</span>
                        <strong><?php echo htmlspecialchars($memberDetails['first_name'] . ' ' . $memberDetails['last_name']); ?></strong>
                    </div>
                </div>
            </div>
        </div>

        <!-- Balance Card -->
        <div class="row">
            <div class="col-lg-12">
                <div class="balance-card">
                    <div class="row">
                        <div class="col-md-6">
                            <h5 class="mb-1">Available Balance</h5>
                            <h2 class="mb-0">KES <?php echo number_format($balanceInfo['net_available_balance'], 2); ?></h2>
                            <small>
                                <?php echo htmlspecialchars($balanceInfo['account_name']); ?> Account
                                <?php if ($balanceInfo['reserved_balance'] > 0): ?>
                                    <br><span class="opacity-75">KES <?php echo number_format($balanceInfo['reserved_balance'], 2); ?> reserved</span>
                                <?php endif; ?>
                            </small>
                        </div>
                        <div class="col-md-6 text-end">
                            <div class="mt-3">
                                <small class="opacity-75">Member ID: <?php echo htmlspecialchars($memberDetails['personal_number']); ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <div class="text-success mb-2">
                            <i class="fa fa-check-circle fa-2x"></i>
                        </div>
                        <h4 class="mb-1"><?php echo $stats['total_processed']['count']; ?></h4>
                        <p class="text-muted mb-0">Completed</p>
                        <small class="text-muted">KES <?php echo number_format($stats['total_processed']['total'], 2); ?></small>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <div class="text-warning mb-2">
                            <i class="fa fa-clock-o fa-2x"></i>
                        </div>
                        <h4 class="mb-1"><?php echo $stats['pending']['count']; ?></h4>
                        <p class="text-muted mb-0">Pending</p>
                        <small class="text-muted">KES <?php echo number_format($stats['pending']['total'], 2); ?></small>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <div class="text-danger mb-2">
                            <i class="fa fa-times-circle fa-2x"></i>
                        </div>
                        <h4 class="mb-1"><?php echo $stats['failed']['count']; ?></h4>
                        <p class="text-muted mb-0">Failed</p>
                        <small class="text-muted">KES <?php echo number_format($stats['failed']['total'], 2); ?></small>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stats-card">
                    <div class="card-body text-center">
                        <div class="text-primary mb-2">
                            <i class="fa fa-phone fa-2x"></i>
                        </div>
                        <h6 class="mb-1"><?php echo MemberB2CValidator::getDisplayPhone($memberDetails['phone_number']); ?></h6>
                        <p class="text-muted mb-0">Registered Phone</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0"><i class="fa fa-money"></i> Withdraw Funds</h5>
                    </div>
                    <div class="card-body">
                        <!-- Withdrawal Information -->
                        <div class="withdrawal-info">
                            <h6><i class="fa fa-info-circle"></i> Important Information</h6>
                            <ul class="mb-0">
                                <li>Minimum withdrawal: <strong>KES 10</strong></li>
                                <li>Maximum withdrawal: <strong>KES 150,000</strong></li>
                                <li>Funds will be sent to your M-Pesa account</li>
                                <li>Processing time: 1-5 minutes</li>
                                <li>Ensure your phone number is registered with M-Pesa</li>
                            </ul>
                        </div>

                        <form method="post" id="withdrawalForm" autocomplete="off">
                            <input type="hidden" name="action" value="withdraw_funds">
                            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="amount" class="form-label">Amount to Withdraw (KES) *</label>
                                    <div class="input-group">
                                        <span class="input-group-text">KES</span>
                                        <input type="number" class="form-control" id="amount" name="amount" 
                                               min="10" max="150000" step="1" required
                                               placeholder="Enter amount">
                                    </div>
                                    <small class="text-muted">Min: KES 10, Max: KES 150,000</small>
                                </div>
                                <div class="col-md-6">
                                    <label for="phone" class="form-label">M-Pesa Phone Number *</label>
                                    <input type="text" class="form-control" id="phone" name="phone" 
                                           required 
                                           value="<?php echo MemberB2CValidator::getDisplayPhone($memberDetails['phone_number']); ?>"
                                           placeholder="0727576400">
                                    <small class="text-muted">Enter your M-Pesa registered number</small>
                                </div>
                            </div>
                            
                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="remarks" class="form-label">Remarks *</label>
                                    <textarea class="form-control" id="remarks" name="remarks" rows="2" 
                                              placeholder="e.g., Emergency funds, School fees, etc." required></textarea>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg" id="withdrawBtn">
                                    <i class="fa fa-paper-plane"></i> Request Withdrawal
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <!-- Recent Transactions -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="fa fa-history"></i> Recent Withdrawals</h5>
                    </div>
                    <div class="card-body">
                        <div class="list-group list-group-flush">
                            <?php foreach ($recentTransactions as $transaction): 
                                $statusClass = 'transaction-status-' . $transaction['transaction_status'];
                            ?>
                                <div class="list-group-item px-0">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">KES <?php echo number_format($transaction['amount'], 2); ?></h6>
                                        <small class="<?php echo $statusClass; ?>">
                                            <?php echo ucfirst($transaction['transaction_status']); ?>
                                        </small>
                                    </div>
                                    <p class="mb-1 small"><?php echo MemberB2CValidator::getDisplayPhone($transaction['phone_number']); ?></p>
                                    <small class="text-muted">
                                        <?php echo date('M j, H:i', strtotime($transaction['created_at'])); ?>
                                        <?php if ($transaction['remarks']): ?>
                                            • <?php echo htmlspecialchars($transaction['remarks']); ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                            <?php endforeach; ?>
                            
                            <?php if (empty($recentTransactions)): ?>
                                <div class="text-center py-4 text-muted">
                                    <i class="fa fa-history fa-2x mb-2"></i>
                                    <p>No withdrawal history</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="./assets/js/jquery-3.6.0.min.js"></script>
    <script src="./assets/js/bootstrap.bundle.min.js"></script>
    <script src="./assets/js/toastr.min.js"></script>
    <script>
        $(document).ready(function() {
            toastr.options = {
                "closeButton": true,
                "progressBar": true,
                "positionClass": "toast-top-right",
                "timeOut": "5000"
            };
            
            // Refresh balance on page load
            refreshBalance();
            
            // Withdrawal form submission
            $('#withdrawalForm').submit(function(e) {
                e.preventDefault();
                
                const amount = parseFloat($('#amount').val());
                const phone = $('#phone').val();
                const availableBalance = parseFloat('<?php echo $balanceInfo["net_available_balance"]; ?>');
                
                if (amount < 10 || amount > 150000) {
                    toastr.error('Amount must be between KES 10 and KES 150,000');
                    return false;
                }
                
                if (amount > availableBalance) {
                    toastr.error('Insufficient balance. Available: KES ' + availableBalance.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
                    return false;
                }
                
                if (!phone.match(/^(07|01|2547|2541)\d{8}$/)) {
                    toastr.error('Please enter a valid M-Pesa phone number');
                    return false;
                }
                
                // Show loading
                $('#loadingOverlay').show();
                $('#withdrawBtn').prop('disabled', true);
                $('#loadingText').text('Processing withdrawal request...');
                
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(response) {
                        $('#loadingOverlay').hide();
                        $('#withdrawBtn').prop('disabled', false);
                        
                        if (response.status === 'success') {
                            toastr.success(response.message, 'Success');
                            $('#withdrawalForm')[0].reset();
                            $('#phone').val('<?php echo MemberB2CValidator::getDisplayPhone($memberDetails["phone_number"]); ?>');
                            
                            // Refresh page after successful transaction
                            setTimeout(() => location.reload(), 2000);
                        } else {
                            toastr.error(response.message, 'Error');
                        }
                    },
                    error: function(xhr) {
                        $('#loadingOverlay').hide();
                        $('#withdrawBtn').prop('disabled', false);
                        
                        try {
                            const response = JSON.parse(xhr.responseText);
                            toastr.error(response.message, 'Error');
                        } catch (e) {
                            toastr.error('An unexpected error occurred', 'Error');
                        }
                    }
                });
            });
            
            // Refresh balance function
            function refreshBalance() {
                $.ajax({
                    url: window.location.href,
                    type: 'POST',
                    data: {
                        action: 'get_balance',
                        csrf_token: '<?php echo $_SESSION['csrf_token']; ?>'
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            // Update balance display if needed
                            console.log('Balance refreshed:', response.balance);
                        }
                    },
                    error: function(xhr) {
                        console.log('Failed to refresh balance');
                    }
                });
            }
            
            // Auto-refresh balance every 30 seconds
            setInterval(refreshBalance, 30000);
        });
    </script>
</body>
</html>