1import{X as G,a as X,c as J,o as Z,p as L,k as u,V as W,r as g,j as e,w as oe,a0 as ce,B as _,x as de,y as me,z as ue,C as B,d as V,e as D,A as z,f as R,L as F,I as H,a6 as O,a7 as Y,D as he}from"./index-IxvR3ybE.js";import{S as we,a as xe,b as fe,c as ge,d as pe}from"./select-C66k4zpo.js";import{C as je}from"./credit-card-CqkMcI0L.js";import{L as A}from"./loader-circle-Dv3Jv63Q.js";import{C as ve}from"./circle-check-B7O452vI.js";import{E as ye}from"./EventSelector-Bpv922Gw.js";import{W as q}from"./wallet-B8J5ed_H.js";import{D as be}from"./dollar-sign-BDH68OUX.js";import{T as Ne}from"./trending-up-NAysCqrH.js";import"./index-BdQq_4o_.js";import"./index-PCA-xeVB.js";import"./chevron-up-Kie37_ZB.js";import"./plus-ByP2IBiw.js";const _e=()=>{const{selectedEventId:a}=G(),{currentUser:t}=X(),{toast:d}=J(),m=Z(),{data:f=[],isLoading:k}=L({queryKey:["withdrawal-history",t==null?void 0:t.id,a],queryFn:async()=>{if(!(t!=null&&t.id)||!a)return[];console.log("Fetching withdrawal history for user:",t.id,"event:",a);const{data:s}=await u.from("admin_wallets").select("id").eq("admin_id",t.id).eq("event_id",a).single();if(!s)return console.log("No wallet found for user"),[];const{data:i,error:c}=await u.from("withdrawal_requests").select("*").eq("admin_wallet_id",s.id).order("created_at",{ascending:!1});if(c)throw console.error("Error fetching withdrawal history:",c),c;return console.log("Withdrawal history fetched:",i==null?void 0:i.length,"records"),i},enabled:!!(t!=null&&t.id)&&!!a}),{data:b=[],isLoading:y}=L({queryKey:["nigerian-banks"],queryFn:async()=>{var c;console.log("Fetching Nigerian banks...");const{data:s,error:i}=await u.functions.invoke("process-withdrawal",{body:{action:"get_banks"}});if(i)throw console.error("Error fetching banks:",i),i;return console.log("Banks fetched successfully:",(c=s==null?void 0:s.data)==null?void 0:c.length,"banks"),(s==null?void 0:s.data)||[]},staleTime:1e3*60*60}),N=W({mutationFn:async({accountNumber:s,bankCode:i,bankName:c})=>{if(!a)throw new Error("No event selected");console.log("Verifying account:",{accountNumber:s,bankCode:i,bankName:c});const{data:r,error:h}=await u.functions.invoke("process-withdrawal",{body:{action:"verify_account",account_number:s,bank_code:i,bank_name:c,event_id:a}});if(h)throw console.error("Account verification error:",h),new Error(h.message||"Failed to verify account");if(!(r!=null&&r.success))throw console.error("Account verification failed:",r),new Error((r==null?void 0:r.message)||"Account verification failed");return console.log("Account verified successfully:",r),r},onSuccess:s=>{m.invalidateQueries({queryKey:["admin-wallet"]}),d({title:"Success",description:`Account verified: ${s.account_name}`})},onError:s=>{console.error("Account verification failed:",s),d({title:"Verification Failed",description:s.message||"Failed to verify bank account",variant:"destructive"})}}),l=W({mutationFn:async({accountName:s,accountNumber:i,bankCode:c})=>{if(!a)throw new Error("No event selected");console.log("Creating recipient:",{accountName:s,accountNumber:i,bankCode:c});const{data:r,error:h}=await u.functions.invoke("process-withdrawal",{body:{action:"create_recipient",account_name:s,account_number:i,bank_code:c,event_id:a}});if(h)throw console.error("Recipient creation error:",h),new Error(h.message||"Failed to create recipient");if(!(r!=null&&r.success))throw console.error("Recipient creation failed:",r),new Error((r==null?void 0:r.message)||"Failed to create recipient");return console.log("Recipient created successfully:",r),r},onSuccess:s=>{m.invalidateQueries({queryKey:["admin-wallet"]}),d({title:"Success",description:"Bank recipient created successfully"})},onError:s=>{console.error("Recipient creation failed:",s),d({title:"Error",description:s.message||"Failed to create recipient",variant:"destructive"})}}),o=W({mutationFn:async({walletId:s,amount:i,bankName:c,accountNumber:r,accountName:h,recipientCode:j,currentBalance:C,totalWithdrawn:w})=>{if(console.log("Initiating withdrawal:",{walletId:s,amount:i,bankName:c,accountNumber:r,accountName:h,currentBalance:C,totalWithdrawn:w}),i<=0)throw new Error("Withdrawal amount must be greater than zero");if(i>C)throw new Error("Insufficient balance for withdrawal");if(i<100)throw new Error("Minimum withdrawal amount is â¦100");const{data:x,error:p}=await u.functions.invoke("process-withdrawal",{body:{action:"initiate_transfer",wallet_id:s,amount:i,bank_name:c,account_number:r,account_name:h,recipient_code:j,new_balance:C-i,total_withdrawn:w+i}});if(p)throw console.error("Withdrawal initiation error:",p),new Error(p.message||"Failed to process withdrawal");if(!(x!=null&&x.success))throw console.error("Withdrawal initiation failed:",x),new Error((x==null?void 0:x.error)||"Withdrawal failed");return console.log("Withdrawal initiated successfully:",x),x},onSuccess:s=>
1{m.invalidateQueries({queryKey:["admin-wallet"]}),m.invalidateQueries({queryKey:["withdrawal-history"]}),d({title:"Withdrawal Initiated",description:s.message||"Your withdrawal request has been processed"})},onError:s=>{console.error("Withdrawal failed:",s),d({title:"Withdrawal Failed",description:s.message||"Failed to process withdrawal",variant:"destructive"})}});return{withdrawalHistory:f,isLoadingHistory:k,banks:b,isLoadingBanks:y,verifyAccount:N,createRecipient:l,initiateWithdrawal:o,isVerifyingAccount:N.isPending,isCreatingRecipient:l.isPending,isInitiatingWithdrawal:o.isPending}},ke=({walletId:a,availableBalance:t,totalWithdrawn:d,bankName:m,accountNumber:f,accountName:k,recipientCode:b,isBankVerified:y})=>{const[N,l]=g.useState(!1),[o,s]=g.useState("bank"),[i,c]=g.useState(f||""),[r,h]=g.useState(""),[j,C]=g.useState(m||""),[w,x]=g.useState(k||""),[p,U]=g.useState(b||""),[S,I]=g.useState(""),[T,K]=g.useState(y||!1),{banks:Q,isLoadingBanks:ee,verifyAccount:ae,createRecipient:te,initiateWithdrawal:se,isVerifyingAccount:M,isCreatingRecipient:P,isInitiatingWithdrawal:$}=_e(),ie=async()=>{if(!(!i||!r||!j))try{console.log("Verifying bank account:",{accountNumber:i,selectedBankCode:r,selectedBankName:j});const n=await ae.mutateAsync({accountNumber:i,bankCode:r,bankName:j});console.log("Bank verification result:",n),n.success&&n.account_name&&(x(n.account_name),K(!0),console.log("Account verified successfully:",n.account_name))}catch(n){console.error("Bank verification failed:",n)}},ne=async()=>{if(!(!w||!i||!r))try{console.log("Creating recipient:",{verifiedAccountName:w,accountNumber:i,selectedBankCode:r});const n=await te.mutateAsync({accountName:w,accountNumber:i,bankCode:r});console.log("Recipient creation result:",n),n.success&&n.recipient_code&&(U(n.recipient_code),s("amount"),console.log("Recipient created successfully:",n.recipient_code))}catch(n){console.error("Recipient creation failed:",n)}},re=async()=>{const n=parseFloat(S);if(!(!n||n<=0||!p||!w))try{console.log("Processing withdrawal:",{walletId:a,amount:n,selectedBankName:j,accountNumber:i,verifiedAccountName:w,recipientCode:p,availableBalance:t,totalWithdrawn:d}),await se.mutateAsync({walletId:a,amount:n,bankName:j,accountNumber:i,accountName:w,recipientCode:p,currentBalance:t,totalWithdrawn:d}),l(!1),s("bank"),I(""),console.log("Withdrawal completed successfully")}catch(v){console.error("Withdrawal failed:",v)}},E=t>0&&t>=10;return e.jsxs(oe,{open:N,onOpenChange:l,children:[e.jsx(ce,{asChild:!0,children:e.jsxs(_,{disabled:!E,className:"w-full",title:E?"Click to withdraw funds":t<10?"Minimum withdrawal amount is â¦10":"No funds available for withdrawal",onClick:()=>{console.log("Withdrawal button clicked:",{canWithdraw:E,availableBalance:t,isBankVerified:y}),s(y&&b?"amount":"bank")},children:[e.jsx(je,{className:"w-4 h-4 mr-2"}),E?"Withdraw Funds":t<10?"Insufficient Balance":"No Funds Available"]})}),e.jsxs(de,{className:"sm:max-w-md",children:[e.jsx(me,{children:e.jsx(ue,{children:"Withdraw Funds"})}),o==="bank"&&e.jsx("div",{className:"space-y-4",children:e.jsxs(B,{children:[e.jsxs(V,{children:[e.jsx(D,{className:"text-sm",children:"Bank Account Setup"}),e.jsx(z,{children:"Verify your bank account to enable withdrawals"})]}),e.jsxs(R,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(F,{htmlFor:"bank",children:"Select Bank"}),e.jsxs(we,{value:r,onValueChange:n=>{h(n);const v=Q.find(le=>le.code===n);C((v==null?void 0:v.name)||""),console.log("Bank selected:",{code:n,name:v==null?void 0:v.name})},children:[e.jsx(xe,{children:e.jsx(fe,{placeholder:"Choose your bank"})}),e.jsx(ge,{children:ee?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(A,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"ml-2",children:"Loading banks..."})]}):Q.map(n=>e.jsx(pe,{value:n.code,children:n.name},n.code))})]})]}),e.jsxs("div",{children:[e.jsx(F,{htmlFor:"account-number",children:"Account Number"}),e.jsx(H,{id:"account-number",value:i,onChange:n=>{c(n.target.value),K(!1),x("")},placeholder:"Enter your account number",maxLength:10})]}),T?e.jsxs(O,{children:[e.jsx(ve,{className:"h-4 w-4"}),e.jsxs(Y,{children:["Account verified: ",e.jsx("strong",{children:w})]})]}):e.jsx(_,{onClick:ie,disabled:!i||!r||M,className:"w-full",children:M?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"w-4 h-4 mr-2 animate-spin"}),"Verifying..."]}):"Verify Account"}),T&&!p&&e.jsx(_,{onClick:ne,disabled:P,className:"w-full",children:P?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"w-4 h-4 mr-2 animate-spin"}),"Setting up..."]}):"Setup Withdrawal"}),p&&e.jsx(_,{onClick:()=>s("amount"),className:"w-full",children:"Continue to Withdrawal"})]})]})}),o==="amount"&&e.jsx("div",{className:"space-y-4",children:e.jsxs(B,{children:[e.jsxs(V,{children:[e.jsx(D,{className:"text-sm",children:"Withdrawal Amount"}
1),e.jsxs(z,{children:["Available Balance: â¦",t.toLocaleString()]})]}),e.jsxs(R,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(F,{htmlFor:"amount",children:"Amount (â¦)"}),e.jsx(H,{id:"amount",type:"number",value:S,onChange:n=>I(n.target.value),placeholder:"Enter amount to withdraw",min:"10",max:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Minimum withdrawal: â¦10"})]}),w&&e.jsx(O,{children:e.jsxs(Y,{children:["Withdrawing to: ",e.jsx("strong",{children:w})," (",j,")"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_,{variant:"outline",onClick:()=>s("bank"),className:"flex-1",children:"Back"}),e.jsx(_,{onClick:re,disabled:!S||parseFloat(S)<10||parseFloat(S)>t||$,className:"flex-1",children:$?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"w-4 h-4 mr-2 animate-spin"}),"Processing..."]}):"Withdraw"})]})]})]})})]})]})},Ce=()=>{const{selectedEventId:a}=G(),{currentUser:t}=X(),{toast:d}=J(),m=Z(),{data:f,isLoading:k,error:b}=L({queryKey:["admin-wallet",t==null?void 0:t.id,a],queryFn:async()=>{if(!(t!=null&&t.id)||!a)return null;console.log("Fetching wallet for admin:",t.id,"event:",a);const{data:l,error:o}=await u.from("admin_wallets").select("*").eq("admin_id",t.id).eq("event_id",a).single();if(o&&o.code!=="PGRST116")throw console.error("Error fetching wallet:",o),o;return console.log("Wallet fetched:",l),l},enabled:!!(t!=null&&t.id)&&!!a,refetchInterval:3e4});g.useEffect(()=>{if(!(t!=null&&t.id)||!a)return;console.log("Setting up real-time subscription for wallet updates");const l=u.channel("admin-wallet-changes").on("postgres_changes",{event:"*",schema:"public",table:"admin_wallets",filter:`admin_id=eq.${t.id}`},o=>{console.log("Wallet updated:",o),m.invalidateQueries({queryKey:["admin-wallet"]})}).subscribe();return()=>{console.log("Cleaning up wallet subscription"),u.removeChannel(l)}},[t==null?void 0:t.id,a,m]),g.useEffect(()=>{if(!(t!=null&&t.id)||!a)return;console.log("Setting up real-time subscription for ticket purchases");const l=u.channel("ticket-purchase-changes").on("postgres_changes",{event:"INSERT",schema:"public",table:"event_tickets",filter:`event_id=eq.${a}`},o=>{console.log("New ticket purchased:",o),m.invalidateQueries({queryKey:["admin-wallet"]})}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"event_tickets",filter:`event_id=eq.${a}`},o=>{var s,i;console.log("Ticket updated:",o),((s=o.new)==null?void 0:s.payment_status)==="completed"&&((i=o.old)==null?void 0:i.payment_status)!=="completed"&&m.invalidateQueries({queryKey:["admin-wallet"]})}).subscribe();return()=>{console.log("Cleaning up ticket subscription"),u.removeChannel(l)}},[t==null?void 0:t.id,a,m]);const y=W({mutationFn:async()=>{if(!(t!=null&&t.id)||!a)throw new Error("Missing required data");console.log("Creating wallet for admin:",t.id,"event:",a);const{data:l,error:o}=await u.from("admin_wallets").insert({admin_id:t.id,event_id:a,available_balance:0,total_earnings:0,withdrawn_amount:0,minimum_payout_amount:10}).select().single();if(o)throw console.error("Error creating wallet:",o),o;return console.log("Wallet created successfully:",l),l},onSuccess:()=>{m.invalidateQueries({queryKey:["admin-wallet"]}),d({title:"Success",description:"Wallet created successfully"})},onError:l=>{console.error("Failed to create wallet:",l),d({title:"Error",description:"Failed to create wallet: "+l.message,variant:"destructive"})}}),N=W({mutationFn:async l=>{if(!f||l>f.available_balance)throw new Error("Insufficient balance");console.log("Legacy withdrawal - amount:",l);const{data:o,error:s}=await u.from("admin_wallets").update({available_balance:f.available_balance-l,withdrawn_amount:f.withdrawn_amount+l,last_payout_at:new Date().toISOString()}).eq("id",f.id).select().single();if(s)throw console.error("Error in legacy withdrawal:",s),s;return console.log("Legacy withdrawal successful:",o),o},onSuccess:()=>{m.invalidateQueries({queryKey:["admin-wallet"]}),d({title:"Success",description:"Withdrawal successful"})},onError:l=>{console.error("Legacy withdrawal failed:",l),d({title:"Error",description:"Withdrawal failed: "+l.message,variant:"destructive"})}});return{wallet:f,isLoading:k,error:b,createWallet:y,withdrawFunds:N,hasWallet:!!f}};function Ke(){const{wallet:a,isLoading:t}=Ce();return t?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"container mx-auto px-4 py-6 max-w-7xl",children:[e.jsxs("div",{className:"flex flex-col space-y-6 mb-8",children:[e.jsxs("div",{className:"flex items-center space-x-4",children:[e.jsx("div",{className:"flex items-center justify-center w-12 h-12 bg-primary rounded-2xl",children:e.jsx(q,{className:"h-6 w-6 text-primary-foreground"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold tracking-tight",children:"Wallet Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your earnings and withdrawals"})]})]}),e.jsx(ye,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(be,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Earnings"})]}),e.jsxs("div",{className:"text-2xl font-bold text-green-600",children:["â¦",((a==null?void 0:a.total_earnings)||0).toLocaleStr
1ing()]})]}),e.jsxs("div",{className:"bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ne,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Available Balance"})]}),e.jsxs("div",{className:"text-2xl font-bold text-blue-600",children:["â¦",((a==null?void 0:a.available_balance)||0).toLocaleString()]})]}),e.jsxs("div",{className:"bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(he,{className:"h-5 w-5 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Withdrawn"})]}),e.jsxs("div",{className:"text-2xl font-bold text-purple-600",children:["â¦",((a==null?void 0:a.withdrawn_amount)||0).toLocaleString()]})]})]})]}),e.jsx("div",{className:"space-y-8",children:e.jsxs(B,{className:"rounded-xl border-0 shadow-md",children:[e.jsx(V,{children:e.jsxs(D,{className:"flex items-center gap-2",children:[e.jsx(q,{className:"h-5 w-5 text-primary"}),"Wallet Details"]})}),e.jsx(R,{children:a?e.jsxs("div",{className:"space-y-6",children:[a.bank_name&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Bank Details"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Bank:"})," ",a.bank_name]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Account:"})," ",a.account_number]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Name:"})," ",a.account_name]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Status"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Verification:"}),e.jsx("span",{className:`ml-2 px-2 py-1 rounded text-xs ${a.is_bank_verified?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:a.is_bank_verified?"Verified":"Pending"})]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Minimum Payout:"}),"â¦",(a.minimum_payout_amount||1e3).toLocaleString()]})]})]})]}),a.available_balance>0&&a.available_balance<(a.minimum_payout_amount||10)&&e.jsx("div",{className:"p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:"w-5 h-5 text-yellow-600 mt-0.5",children:e.jsx("svg",{fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-yellow-800",children:"Balance below minimum withdrawal"}),e.jsxs("p",{className:"text-sm text-yellow-700 mt-1",children:["You need at least â¦",(a.minimum_payout_amount||1e3).toLocaleString()," to make a withdrawal. Current balance: â¦",a.available_balance.toLocaleString()]})]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Withdrawals"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.last_payout_at?`Last withdrawal: ${new Date(a.last_payout_at).toLocaleDateString()}`:"No withdrawals yet"})]}),a&&e.jsx(ke,{walletId:a.id,availableBalance:a.available_balance,totalWithdrawn:a.withdrawn_amount,bankName:a.bank_name||void 0,accountNumber:a.account_number||void 0,accountName:a.account_name||void 0,recipientCode:a.recipient_code||void 0,isBankVerified:a.is_bank_verified||!1})]})]}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-16 h-16 bg-muted rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(q,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No wallet found"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm mx-auto",children:"Start selling tickets to create your wallet and begin earning revenue"})]})})]})})]})})}export{Ke as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.