LAWN BOWLS DIGITAL SCORING SYSTEM
Administrator Dashboard
V63 · Direct save / revision visibleMySQL: Checking…

Greens & Rinks

🟢 Available🟡 Scheduled🔵 In Play🟣 Completed

Planned system connections

The administrator will configure competitions, clubs, players and rinks. Authorized referees will then open scheduled matches or start casual games, while spectators view read-only results. The physical rink displays will connect in a later phase.

Clear public display

This hides selected results on the public scoreboard only. Match assignments, scores and scoring history are preserved. The server rejects changed assignments.

Release scoring device?

The referee will lose scoring control. Confirmed scores and match history will not be changed.

Administrator V53 · Browser data retained · Controlled competition upload, update and test-only deletion

Add

Green · Rink

End 1

Choose Power Ends

Click the numbered ends for each team. Green = Team A; blue = Team B. Both teams may choose the same end.

0
Total
This end: 0

0
Total
This end: 0

Select shots for the current end.

Administrator scoring handover

Authenticated handover is not available yet. Referee scoring remains unchanged.

End-by-end History

Correct End

Change the shots for this completed end. Running totals will be recalculated.

0

0

Choose Power Ends

Select the numbered ends for each team, just as on the referee scoreboard. Each team may select any number of ends; both teams may select the same end. Selected ends are highlighted.

Team A

Team B

Move / Swap Match

Choose the destination time slot, green and rink. An occupied destination will swap the two matches.

Rink

'; const win=window.open('','_blank'); if(!win)return alert('Allow pop-ups for this page to export results as a PDF.'); win.document.open();win.document.write(html);win.document.close(); } // The server inventory is read-only. Never overwrite the browser prototype cache with it. let adminLiveScores=new Map(),adminLiveScoresBusy=false,adminLiveScoresError=false,adminLiveScoresPending=false; let adminServerMatches=null; let adminInventoryLastSuccess=0; let adminInventoryFailureMessage=""; const ADMIN_INVENTORY_MAX_AGE_MS=12000; function adminInventoryReady(){return adminServerMatches!==null&&!adminLiveScoresError&&Date.now()-adminInventoryLastSuccess<=ADMIN_INVENTORY_MAX_AGE_MS} function adminInventoryWarning(){return adminLiveScoresError?"MySQL match inventory unavailable: "+adminInventoryFailureMessage+". Changes are blocked until a successful refresh.":"Loading authoritative MySQL match inventory… Data is loading or stale. Changes are blocked until refreshed."} function adminInventoryGuard(){if(adminInventoryReady())return true;alert(adminInventoryWarning());void adminRefreshLiveScores();return false} function adminMatchInventory(){return adminServerMatches===null?[]:adminServerMatches} function adminServerMatch(id){return adminServerMatches?.find(m=>String(m.id)===String(id))||null} async function adminRefreshLiveScores(){ if(document.hidden)return; if(adminLiveScoresBusy){adminLiveScoresPending=true;return;} adminLiveScoresBusy=true; try{ const response=await fetch('/bowls_staging/api/admin_live_scores.php',{credentials:'same-origin',cache:'no-store'}); const data=await response.json(); if(!response.ok||data.status!=='ok'||!Array.isArray(data.matches))throw Error(data.message||'Live scores unavailable'); // A complete authoritative inventory is required: never silently fall back to stale local matches. if(!data.matches.every(m=>m&&typeof m.match_id==='string'&&m.match&&typeof m.match==='object'&&!Array.isArray(m.match)&&String(m.match.id)===m.match_id))throw Error('Incomplete MySQL match inventory'); const next=new Map(data.matches.map(m=>[String(m.match_id),m])); const inventory=data.matches.map(m=>({...m.match,id:m.match_id})); const changed=JSON.stringify([...next])!==JSON.stringify([...adminLiveScores]); adminLiveScores=next;adminServerMatches=inventory;adminLiveScoresError=false;adminInventoryLastSuccess=Date.now();adminInventoryFailureMessage=""; // A successful fetch must clear any stale/loading warning even when rows are unchanged. render(); }catch(error){adminLiveScoresError=true;adminInventoryFailureMessage=String(error?.message||"Unknown error").slice(0,160);console.warn('Administrator live scores unavailable:',error.message);render();} finally{adminLiveScoresBusy=false;if(adminLiveScoresPending){adminLiveScoresPending=false;void adminRefreshLiveScores();}} } setInterval(()=>{if(document.querySelector('#overview:not(.hidden),#matches:not(.hidden)'))void adminRefreshLiveScores()},3000); document.addEventListener('visibilitychange',()=>{if(!document.hidden)void adminRefreshLiveScores()}); void adminRefreshLiveScores(); function adminDisplayedMatch(m){ if(!m)return m; const live=adminLiveScores.get(String(m.id)); if(!live)return m; return {...m,scoreA:live.totals.A,scoreB:live.totals.B,currentEnd:live.next_end_number,status:live.match_status||m.status,hiddenOnPublicDisplay:live.hidden_on_public_display===true}; } function renderRinks(){ const host=$('rinkOverview'); if(!adminInventoryReady()){ host.innerHTML=''; return; } if(!db.greens.length){host.innerHTML='
No greens configured for this browser. Check Greens & Rinks.
';return;} // One live rink board: time slots are scheduling presets, never separate scoreboards. const matches=adminMatchInventory().filter(adminRinkDisplayEligible).map(adminDisplayedMatch); const statusRank={inplay:4,scheduled:3,completed:2}; const choose=(gid,rink)=>matches.filter(m=>String(m.greenId)===String(gid)&&Number(m.rink)===rink) .sort((a,b)=>(statusRank[a.status]||0)-(statusRank[b.status]||0)||String(a.actualStartedAt||a.date||'').localeCompare(String(b.actualStartedAt||b.date||''))).at(-1)||null; host.className=''; host.innerHTML='

Current Live Rinks

All matches · Time slots are scheduling presets
'+db.greens.map(g=>'

'+esc(g.name)+'

'+Array.from({length:Number(g.rinks)},(_,i)=>{ const r=i+1,m=choose(g.id,r),status=m?(m.status||'scheduled'):'available'; const a=Number(m?.scoreA||0),b=Number(m?.scoreB||0),done=status==='completed'; const standalone=m?.source==='standalone_referee'; const team=(side,score,wins)=>'
'+esc(m['name'+side]||'Team '+side)+(done&&wins?' ★ Winner ★':done&&a===b?' Match Peeled':'')+''+score+'
'; const body=m?'
'+team('A',a,a>b)+'
vs'+(status==='inplay'?'End '+Number(m.currentEnd||1)+(m.pointsMode?' · Points '+esc(m.target||m.pointsTarget||21):' of '+esc(m.ends||'')):'')+'
'+team('B',b,b>a)+'
':'
+ Assign a match
'; return ''; }).join('')+'
').join('')+'
'; } // Rink buttons use delegated events. Embedding JSON quotes in an HTML // onclick attribute broke the attribute and prevented all rink clicks. document.getElementById('rinkOverview').addEventListener('click',function(event){ const card=event.target.closest('button.rink-card[data-green][data-rink]'); if(!card||!this.contains(card))return; openCurrentRink(card.dataset.green,Number(card.dataset.rink)); }); function openCurrentRink(gid,rink){ // Viewing a rink must not depend on the 12-second write freshness guard. // Database-changing actions retain their existing server inventory checks. if(adminServerMatches===null){void adminRefreshLiveScores();alert('Loading live match information. Please try again shortly.');return;} const candidates=adminMatchInventory().filter(m=>adminRinkDisplayEligible(m)&&String(m.greenId)===String(gid)&&Number(m.rink)===rink); const rank={inplay:4,scheduled:3,completed:2}; const m=candidates.sort((a,b)=>(rank[a.status]||0)-(rank[b.status]||0)||String(a.actualStartedAt||a.date||'').localeCompare(String(b.actualStartedAt||b.date||''))).at(-1); selectedRink={gid,rink,slotId:m?.slotId||'unscheduled'}; $('rinkTitle').textContent=greenName(gid)+' — Rink '+rink; if(!m){$('rinkDetails').innerHTML='

No match assigned to this rink.

';} else{ const live=adminDisplayedMatch(m); const isStandalone=m.source==='standalone_referee'||m.recordType==='standalone_match'||m.record_type==='standalone_match'; const canEditScheduled=!isStandalone&&m.status==='scheduled'; $('rinkDetails').innerHTML='

'+esc(live.nameA)+' vs '+esc(live.nameB)+'

'+esc(live.format||'')+' · '+esc(live.status||'scheduled')+'

Score: '+Number(live.scoreA||0)+' – '+Number(live.scoreB||0)+'

'+ (canEditScheduled?'

Uses the existing MySQL revision-checked editor. Saves are validated by the server.

': '

'+(isStandalone?'Standalone matches are referee-managed.':'In-play or completed match editing requires a dedicated safe MySQL workflow.')+' Existing scores and device locks are protected.

'); const detailsButton=document.createElement('button'); detailsButton.type='button';detailsButton.className='btn secondary'; detailsButton.textContent='Match Details'; detailsButton.addEventListener('click',()=>openAuthoritativeMatchDetails(m.id)); $('rinkDetails').appendChild(detailsButton); if(canEditScheduled){const button=$('v256EditMatch');button.addEventListener('click',()=>editSelectedMatch(m.id));} } $('rinkDialog').showModal(); } // Checkpoint 258: safe MySQL-backed match-details view. Do not offer // unimplemented override actions that could conflict with referee locks. function openAuthoritativeMatchDetails(id){ const m=adminServerMatch(id); if(!m){void adminRefreshLiveScores();alert('Match information is being refreshed. Try again.');return;} const live=adminDisplayedMatch(m); const panel=$('rinkDetails'); const lineups=m.lineups||{}; const playerNames=side=>{ const lineup=lineups[side]; if(!lineup||typeof lineup!=='object')return 'Not recorded'; const values=Object.entries(lineup).map(([position,player])=>{ const name=typeof player==='string'?player:(player?.name||player?.playerName||''); return name?position+': '+name:''; }).filter(Boolean); return values.length?values.join(' · '):'Not recorded'; }; const rows=[ ['Team A',live.nameA||'Team A'],['Team A players',playerNames('A')], ['Team B',live.nameB||'Team B'],['Team B players',playerNames('B')], ['Status',live.status||'Unknown'],['Format',live.format||'Not recorded'], ['Scheduled date',live.playDate||live.date||'Not recorded'], ['Ends',live.ends??'Not recorded'], ['Score',Number(live.scoreA||0)+' – '+Number(live.scoreB||0)], ['Power ends',m.powerEnds?JSON.stringify(m.powerEnds):'Not recorded'], ['Revision',m.revision??'Not available'] ]; panel.replaceChildren(); const heading=document.createElement('h3');heading.textContent='Match Details';panel.appendChild(heading); for(const [label,value] of rows){const row=document.createElement('p'); const strong=document.createElement('strong');strong.textContent=label+': '; row.append(strong,document.createTextNode(String(value)));panel.appendChild(row); } const note=document.createElement('p');note.className='notice'; note.textContent='Live match details are read-only here. Administrator takeover, player corrections, power-end changes and End Match require a server-enforced override workflow; no referee lock or score has been changed.'; panel.appendChild(note); // Checkpoint 259: authenticated read-only lock preflight. Never release a // referee lock or claim Administrator scoring ownership from this view. if(String(live.status).toLowerCase()==='inplay'){ const review=document.createElement('button'); review.type='button';review.className='btn secondary'; review.textContent='Review Scoring Control'; review.addEventListener('click',async()=>{ review.disabled=true; const result=document.createElement('p');result.className='notice'; result.textContent='Checking the current scoring lock…'; review.insertAdjacentElement('afterend',result); try{ const response=await fetch('/bowls_staging/api/admin_scoring_devices.php',{credentials:'same-origin',cache:'no-store'}); const payload=await response.json(); if(!response.ok||payload.status!=='ok'||!Array.isArray(payload.locks))throw Error('Unable to verify scoring locks'); const matches=payload.locks.filter(l=>String(l.match_id)===String(m.id)&&String(l.green_id)===String(m.greenId)&&Number(l.rink_number)===Number(m.rink)); const active=matches.filter(l=>l.lock_state==='active'); if(active.length>1){result.textContent='Multiple active locks found. Administrator review required; no changes made.';} else if(active.length===1){result.textContent='Referee scoring lock active. Rink Access can release the device, but this is NOT an Administrator takeover. No changes made.';} else {result.textContent='No active scoring lock was reported. A dedicated Administrator scoring session is still required; no changes made.';} }catch(e){result.textContent='Unable to verify current scoring control. No changes made.';} finally{review.disabled=false;} }); panel.appendChild(review); } const back=document.createElement('button');back.type='button';back.className='btn secondary';back.textContent='Back to score summary'; back.addEventListener('click',()=>openCurrentRink(m.greenId,Number(m.rink)));panel.appendChild(back); } let selectedRink=null; function openRink(gid,rink,slotId='unscheduled'){if(!adminInventoryGuard())return;selectedRink={gid,rink,slotId};const m=rinkMatch(gid,rink,slotId);$('rinkTitle').textContent=`${greenName(gid)} — Rink ${rink} — ${slotLabel(slotId)}`;$('rinkDetails').innerHTML=m?`

${esc(m.nameA)} vs ${esc(m.nameB)}

${esc(compName(m.competitionId))} · ${esc(m.format)} · ${esc(slotLabel(m.slotId,m.date))}

Status: ${esc(m.status||'scheduled')} · Score: ${Number(m.scoreA||0)} – ${Number(m.scoreB||0)}

${['A','B'].map(side=>`

${esc(m['name'+side])}

${(positions[m.format]||[]).map(pos=>`
${esc(pos)}: ${esc(m.lineups?.[side]?.[pos]?.name||'Not assigned')}
`).join('')}
`).join('')}
`:`

This rink is available for this time slot.

`;$('rinkDialog').showModal()} function newMatchAtRink(){ if(!adminServerMatches||adminLiveScoresError){void adminRefreshLiveScores();return alert('Wait for a successful MySQL inventory refresh before creating a match.');} if(!selectedRink)return; const rink={...selectedRink}; $('rinkDialog').close(); openForm('match'); // V64 MySQL match editor opens asynchronously only when editing. Creation uses the existing form. const green=$('f_greenId');if(!green)return; green.value=rink.gid;updateMatchRinkOptions(rink.rink); const sl=$('f_slotId');if(sl){sl.value=rink.slotId==='unscheduled'?'':rink.slotId;if(sl.value)setSlotDate(sl.value);} if(sl&&!sl.value){const hint=document.createElement('p');hint.className='notice';hint.textContent='Select a Time Slot before saving. Time Slots are date/time presets; this match will be saved to MySQL.';$('formFields').prepend(hint);} } function editSelectedMatch(id){if(!adminServerMatches||adminLiveScoresError){void adminRefreshLiveScores();return alert('MySQL inventory is unavailable. Please retry.');}$('rinkDialog').close();openForm('match',id)} /* V50: Browser-side start gate. MySQL/server referee enforcement is a later phase. */ function v50StartIssues(m){ const issues=[]; if(m.competitionId && !find('competitions',m.competitionId))issues.push('The selected competition no longer exists.'); const green=find('greens',m.greenId); if(!green)issues.push('Select an existing green.'); else if(!Number.isInteger(Number(m.rink))||Number(m.rink)<1||Number(m.rink)>Number(green.rinks))issues.push('Select a valid rink on the green.'); if(!m.slotId||!find('slots',m.slotId))issues.push('Select an existing time slot (its date and time do not restrict starting).'); for(const side of ['A','B']){ const teamId=m['team'+side+'Id']; if(teamId&&!find('teams',teamId))issues.push('Team '+side+' references a missing registered team.'); if(!String(m['name'+side]||'').trim())issues.push('Enter the name for Team '+side+'.'); } const roles=positions[m.format]; if(!roles)issues.push('Select a valid match format.'); else for(const side of ['A','B'])for(const role of roles){ const player=m.lineups?.[side]?.[role]||{}; if(!String(player.name||'').trim())issues.push('Team '+side+' — '+role+': enter a player name.'); if(player.playerId&&!find('players',player.playerId))issues.push('Team '+side+' — '+role+': registered player no longer exists.'); } return issues; } function v50CanStart(m){ const issues=v50StartIssues(m); if(!issues.length)return true; alert('This match cannot begin scoring until the following are corrected:\n\n• '+issues.join('\n• ')+'\n\nEdit Match & Players, save the corrections, then try again.'); return false; } function setMatchStatus(id,status){return alert('Status changes must be saved through the MySQL match API.');/* legacy disabled */const m=find('matches',id);if(!m)return;if(status==='inplay'&&m.status!=='inplay'&&!v50CanStart(m))return;if(status==='completed'&&!confirm('Mark this match completed? Scores and end history will be retained.'))return;m.status=status;save();render();$('rinkDialog').close();toast('Match status updated')} function destinationOptions(m){return slotOptions().flatMap(s=>db.greens.flatMap(g=>Array.from({length:Number(g.rinks)},(_,i)=>({slotId:s.id,gid:g.id,rink:i+1,label:`${s.name} → ${g.name} → Rink ${i+1}`})))).filter(o=>!(o.gid===m.greenId&&o.rink===Number(m.rink)&&o.slotId===slotKey(m)))} let moveMatchId=null; function moveMatchPrompt(id){return alert('Move / Swap is unavailable until server-authoritative updates are connected.');/* legacy disabled */const m=find('matches',id);if(!m)return;const options=destinationOptions(m);if(!options.length)return alert('No other destinations exist.');moveMatchId=id;const dropdown=$('moveDestination');dropdown.innerHTML=options.map((o,i)=>``).join('');$('rinkDialog').close();$('moveDialog').showModal()} function confirmMoveDestination(){const m=find('matches',moveMatchId);if(!m)return;const options=destinationOptions(m);const o=options[Number($('moveDestination').value)];if(!o)return alert('Choose a destination.');$('moveDialog').close();moveOrSwapRinks({gid:m.greenId,rink:Number(m.rink),slotId:slotKey(m)},o)} function attachRinkDragHandlers(){return;/* Server-authoritative move/swap endpoint not yet connected. */const host=$('rinkOverview');host.querySelectorAll('.rink-card').forEach(card=>{const loc=()=>({gid:card.dataset.green,rink:Number(card.dataset.rink),slotId:card.dataset.slot});card.addEventListener('dragstart',e=>{const m=rinkMatch(...[card.dataset.green,Number(card.dataset.rink),card.dataset.slot]);if(!m||m.status==='completed'){e.preventDefault();return}draggedRink=loc();e.dataTransfer.effectAllowed='move';e.dataTransfer.setData('text/plain',JSON.stringify(draggedRink));card.classList.add('dragging')});card.addEventListener('dragend',()=>{draggedRink=null;host.querySelectorAll('.rink-card').forEach(c=>c.classList.remove('dragging','drop-target'))});card.addEventListener('dragover',e=>{if(!draggedRink)return;e.preventDefault();card.classList.add('drop-target')});card.addEventListener('dragleave',()=>card.classList.remove('drop-target'));card.addEventListener('drop',e=>{e.preventDefault();e.stopPropagation();card.classList.remove('drop-target');if(!draggedRink)return;const from={...draggedRink};draggedRink=null;moveOrSwapRinks(from,loc())})})} function moveOrSwapRinks(from,to){return alert('Move / Swap is unavailable until server-authoritative updates are connected.');/* legacy disabled */if(from.gid===to.gid&&from.rink===to.rink&&from.slotId===to.slotId)return;const a=rinkMatch(from.gid,from.rink,from.slotId),b=rinkMatch(to.gid,to.rink,to.slotId);if(!a||a.status==='completed')return alert('Only unfinished matches can be moved.');if(b?.status==='completed')return alert('Destination contains a completed match. Clear it first.');if(!confirm(`${b?'SWAP':'MOVE'} matches?\n\n${slotLabel(from.slotId)} / ${greenName(from.gid)} / Rink ${from.rink}\n→ ${slotLabel(to.slotId)} / ${greenName(to.gid)} / Rink ${to.rink}${a.status==='inplay'||b?.status==='inplay'?'\n\nWARNING: An in-progress match is being moved.':''}`))return;const apply=(m,l)=>{m.greenId=l.gid;m.rink=l.rink;m.slotId=l.slotId==='unscheduled'?'':l.slotId;if(m.slotId)m.date=find('slots',m.slotId)?.date||m.date};apply(a,to);if(b)apply(b,from);save();render();$('rinkDialog').close();toast(b?'Matches swapped':'Match moved')} // All public-display clearing uses a fresh authenticated MySQL inventory, never browser-local matches. let adminPublicClearBusy=false,adminPublicClearScope=null; function adminPublicClearDialog(){return $('adminPublicClearDialog')} function adminPublicClearClose(){if(adminPublicClearBusy)return;adminPublicClearDialog().close()} $('adminPublicClearCancel').addEventListener('click',adminPublicClearClose); $('adminPublicClearDialog').addEventListener('cancel',event=>{if(adminPublicClearBusy)event.preventDefault()}); function adminPublicClearOpen(scope,greenId='',rink=0,slotId=''){ if(adminPublicClearBusy)return; adminPublicClearScope={scope,greenId,rink,slotId}; $('adminPublicClearTitle').textContent=scope==='all'?'Clear All Public Rinks':scope==='green'?'Clear Green Public Results':'Clear Rink Public Results'; $('adminPublicClearGreenControls').classList.toggle('hidden',scope!=='green'); $('adminPublicClearDescription').textContent=scope==='all'?'All time slots and all greens':scope==='rink'?`Green ${greenId}, rink ${rink}, time slot ${slotId}`:'Select one green and one time slot'; $('adminPublicClearStatus').textContent='The current MySQL assignments will be checked before confirmation.'; if(scope==='green'){ $('adminPublicClearSlot').innerHTML=db.slots.map(x=>``).join(''); $('adminPublicClearGreen').innerHTML=db.greens.map(x=>``).join(''); if(!db.slots.length||!db.greens.length){$('adminPublicClearStatus').textContent='Configure a green and time slot first.';$('adminPublicClearConfirm').disabled=true}else $('adminPublicClearConfirm').disabled=false; }else $('adminPublicClearConfirm').disabled=false; adminPublicClearDialog().showModal(); } function clearRink(gid,rink,slotId='unscheduled'){if($('rinkDialog').open)$('rinkDialog').close();adminPublicClearOpen('rink',gid,Number(rink),slotId)} function clearAllRinks(){adminPublicClearOpen('all')} function openClearGreenDialog(){adminPublicClearOpen('green')} async function adminPublicClearInventory(){ const response=await fetch('/bowls_staging/api/admin_records.php',{credentials:'same-origin',cache:'no-store'}); const result=await response.json(); if(!response.ok||result.status!=='ok'||!Array.isArray(result.records))throw Error(result.message||'Cannot read authoritative MySQL inventory'); return result.records; } function adminPublicClearExpected(records,scope,slot,green,rink){ const expected=[],seen=new Set(); for(const row of records){ if(row.record_type!=='match')continue; const m=row.data; if(!m||typeof m!=='object'||Array.isArray(m))throw Error('Invalid match in MySQL inventory'); if(!['scheduled','inplay','completed'].includes(String(m.status||'scheduled').toLowerCase()))continue; if(scope!=='all'&&(m.slotId!==slot||m.greenId!==green||(scope==='rink'&&m.rink!==rink)))continue; if(typeof m.slotId!=='string'||typeof m.greenId!=='string'||!Number.isInteger(m.rink)||typeof row.record_id!=='string')throw Error('Invalid match assignment in MySQL inventory'); const key=JSON.stringify([m.slotId,m.greenId,m.rink]); if(seen.has(key))throw Error('Multiple matches assigned to the same rink. Administrator review required.'); seen.add(key); expected.push({slot_id:m.slotId,green_id:m.greenId,rink:m.rink,match_id:row.record_id}); } return expected; } $('adminPublicClearConfirm').addEventListener('click',async()=>{ if(adminPublicClearBusy||!adminPublicClearScope)return; const {scope,greenId,rink,slotId}=adminPublicClearScope; const slot=scope==='green'?$('adminPublicClearSlot').value:slotId; const green=scope==='green'?$('adminPublicClearGreen').value:greenId; const status=$('adminPublicClearStatus'),confirmButton=$('adminPublicClearConfirm'); adminPublicClearBusy=true;confirmButton.disabled=true;$('adminPublicClearCancel').disabled=true; try{ status.textContent='Checking current MySQL rink assignments…'; const records=await adminPublicClearInventory(); if(scope!=='all'&&(!records.some(r=>r.record_type==='slot'&&r.record_id===slot)||!records.some(r=>r.record_type==='green'&&r.record_id===green)))throw Error('Selected green or time slot is not in MySQL. Refresh the administrator page.'); const expected=adminPublicClearExpected(records,scope,slot,green,rink); if(!expected.length)throw Error('No assigned MySQL matches in this scope to clear.'); const description=scope==='all'?'all time slots and greens':scope==='green'?`green ${green}, time slot ${slot}`:`green ${green}, rink ${rink}, time slot ${slot}`; if(!window.confirm(`Hide ${expected.length} match result(s) on the public display for ${description}?\n\nAll match records and scoring history will remain intact.`)){status.textContent='Clear cancelled. No changes made.';return} status.textContent='Applying display-only clear in MySQL…'; const body={scope,expected_matches:expected}; if(scope!=='all'){body.slot_id=slot;body.green_id=green;if(scope==='rink')body.rink=rink} const response=await fetch('/bowls_staging/api/admin_public_display_clear.php',{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json','X-Bowls-Request':'admin-public-display-clear'},body:JSON.stringify(body)}); const result=await response.json(); if(!response.ok||result.status!=='ok'||result.hidden_count!==expected.length)throw Error(result.message||'Clear response could not be verified. Refresh public results before retrying.'); status.textContent=`${result.hidden_count} public result(s) hidden. Match records and scoring history preserved.`; toast(status.textContent); await adminRefreshLiveScores(); if(adminLiveScoresError)throw Error('Display changed, but administrator visibility could not be refreshed; verify the public viewer before retrying.'); }catch(error){status.textContent='Display not confirmed cleared: '+error.message;console.warn('Public display clear:',error)} finally{adminPublicClearBusy=false;confirmButton.disabled=false;$('adminPublicClearCancel').disabled=false} }); function applyCompetitionDefaults(id){const c=find('competitions',id);if(!c)return;const root=$('formFields');for(const key of ['format','ends','target','mult']){const el=root.querySelector(`[name="${key}"]`);if(el)el.value=c[key]??(key==='format'?'Pairs':key==='ends'?10:key==='target'?21:2)}for(const key of ['pointsMode','power']){const el=root.querySelector(`[name="${key}"]`);if(el)el.checked=!!c[key]}drawPositionFields(root.querySelector('[name="format"]').value);for(const side of ['A','B']){const select=$('f_savedTeam'+side);if(select?.value&&find('teams',select.value)?.format!==c.format)select.value=''}} function ensureScore(m){if(!Array.isArray(m.endsHistory))m.endsHistory=[];if(!Array.isArray(m.powerA))m.powerA=[];if(!Array.isArray(m.powerB))m.powerB=[];recalcScore(m)} function scorePower(m,end,side){return !!m.power&&(side==='A'?m.powerA:m.powerB).includes(end)} function recalcScore(m){let a=0,b=0;for(let i=0;i=Number(m.ends||10))||(m.pointsMode&&Math.max(m.scoreA||0,m.scoreB||0)>=Number(m.target||21))} function openAdminScore(id){const m=find('matches',id);if(!m)return;if(m.status!=='inplay'&&m.status!=='completed'&&!v50CanStart(m))return;ensureScore(m);$('rinkDialog').close();$('scoreMatchId').value=id;$('scoreMatchId').dispatchEvent(new Event('change',{bubbles:true}));adminPending={A:0,B:0};drawScoreEditor();openInlinePower();$('scoreDialog').showModal()} function adjustAdminPending(side,delta){const m=find('matches',$('scoreMatchId').value);if(!m||adminComplete(m))return;if(delta>0&&adminPending[side==='A'?'B':'A']>0)return alert('Only one team can score in an end.');adminPending[side]=Math.max(0,adminPending[side]+delta);drawScoreEditor()} function drawScoreEditor(){ const m=find('matches',$('scoreMatchId').value);if(!m)return;ensureScore(m); const complete=adminComplete(m),end=m.endsHistory.length+1,mult=Number(m.mult)===3?3:2; $('scoreCompetition').textContent=compName(m.competitionId)==='Casual match'?'':compName(m.competitionId); $('scoreTitle').textContent=greenName(m.greenId)+' · Rink '+m.rink; $('scoreSummary').textContent=m.format+' · '+(m.pointsMode?'First to '+m.target+' points':m.ends+' ends'); $('scoreEndLabel').textContent=complete?'Match complete':'End '+end+(m.pointsMode?'':' of '+m.ends); for(const side of ['A','B']){ const active=!complete&&scorePower(m,end,side),box=$('scoreName'+side).closest('.ref-team'); box.classList.toggle('power-active-a',active&&side==='A'); box.classList.toggle('power-active-b',active&&side==='B'); $('scoreName'+side).textContent=m['name'+side]; $('scoreTotal'+side).textContent=Number(m['score'+side]||0); $('scorePending'+side).textContent='This end: '+adminPending[side]; $('scorePlayers'+side).textContent=(positions[m.format]||[]).map(pos=>{const n=m.lineups?.[side]?.[pos]?.name;return n?(pos==='Player'?'':pos+': ')+n:''}).filter(Boolean).join('\n'); $('scorePower'+side).innerHTML=(active?'
★ POWER END ×'+mult+' IN PLAY ★
':'')+(m.power?'
Selected Power Ends: '+esc((side==='A'?m.powerA:m.powerB).join(', ')||'None')+' (×'+mult+')
':''); } $('scorePowerOverview').classList.toggle('hidden',!m.power||!!m.pointsMode); $('scorePowerOverview').innerHTML=m.power?'Power Ends selected
'+esc(m.nameA)+': '+esc(m.powerA.join(', ')||'None')+'
'+esc(m.nameB)+': '+esc(m.powerB.join(', ')||'None')+'
Multiplier: ×'+mult+'
':''; // Handover safety: rendering must never re-enable legacy local save() scoring. for(const id of ['scoreAdd','scoreUndo','scoreFinish']){ const button=$(id);button.disabled=true; button.title='Administrator scoring requires the authenticated handover API'; } const picker=$('inlinePowerPicker'); if(picker){picker.style.pointerEvents='none';picker.setAttribute('aria-disabled','true');} $('scoreNotice').textContent=complete?'Match complete. You may correct any completed end.':'Select shots for one team, then confirm End '+end+'.'; let a=0,b=0; $('scoreHistory').innerHTML=''+m.endsHistory.map((e,i)=>{ if(e.side==='A')a+=e.points;else b+=e.points; const pa=scorePower(m,i+1,'A'),pb=scorePower(m,i+1,'B'); return '' }).join('')+(m.endsHistory.length?'':'')+'
End'+esc(m.nameA)+''+esc(m.nameB)+'Running PointsCorrection
'+(i+1)+''+(e.side==='A'?e.shots+(e.multiplier>1?' ×'+e.multiplier+' = '+e.points:''):'0')+''+(e.side==='B'?e.shots+(e.multiplier>1?' ×'+e.multiplier+' = '+e.points:''):'0')+''+a+' – '+b+'
No completed ends yet
'; } let adminPowerDraft={A:[],B:[]}; function openInlinePower(){const m=find('matches',$('scoreMatchId').value);if(!m)return;ensureScore(m);adminPowerDraft={A:[...m.powerA],B:[...m.powerB]};$('inlinePowerNameA').textContent=m.nameA||'Team A';$('inlinePowerNameB').textContent=m.nameB||'Team B';drawInlinePower();$('inlinePowerPicker').classList.toggle('hidden',!m.power||!!m.pointsMode);} function closeInlinePower(){openInlinePower()} function drawInlinePower(){const m=find('matches',$('scoreMatchId').value);if(!m)return;const limit=m.pointsMode?0:Math.min(60,Math.max(1,Number(m.ends)||10));for(const side of ['A','B']){const grid=$('inlinePowerGrid'+side);grid.replaceChildren();for(let end=1;end<=limit;end++){const b=document.createElement('button'),selected=adminPowerDraft[side].includes(end);b.type='button';b.textContent=end;b.className='power-pick'+(selected?' selected-'+side.toLowerCase():'');b.setAttribute('aria-pressed',String(selected));b.onclick=()=>{adminPowerDraft[side]=selected?adminPowerDraft[side].filter(n=>n!==end):[...adminPowerDraft[side],end].sort((a,b)=>a-b);drawInlinePower()};grid.append(b)}}} function saveInlinePower(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */const m=find('matches',$('scoreMatchId').value);if(!m)return;if(m.endsHistory.length&&!confirm('Update Power Ends and recalculate already recorded ends?'))return;m.power=true;m.powerA=[...adminPowerDraft.A];m.powerB=[...adminPowerDraft.B];recalcScore(m);save();render();drawScoreEditor();openInlinePower();toast('Power Ends saved')} function configureAdminPower(){ const m=find('matches',$('scoreMatchId').value);if(!m||!m.power)return; ensureScore(m);adminPowerDraft={A:[...m.powerA],B:[...m.powerB]}; $('adminPowerNameA').textContent=m.nameA||'Team A';$('adminPowerNameB').textContent=m.nameB||'Team B'; drawAdminPowerChoices();$('adminPowerDialog').showModal(); } function drawAdminPowerChoices(){ const m=find('matches',$('scoreMatchId').value);if(!m)return; const limit=m.pointsMode?Math.max(60,m.endsHistory.length+1):Math.min(60,Math.max(1,Number(m.ends)||10)); for(const side of ['A','B']){ const grid=$('adminPowerGrid'+side);grid.replaceChildren(); for(let end=1;end<=limit;end++){ const selected=adminPowerDraft[side].includes(end),button=document.createElement('button'); button.type='button';button.textContent=end;button.className='power-pick'+(selected?' selected-'+side.toLowerCase():''); button.setAttribute('aria-pressed',String(selected));button.setAttribute('aria-label',`Team ${side} Power End ${end}`); button.onclick=()=>{adminPowerDraft[side]=selected?adminPowerDraft[side].filter(n=>n!==end):[...adminPowerDraft[side],end].sort((a,b)=>a-b);drawAdminPowerChoices()}; grid.append(button); } } } function saveAdminPowerSelection(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */ const m=find('matches',$('scoreMatchId').value);if(!m||!m.power)return; if(m.endsHistory.length&&!confirm('Update Power Ends and recalculate the points for already recorded ends?'))return; m.powerA=[...adminPowerDraft.A];m.powerB=[...adminPowerDraft.B];recalcScore(m);save();render();drawScoreEditor();$('adminPowerDialog').close();toast('Power Ends saved'); } function addScoreEnd(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */const m=find('matches',$('scoreMatchId').value);if(!m||adminComplete(m))return;if(m.status!=='inplay'&&!v50CanStart(m))return;const shots=adminPending.A+adminPending.B;if(shots<=0||adminPending.A>0&&adminPending.B>0)return alert('An end must have shots for exactly one team. 0–0 is not allowed.');const side=adminPending.A>0?'A':'B',end=m.endsHistory.length+1,mult=scorePower(m,end,side)?(Number(m.mult)===3?3:2):1;if(!confirm(`Confirm End ${end}: ${m['name'+side]} scores ${shots} shot(s)${mult>1?' ×'+mult:''}, awarding ${shots*mult} point(s)?`))return;m.endsHistory.push({side,shots});m.status='inplay';recalcScore(m);adminPending={A:0,B:0};save();render();drawScoreEditor();toast('End recorded')} function undoAdminEnd(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */const m=find('matches',$('scoreMatchId').value);if(!m?.endsHistory?.length||m.status==='completed')return;if(!confirm('Undo the last confirmed end?'))return;const e=m.endsHistory.pop();adminPending={A:e.side==='A'?e.shots:0,B:e.side==='B'?e.shots:0};recalcScore(m);save();render();drawScoreEditor()} let adminEditIndex=null,adminEditShots={A:0,B:0}; function adminEditValid(){return (adminEditShots.A>0)!==(adminEditShots.B>0)} function editScoreEnd(i){ const m=find('matches',$('scoreMatchId').value),e=m?.endsHistory?.[i];if(!e)return; adminEditIndex=i;adminEditShots={A:e.side==='A'?e.shots:0,B:e.side==='B'?e.shots:0}; $('adminEditTitle').textContent='Correct End '+(i+1); $('adminEditNameA').textContent=m.nameA;$('adminEditNameB').textContent=m.nameB; drawAdminEdit();$('adminEditEndDialog').showModal(); } function drawAdminEdit(){ $('adminEditShotsA').textContent=adminEditShots.A;$('adminEditShotsB').textContent=adminEditShots.B; const m=find('matches',$('scoreMatchId').value),side=adminEditShots.A?'A':'B',shots=adminEditShots[side]; const mult=m&&scorePower(m,adminEditIndex+1,side)?(Number(m.mult)===3?3:2):1; $('adminEditInfo').textContent=adminEditValid()?'End '+(adminEditIndex+1)+': '+m['name'+side]+' scores '+shots+' shot(s)'+(mult>1?' · Power End ×'+mult+' = '+shots*mult+' points':' · '+shots+' points'):'Enter at least one shot for exactly one team. 0–0 is not permitted.'; $('adminEditSave').disabled=!adminEditValid(); } function adjustAdminEdit(side,delta){ if(delta>0&&adminEditShots[side==='A'?'B':'A']>0)return alert('Only one team can score in an end. Reduce the other team to zero first.'); adminEditShots[side]=Math.max(0,adminEditShots[side]+delta);drawAdminEdit(); } function saveAdminEdit(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */ if(adminEditIndex===null||!adminEditValid())return; const m=find('matches',$('scoreMatchId').value),e=m?.endsHistory?.[adminEditIndex];if(!e)return; const side=adminEditShots.A?'A':'B',shots=adminEditShots[side]; if(!confirm('Change End '+(adminEditIndex+1)+' from '+e.side+' '+e.shots+' to '+side+' '+shots+'? All running totals will be recalculated.'))return; m.scoreCorrections=m.scoreCorrections||[]; m.scoreCorrections.push({end:adminEditIndex+1,previous:{...e},newShots:shots,newSide:side,actor:'Administrator',at:new Date().toISOString()}); e.side=side;e.shots=shots;recalcScore(m);save();render();drawScoreEditor();$('adminEditEndDialog').close();adminEditIndex=null; } function finishAdminMatch(){return alert('Administrator scoring is awaiting the authenticated handover API; no score was changed.');/* legacy scoring disabled */const m=find('matches',$('scoreMatchId').value);if(!m||m.status==='completed'||!confirm('End this match now? All recorded results will be preserved.'))return;m.status='completed';m.endedAt=new Date().toISOString();adminPending={A:0,B:0};save();render();drawScoreEditor()} function bulkSlots(){const count=Number(prompt('How many time slots would you like to create? (1–30)','4'));if(!Number.isInteger(count)||count<1||count>30)return;const first=prompt('First date and time (YYYY-MM-DDTHH:MM)',dateNow());if(!first)return;const start=new Date(first);if(isNaN(start.getTime()))return alert('Invalid date.');const mins=Number(prompt('Minutes between time slots','150'));if(!Number.isFinite(mins)||mins<1||mins>1440)return alert('Invalid interval.');for(let i=0;i`} function refreshSavedTeamOptions(){const root=$('formFields');if(!root)return;const format=root.querySelector('[name="format"]')?.value||'Pairs';for(const side of ['A','B']){const sel=$('f_savedTeam'+side);if(!sel)continue;const prior=sel.value;const other=$('f_savedTeam'+(side==='A'?'B':'A'))?.value||'';sel.innerHTML=''+db.teams.filter(t=>t.format===format).map(t=>``).join('');if(!db.teams.some(t=>t.id===prior&&t.format===format))sel.value='';}} function teamEntries(team){return Object.values(team?.lineup||{}).filter(e=>e&&(e.playerId||e.name?.trim()))} function entryClash(a,b){return !!((a.playerId&&b.playerId&&a.playerId===b.playerId)||(a.name&&b.name&&a.name.trim().toLowerCase()===b.name.trim().toLowerCase()))} function applySavedTeam(side){const root=$('formFields'),sel=$('f_savedTeam'+side),team=find('teams',sel.value);if(!team){refreshSavedTeamOptions();return;}const format=root.querySelector('[name="format"]').value,otherSide=side==='A'?'B':'A',other=find('teams',$('f_savedTeam'+otherSide)?.value);if(team.format!==format){sel.value='';refreshSavedTeamOptions();return alert('Select a team matching the match format.')}const occupied=[];for(const pos of positions[format]){const key=otherSide+'_'+pos,pid=root.querySelector(`[name="pick_${key}"]`)?.value||'',name=root.querySelector(`[name="name_${key}"]`)?.value||'';if(pid||name.trim())occupied.push({playerId:pid,name})}if(team.id===other?.id||teamEntries(team).some(a=>occupied.some(b=>entryClash(a,b)))){sel.value='';refreshSavedTeamOptions();return alert('This team contains a player already assigned to the opposing team. Choose a different team.')}for(const pos of positions[format]){const e=team.lineup?.[pos]||{},k=side+'_'+pos;const pick=root.querySelector(`[name="pick_${k}"]`),name=root.querySelector(`[name="name_${k}"]`);if(pick)pick.value=e.playerId||'';if(name)name.value=e.name||''}teamNameManual[side]=true;root.querySelector(`[name="name${side}"]`).value=team.name;refreshAvailablePlayers();refreshSavedTeamOptions();} function teamPositionsHTML(item){return `
${(positions[item?.format||'Pairs']||[]).map(pos=>`
`).join('')}
`} function updateTeamPositionFields(item){const f=$('formFields');if(!f)return;const fmt=f.querySelector('[name="format"]').value,old={};f.querySelectorAll('#teamPositionFields [name]').forEach(el=>old[el.name]=el.value);const fields=$('teamPositionFields');fields.innerHTML=(positions[fmt]||[]).map(pos=>`
`).join('');wireTeamSelects()} function wireTeamSelects(){$('teamPositionFields').querySelectorAll('select').forEach(sel=>sel.addEventListener('change',()=>{const p=find('players',sel.value);if(p)sel.nextElementSibling.value=p.name;const chosen=new Set([...$('teamPositionFields').querySelectorAll('select')].map(x=>x.value).filter(Boolean));$('teamPositionFields').querySelectorAll('select').forEach(x=>[...x.options].forEach(o=>{if(o.value)o.disabled=chosen.has(o.value)&&o.value!==x.value}))}))} // V52: Rink Access uses the existing administrator-authenticated MySQL daily code API. // Never store access codes in localStorage or automatically generate them. const v52CodeCache=new Map();let v52Loading=false; let adminDeviceLocks=null,adminDeviceBusy=false,adminDeviceRefreshing=false; // A status request belongs to one snapshot epoch. A release, code reload or // newer refresh invalidates its result even if the old HTTP response arrives later. let adminDeviceEpoch=0; let adminDeviceReleaseSerial=0; let adminDeviceReleaseNotice=null; let adminDeviceReconcilePending=false; // Reconciliation owns the refresh lane until its status request settles. // A post-release reconciliation is still part of the release transaction in the UI. // Do not start a second Force Release until the first verification settles. function adminDeviceReleaseStartAllowed(busy,loading,reconciling,refreshing){ return busy===false&&loading===false&&reconciling===false&&refreshing===false; } function adminDevicePollAllowed(hidden,tabHidden,busy,refreshing,dialogOpen,reconciling){ return !hidden&&!tabHidden&&!busy&&!refreshing&&!dialogOpen&&!reconciling; } // A release notice is independent of the routine status line. Background // polling, code reloads and code generation must never erase it. function adminDeviceNoticeAction(state,reason){ if(state===null||typeof state!=='object'||Array.isArray(state))return 'ignore'; if(reason==='new-release')return 'clear'; if(reason==='publish'&&typeof state.message==='string'&&state.message.trim()!==''&&state.serial===adminDeviceReleaseSerial)return 'publish'; return 'ignore'; } function adminDeviceRenderReleaseNotice(){ const el=$('adminDeviceReleaseNotice'); el.textContent=adminDeviceReleaseNotice?adminDeviceReleaseNotice.message+(adminDeviceReleaseNotice.observation?' '+adminDeviceReleaseNotice.observation:''):''; el.classList.toggle('hidden',!adminDeviceReleaseNotice); } // Current ownership is a separate observation, never evidence of the old POST. // Refresh failures and superseded epochs must not replace a verified observation. function adminDeviceNoticeObservation(snapshot,greenId,rink,expectedId){ if(!(snapshot instanceof Map))return null; const current=snapshot.get(v52CodeKey(greenId,rink)); if(!current)return 'Latest verified rink status: no lock listed. This does not establish whether the original release succeeded.'; if(current.lockId===expectedId)return 'Latest verified rink status: original lock '+expectedId+' remains listed.'; return 'Latest verified rink status: replacement lock '+current.lockId+' is listed. Do not retry the earlier release against this device.'; } function adminDeviceUpdateNoticeObservation(snapshot){ const notice=adminDeviceReleaseNotice; if(!notice||notice.serial!==adminDeviceReleaseSerial||!notice.identity)return; const observation=adminDeviceNoticeObservation(snapshot,notice.identity.greenId,notice.identity.rink,notice.identity.lockId); if(observation===null)return; notice.observation=observation; adminDeviceRenderReleaseNotice(); } function adminDevicePublishReleaseNotice(message,serial,identity=null){ if(adminDeviceNoticeAction({message,serial},'publish')!=='publish')return; adminDeviceReleaseNotice={message,serial,identity,observation:null};adminDeviceRenderReleaseNotice(); } function adminDeviceClearReleaseNotice(){ adminDeviceReleaseNotice=null;adminDeviceRenderReleaseNotice(); } // Preserve a submitted operation's result even when its tab is no longer visible. // Only a newer release operation may supersede the notice. function adminDeviceNoticeDelivery(serial,currentSerial,submitted,visible){ if(serial!==currentSerial)return 'stale'; if(!submitted&&!visible)return 'defer'; return visible?'visible':'retain'; } function adminDeviceAcceptResponse(requestEpoch,currentEpoch,busy){ return Number.isSafeInteger(requestEpoch)&&requestEpoch>=0&&requestEpoch===currentEpoch&&busy===false; } function adminDeviceInvalidate(){adminDeviceEpoch++;adminDeviceLocks=null;} // Invalidate preflight work if the page becomes hidden, even when it becomes // visible again before a delayed response arrives. document.addEventListener('visibilitychange',()=>{if(document.hidden)adminDeviceInvalidate();}); // A release reconciliation may use only the snapshot returned by its own refresh. // Never read a later poll's global snapshot or one invalidated by a tab change. function adminDeviceReleaseSnapshotCurrent(result,releaseEpoch,releaseSerial){ return result&&result.snapshot instanceof Map&& Number.isSafeInteger(result.epoch)&&result.epoch>releaseEpoch&& result.epoch===adminDeviceEpoch&&releaseSerial===adminDeviceReleaseSerial&& !document.hidden&&!$('access').classList.contains('hidden')?result.snapshot:null; } // Only the current release operation may publish its result. A tab switch, // visibility change or access-code reload invalidates a pending verification. function adminDeviceReleaseContextCurrent(epoch){ return Number.isSafeInteger(epoch)&&epoch===adminDeviceEpoch&& adminDeviceBusy===true&&!document.hidden&&!$('access').classList.contains('hidden'); } // A confirmation is bound to the exact snapshot the administrator reviewed. // An intervening refresh or code reload invalidates that review. function adminDeviceReviewStillCurrent(reviewEpoch,greenId,rink,expectedId){ return !document.hidden&&!$('access').classList.contains('hidden')&& adminDeviceAcceptResponse(reviewEpoch,adminDeviceEpoch,adminDeviceBusy)&& adminDeviceLocks instanceof Map&& adminDeviceLocks.get(v52CodeKey(greenId,rink))?.lockId===expectedId; } // Recheck the specific lock immediately before submitting a confirmed release. // The server independently enforces the same lock identity under its rink mutex. // Treat the device list as an atomic snapshot: any malformed, ambiguous or // truncated response is unavailable, never a partially trusted green indicator. function adminDeviceSnapshot(locks,truncatedPossible=false){ if(!Array.isArray(locks)||locks.length>500||truncatedPossible!==false)return null; const result=new Map(); for(const lock of locks){ if(!lock||typeof lock!=='object'||Array.isArray(lock)|| typeof lock.green_id!=='string'||!(/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i).test(lock.green_id)|| !(Number.isSafeInteger(lock.rink_number)||typeof lock.rink_number==='string'&&/^[1-9][0-9]*$/.test(lock.rink_number))|| Number(lock.rink_number)<1||Number(lock.rink_number)>40|| !['active','expired'].includes(lock.lock_state)|| !['missing','unknown','finished','unfinished'].includes(lock.match_state)|| typeof lock.requires_review!=='boolean'|| !(typeof lock.lock_id==='string'&&/^[1-9][0-9]*$/.test(lock.lock_id)||Number.isSafeInteger(lock.lock_id)&&lock.lock_id>0))return null; const id=String(lock.lock_id),key=v52CodeKey(lock.green_id,Number(lock.rink_number)); if(result.has(key))return null; result.set(key,{state:lock.lock_state,matchState:lock.match_state,review:lock.requires_review,lockId:id}); } return result; } // Validate the complete status envelope before trusting its lock snapshot. function adminDeviceEnvelope(payload){ if(!payload||typeof payload!=='object'||Array.isArray(payload)||payload.status!=='ok'|| payload.historical_window_hours!==24||typeof payload.truncated_possible!=='boolean')return null; return adminDeviceSnapshot(payload.locks,payload.truncated_possible); } function adminReleaseSnapshotMatches(locks,greenId,rink,expectedId,truncatedPossible=false){ if(typeof greenId!=='string'||!Number.isSafeInteger(rink)||rink<1||rink>40||typeof expectedId!=='string'||!/^[1-9][0-9]*$/.test(expectedId))return false; const snapshot=adminDeviceSnapshot(locks,truncatedPossible); return snapshot!==null&&snapshot.get(v52CodeKey(greenId,rink))?.lockId===expectedId; } // Bound network waits; an aborted POST may still have committed on the server. // Never infer that a failed/aborted request means its lock was not released. async function adminDeviceFetch(url,options={},timeoutMs=8000){ const controller=new AbortController(); const timer=setTimeout(()=>controller.abort(),timeoutMs); try{return await fetch(url,{...options,signal:controller.signal});} finally{clearTimeout(timer);} } function adminDeviceReleaseOutcome(responseOk,payload,greenId,rink){ if(!responseOk||!payload||payload.status!=='ok'||payload.released!==true|| payload.released_count!==1||payload.green_id!==greenId|| !Number.isSafeInteger(payload.rink)||payload.rink!==rink)return false; return true; } // Only a verified HTTP 409 conflict proves this particular expected-lock release // was rejected. Transport errors, HTTP 5xx and malformed replies remain unknown. function adminDeviceReleaseVerdict(httpStatus,payload,greenId,rink){ if(httpStatus===200&&adminDeviceReleaseOutcome(true,payload,greenId,rink))return 'released'; if(httpStatus===409&&payload&&typeof payload==='object'&&!Array.isArray(payload)&&payload.status==='conflict')return 'conflict'; return 'unverified'; } // A post-request refresh describes current state, not whether a prior POST committed. // In particular, a different lock ID must NEVER be treated as proof of success. function adminDeviceReconcileOutcome(snapshot,greenId,rink,expectedId){ if(!(snapshot instanceof Map))return 'status-unavailable'; const current=snapshot.get(v52CodeKey(greenId,rink)); if(!current)return 'lock-absent'; if(current.lockId===expectedId)return 'original-lock-present'; return 'different-lock-present'; } // Distinguish an unavailable response from a refresh superseded by another // view or operation. Neither is evidence that an uncertain POST committed. function adminDeviceRefreshDiagnostic(result,expectedEpoch,currentEpoch){ if(!result||!Number.isSafeInteger(result.epoch)||result.epoch!==currentEpoch|| result.epoch<=expectedEpoch||result.reason==='superseded')return 'superseded'; // A Map alone is insufficient: a delayed or failed request may carry a // snapshot that does not belong to the accepted verification response. if(result.reason==='network-error'||result.reason==='invalid-response'|| result.reason!=='verified'||!(result.snapshot instanceof Map))return 'unavailable'; return 'verified'; } function adminDeviceRefreshDiagnosticMessage(reason){ if(reason==='superseded')return 'Status verification was superseded by another page or device-status operation. Review a fresh Rink Access snapshot before retrying.'; if(reason==='unavailable')return 'The latest device-status request failed or returned invalid data. Refresh Rink Access before retrying.'; return ''; } // A release notice is about one reviewed lock, not merely its rink. // A replacement lock can appear after the request; never imply it was released. function adminDeviceReconcileIdentity(snapshot,greenId,rink,expectedId){ const state=adminDeviceReconcileOutcome(snapshot,greenId,rink,expectedId); if(state==='status-unavailable')return 'Current lock identity is unavailable; do not retry until a fresh snapshot is verified.'; if(state==='lock-absent')return 'Original lock '+expectedId+': no lock currently listed on this rink. This does not prove the release committed.'; if(state==='original-lock-present')return 'Original lock '+expectedId+' remains listed. Review its current status before any new action.'; const replacement=snapshot.get(v52CodeKey(greenId,rink)); return 'Original lock '+expectedId+' is no longer listed; replacement lock '+replacement.lockId+' now controls this rink. Do not retry the previous release against the replacement.'; } function adminDeviceReconcileMessage(state){ switch(state){ case 'lock-absent':return 'Current status: no device lock is listed on this rink. This does not prove which request removed it.'; case 'original-lock-present':return 'Current status: the original device lock is still listed. Review its status before considering another release.'; case 'different-lock-present':return 'Current status: a different device lock now exists. Do not retry the previous release; review the new lock separately.'; default:return 'Current device status could not be verified. Do not retry until Rink Access refresh succeeds.'; } } // A preflight GET is authoritative only for the exact lock and the still-open // release context. Never accept a stale result after code reload, tab switch, // page hiding, or a newer device snapshot. function adminDevicePreflightDecision(contextCurrent,snapshot,greenId,rink,expectedId){ if(contextCurrent!==true)return 'cancelled'; if(!(snapshot instanceof Map))return 'unavailable'; const lock=snapshot.get(v52CodeKey(greenId,rink)); if(!lock||lock.lockId!==expectedId)return 'changed'; return 'matched'; } async function adminReleasePreflight(greenId,rink,expectedId,contextEpoch=null){ if(contextEpoch!==null&&!adminDeviceReleaseContextCurrent(contextEpoch))throw Error('Rink Access view changed during verification; release cancelled'); const response=await adminDeviceFetch('/bowls_staging/api/admin_scoring_devices.php',{credentials:'same-origin',cache:'no-store'}); // Revalidate after the network wait, before consuming an expensive response. if(contextEpoch!==null&&!adminDeviceReleaseContextCurrent(contextEpoch))throw Error('Rink Access view changed during verification; release cancelled'); let payload;try{payload=await response.json()}catch{throw Error('Cannot verify current device lock; refresh Rink Access');} const current=contextEpoch===null?true:adminDeviceReleaseContextCurrent(contextEpoch); const snapshot=response.ok?adminDeviceEnvelope(payload):null; const decision=adminDevicePreflightDecision(current,snapshot,greenId,rink,expectedId); if(decision==='cancelled')throw Error('Rink Access view changed during verification; release cancelled'); if(decision!=='matched')throw Error('Device lock changed or cannot be verified. Refresh Rink Access and review again'); } async function adminDeviceRefresh(){ // Explicit post-release refresh must supersede an older in-flight poll. // The epoch prevents that poll from publishing a stale lock snapshot. if(adminDeviceBusy)return; adminDeviceRefreshing=true; const epoch=++adminDeviceEpoch; const previous=adminDeviceLocks===null?null:JSON.stringify([...adminDeviceLocks].sort(([a],[b])=>a.localeCompare(b))); try{ const r=await adminDeviceFetch('/bowls_staging/api/admin_scoring_devices.php',{credentials:'same-origin',cache:'no-store'}); let j;try{j=await r.json()}catch{throw Error('Invalid device-status response; refresh Rink Access');} if(!adminDeviceAcceptResponse(epoch,adminDeviceEpoch,adminDeviceBusy))return {epoch,reason:'superseded',snapshot:null}; if(!r.ok||!j||j.status!=='ok')throw Error('Device status unavailable; refresh Rink Access'); const verified=adminDeviceEnvelope(j); if(verified===null)throw Error('Incomplete or ambiguous device status; refresh Rink Access'); adminDeviceLocks=verified; if(typeof adminDeviceUpdateNoticeObservation==='function')adminDeviceUpdateNoticeObservation(verified); }catch(e){ if(!adminDeviceAcceptResponse(epoch,adminDeviceEpoch,adminDeviceBusy))return {epoch,reason:'superseded',snapshot:null}; adminDeviceLocks=null;$('v52AccessStatus').textContent='Device status unavailable: '+e.message; }finally{if(epoch===adminDeviceEpoch)adminDeviceRefreshing=false;} if(!adminDeviceAcceptResponse(epoch,adminDeviceEpoch,adminDeviceBusy))return {epoch,reason:'superseded',snapshot:null}; const current=adminDeviceLocks===null?null:JSON.stringify([...adminDeviceLocks].sort(([a],[b])=>a.localeCompare(b))); if(previous!==current&&!$('access').classList.contains('hidden'))v52DrawCodeRows(); return {epoch,snapshot:adminDeviceLocks,reason:adminDeviceLocks instanceof Map?'verified':'unavailable'}; } // Poll only lock state while this tab is visible and Rink Access is open. // Never poll access codes or overwrite an open confirmation dialog. setInterval(()=>{ if(!adminDevicePollAllowed(document.hidden,$('access').classList.contains('hidden'),adminDeviceBusy,adminDeviceRefreshing,$('adminDeviceDialog').open,adminDeviceReconcilePending))return; void adminDeviceRefresh(); },3000); function adminDeviceConfirmRelease(description,lock){return new Promise(resolve=>{ const d=$('adminDeviceDialog'); const warning=lock?.review?' This lock is expired and its associated match is '+String(lock.matchState||'unknown')+'. Releasing control will NOT complete, clear or recover that match. Confirm that the match has been reviewed before proceeding.':lock?.state==='active'?' This is an active device lock; the referee will immediately lose scoring control.':' This is an expired device lock. Verify the match before releasing it.'; $('adminDeviceDialogText').textContent='Force release '+description+'?'+warning; const yes=$('adminDeviceConfirm'),no=$('adminDeviceCancel'); const finish=answer=>{yes.onclick=null;no.onclick=null;d.removeEventListener('cancel',onCancel);if(d.open)d.close();resolve(answer)}; const onCancel=e=>{e.preventDefault();finish(false)}; yes.onclick=()=>finish(true);no.onclick=()=>finish(false);d.addEventListener('cancel',onCancel);d.showModal(); })} const v52CodeKey=(greenId,rink)=>greenId+'|'+rink; function v52DrawCodeRows(){ const rows=db.greens.flatMap(g=>Array.from({length:Math.min(40,Math.max(0,Number(g.rinks)||0))},(_,i)=>{ const rink=i+1,key=v52CodeKey(g.id,rink),item=v52CodeCache.get(key); const display=item?.exists?''+esc(item.code)+'':item?.error?''+esc(item.error)+'':item?'Not generated':'Not checked'; const action=item?.exists?'':item&&!item.error?'':'—'; const device=adminDeviceLocks?.get(key); const indicator=adminDeviceLocks===null?'Unknown':!device?'Free':device.state==='active'?'Active lock':device.review?'Expired — review required':'Expired lock'; const matchInfo=device?'
Match: '+esc(device.matchState)+(device.review?' · Requires review':'')+'
':''; const release=device?'':'—'; return ''+esc(g.name)+'Rink '+rink+''+display+''+action+''+indicator+matchInfo+''+release+''; })); $('accessList').innerHTML=table(['Green','Rink','MySQL code','Actions','Device status','Device control'],rows); } async function v52CodeRequest(greenId,rink,generate=false){ const path='/bowls_staging/api/admin_rink_codes.php'; const options=generate?{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json','X-Bowls-Request':'admin-rink-codes'},body:JSON.stringify({green_id:greenId,rink})}:{method:'GET',credentials:'same-origin',cache:'no-store'}; const url=generate?path:path+'?green_id='+encodeURIComponent(greenId)+'&rink='+rink; const response=await fetch(url,options);let result; try{result=await response.json()}catch{throw Error('Non-JSON server response (HTTP '+response.status+')')} if(!response.ok||result.status!=='ok')throw Error((result.message||'Request failed')+' (HTTP '+response.status+')'); if(result.green_id!==greenId||Number(result.rink)!==rink||typeof result.exists!=='boolean'||(result.exists&&!/^\d{6}$/.test(result.code||'')))throw Error('Unexpected server code response'); return result; } async function v52LoadCodes(){ if(v52Loading)return; v52Loading=true;v52CodeCache.clear();adminDeviceInvalidate();v52DrawCodeRows(); await adminDeviceRefresh(); const targets=db.greens.flatMap(g=>Array.from({length:Math.min(40,Math.max(0,Number(g.rinks)||0))},(_,i)=>({id:g.id,rink:i+1}))); const status=$('v52AccessStatus');status.textContent='Reading '+targets.length+' rink code(s) from MySQL…'; let errors=0; try{ for(const t of targets){ try{v52CodeCache.set(v52CodeKey(t.id,t.rink),await v52CodeRequest(t.id,t.rink))} catch(e){errors++;v52CodeCache.set(v52CodeKey(t.id,t.rink),{error:e.message})} if(!$('access').classList.contains('hidden'))v52DrawCodeRows(); } status.textContent=errors?'MySQL read finished with '+errors+' error(s). No codes were generated.':'MySQL read finished. Existing codes shown; missing codes were not generated.'; }finally{v52Loading=false} } $('v52RefreshCodes').addEventListener('click',v52LoadCodes); $('accessList').addEventListener('click',async event=>{ const releaseButton=event.target.closest('[data-device-release]'); if(releaseButton){ if(!adminDeviceReleaseStartAllowed(adminDeviceBusy,v52Loading,adminDeviceReconcilePending,adminDeviceRefreshing))return; const key=releaseButton.dataset.deviceRelease,sep=key.lastIndexOf('|'),id=key.slice(0,sep),rink=Number(key.slice(sep+1)); const green=db.greens.find(g=>g.id===id); if(!green||!adminDeviceLocks?.has(key))return; const reviewedLock=adminDeviceLocks.get(key); const reviewEpoch=adminDeviceEpoch; if(!/^[1-9][0-9]{0,19}$/.test(reviewedLock.lockId)){$('v52AccessStatus').textContent='Device identity unavailable; refresh before releasing.';return;} if(!await adminDeviceConfirmRelease(green.name+' — Rink '+rink,reviewedLock))return; if(!adminDeviceReleaseStartAllowed(adminDeviceBusy,v52Loading,adminDeviceReconcilePending,adminDeviceRefreshing)||!adminDeviceReviewStillCurrent(reviewEpoch,id,rink,reviewedLock.lockId)){ $('v52AccessStatus').textContent='Device status changed during confirmation. Refresh Rink Access and review the lock again.'; return; } adminDeviceClearReleaseNotice(); adminDeviceBusy=true;adminDeviceInvalidate();const submissionEpoch=adminDeviceEpoch,releaseSerial=++adminDeviceReleaseSerial;v52DrawCodeRows();releaseButton.disabled=true; let releaseSubmitted=false,releaseVerdict='not-submitted',releaseMessage=''; try{ await adminReleasePreflight(id,rink,reviewedLock.lockId,submissionEpoch); if(!adminDeviceReleaseContextCurrent(submissionEpoch))throw Error('Rink Access view changed during verification; release cancelled'); // From this point a network failure cannot prove the server did not commit. releaseSubmitted=true;releaseVerdict='unverified'; const r=await adminDeviceFetch('/bowls_staging/api/admin_scoring_devices.php',{method:'POST',credentials:'same-origin',cache:'no-store',headers:{'Content-Type':'application/json','X-Bowls-Request':'admin-scoring-devices'},body:JSON.stringify({green_id:id,rink,expected_lock_id:reviewedLock.lockId})},12000); const j=await r.json(); const verdict=adminDeviceReleaseVerdict(r.status,j,id,rink); releaseVerdict=verdict; if(verdict==='conflict'){ releaseMessage='Device lock changed; the server rejected this release of the reviewed lock. Refresh Rink Access to inspect the current owner; do not retry this request against another lock.'; }else if(verdict==='released'){ releaseMessage='Scoring device released for '+green.name+' — Rink '+rink+'.'; }else throw Error('Device release response could not be verified'); }catch(e){releaseMessage=(releaseSubmitted?'Device release outcome unverified: ':'Device release not submitted: ')+e.message;} finally{ adminDeviceBusy=false; adminDeviceReconcilePending=true; let refreshed; try{refreshed=await adminDeviceRefresh();} catch(e){refreshed={epoch:adminDeviceEpoch,reason:'network-error',snapshot:null};} finally{adminDeviceReconcilePending=false;} const reconciledSnapshot=adminDeviceReleaseSnapshotCurrent(refreshed,submissionEpoch,releaseSerial); // Refresh cannot establish whether an ambiguous POST committed; report only // the newly observed lock identity, never claim an uncertain release succeeded. if(releaseSubmitted&&(releaseVerdict==='unverified'||releaseVerdict==='not-submitted')){ const state=adminDeviceReconcileOutcome(reconciledSnapshot,id,rink,reviewedLock.lockId); releaseMessage+=' '+adminDeviceReconcileIdentity(reconciledSnapshot,id,rink,reviewedLock.lockId); const diagnostic=adminDeviceRefreshDiagnostic(refreshed,submissionEpoch,adminDeviceEpoch); if(diagnostic!=='verified')releaseMessage+=' '+adminDeviceRefreshDiagnosticMessage(diagnostic); } // A submitted POST must retain its outcome warning across tab switches. // An unsubmitted preflight cancelled by navigation does not create a hidden notice. const releaseVisible=!document.hidden&&!$('access').classList.contains('hidden'); const delivery=adminDeviceNoticeDelivery(releaseSerial,adminDeviceReleaseSerial,releaseSubmitted,releaseVisible); if(releaseSubmitted)releaseMessage='Reviewed lock '+reviewedLock.lockId+' — '+green.name+' / Rink '+rink+'. '+releaseMessage; if(delivery==='visible'||delivery==='retain'){ adminDevicePublishReleaseNotice(releaseMessage,releaseSerial,{greenId:id,rink,lockId:reviewedLock.lockId}); if(reconciledSnapshot instanceof Map)adminDeviceUpdateNoticeObservation(reconciledSnapshot); if(delivery==='visible')$('v52AccessStatus').textContent='Device release review recorded. See the release notice above.'; } } return; } const copy=event.target.closest('[data-v52-copy]'); if(copy){const item=v52CodeCache.get(copy.dataset.v52Copy);if(!item?.exists)return;try{await navigator.clipboard.writeText(item.code);toast('MySQL rink code copied')}catch{prompt('Copy MySQL rink code:',item.code)}return;} const button=event.target.closest('[data-v52-generate]');if(!button||v52Loading)return; const key=button.dataset.v52Generate,sep=key.lastIndexOf('|'),id=key.slice(0,sep),rink=Number(key.slice(sep+1)); const green=db.greens.find(g=>g.id===id);if(!green||!Number.isInteger(rink)||rink<1||rink>Number(green.rinks))return; if(!confirm('Generate today’s MySQL access code for '+green.name+' — Rink '+rink+'? Existing codes will be retained.'))return; button.disabled=true;$('v52AccessStatus').textContent='Requesting MySQL code for '+green.name+' — Rink '+rink+'…'; try{const item=await v52CodeRequest(id,rink,true);v52CodeCache.set(key,item);$('v52AccessStatus').textContent=item.created?'New MySQL code generated for '+green.name+' — Rink '+rink+'.':'Existing MySQL code retrieved for '+green.name+' — Rink '+rink+'.';} catch(e){v52CodeCache.set(key,{error:e.message});$('v52AccessStatus').textContent='Code request failed: '+e.message} v52DrawCodeRows(); }); function accessCode(id,rink){let h=2166136261;for(const c of id+':'+rink)h=Math.imul(h^c.charCodeAt(0),16777619);return String((h>>>0)%900000+100000)}function copyCode(s){navigator.clipboard?.writeText(s).then(()=>toast('Code copied')).catch(()=>prompt('Copy demo code:',s))||prompt('Copy demo code:',s)} let matchPowerDraft={A:[],B:[]}; function renderMatchPowerChoices(){ const host=$('matchPowerChoices');if(!host)return; const enabled=!!$('f_power')?.checked&&!$('f_pointsMode')?.checked;host.classList.toggle('hidden',!enabled); if(!enabled)return; const count=$('f_pointsMode')?.checked?60:Math.max(1,Math.min(60,Number($('f_ends')?.value)||10)); for(const side of ['A','B']){ const root=$('matchPowerGrid'+side);if(!root)continue; root.replaceChildren(); for(let end=1;end<=count;end++){ const b=document.createElement('button');b.type='button';b.textContent=end; const chosen=matchPowerDraft[side].includes(end); b.className='match-power-end'+(chosen?' selected-'+side.toLowerCase():''); b.setAttribute('aria-pressed',String(chosen)); b.onclick=()=>{matchPowerDraft[side]=chosen?matchPowerDraft[side].filter(n=>n!==end):[...matchPowerDraft[side],end].sort((a,b)=>a-b);renderMatchPowerChoices()}; root.append(b); } } } let temporaryOriginal=null,cropImage=null,cropScale=1,cropX=0,cropY=0,cropBase=1,cropPointer=null; function positionCrop(){ const view=$('cropViewport'),im=$('cropSource');if(!cropImage)return; const w=view.clientWidth,h=view.clientHeight,sw=cropImage.naturalWidth*cropBase*cropScale,sh=cropImage.naturalHeight*cropBase*cropScale; cropX=Math.min(0,Math.max(w-sw,cropX));cropY=Math.min(0,Math.max(h-sh,cropY)); im.style.width=sw+'px';im.style.height=sh+'px';im.style.left=cropX+'px';im.style.top=cropY+'px'; } function resetPhotoCrop(){if(!cropImage)return;const v=$('cropViewport');cropBase=Math.max(v.clientWidth/cropImage.naturalWidth,v.clientHeight/cropImage.naturalHeight);cropScale=1;cropX=(v.clientWidth-cropImage.naturalWidth*cropBase)/2;cropY=(v.clientHeight-cropImage.naturalHeight*cropBase)/2;$('cropZoom').value='1';positionCrop()} function setCropZoom(value){ const v=$('cropViewport'),old=cropScale,centerX=v.clientWidth/2,centerY=v.clientHeight/2; cropScale=Math.min(4,Math.max(1,Number(value)));cropX=centerX-(centerX-cropX)*cropScale/old;cropY=centerY-(centerY-cropY)*cropScale/old; $('cropZoom').value=String(cropScale);positionCrop(); } function openPhotoCrop(src){ $('cropTitle').textContent=formType==='club'?'Adjust club logo':'Adjust player photograph'; const im=new Image();im.onload=()=>{cropImage=im;$('cropSource').src=src;$('photoCropDialog').showModal();requestAnimationFrame(resetPhotoCrop)}; im.onerror=()=>alert('Unable to load the image.');im.src=src; } function savePhotoCrop(){ if(!cropImage)return;const v=$('cropViewport'),canvas=document.createElement('canvas'),ratio=300/v.clientWidth; canvas.width=300;canvas.height=Math.round(v.clientHeight*ratio); canvas.getContext('2d').drawImage(cropImage,cropX*ratio,cropY*ratio,cropImage.naturalWidth*cropBase*cropScale*ratio,cropImage.naturalHeight*cropBase*cropScale*ratio); temporaryImage=canvas.toDataURL('image/jpeg',.82); $('imagePreview').src=temporaryImage;$('imagePreview').classList.remove('hidden');$('photoCropDialog').close(); } document.addEventListener('DOMContentLoaded',()=>{ $('cropZoom').addEventListener('input',e=>setCropZoom(e.target.value)); const v=$('cropViewport'); v.addEventListener('pointerdown',e=>{if(!cropImage)return;cropPointer={id:e.pointerId,x:e.clientX,y:e.clientY};v.setPointerCapture(e.pointerId)}); v.addEventListener('pointermove',e=>{if(!cropPointer||cropPointer.id!==e.pointerId)return;cropX+=e.clientX-cropPointer.x;cropY+=e.clientY-cropPointer.y;cropPointer.x=e.clientX;cropPointer.y=e.clientY;positionCrop()}); const end=e=>{if(cropPointer?.id===e.pointerId)cropPointer=null};v.addEventListener('pointerup',end);v.addEventListener('pointercancel',end); v.addEventListener('wheel',e=>{e.preventDefault();setCropZoom(cropScale*(e.deltaY<0?1.08:.92))},{passive:false}); }); // V51: Rink choices follow the selected green's configured rink count. function updateMatchRinkOptions(preferred){ const green=find('greens',$('f_greenId')?.value); const select=$('f_rink');if(!select)return; const previous=preferred??select.value; const count=green?Number(green.rinks):0; select.innerHTML=''+ Array.from({length:Number.isInteger(count)&&count>0&&count<=40?count:0},(_,i)=>``).join(''); select.value=String(previous); if(select.selectedIndex<0)select.value=''; select.disabled=!green; } function openForm(type,id=null){formType=type;editId=id;temporaryImage=null;const coll=type==='green'?'greens':type==='match'?'matches':type+'s',item=id?find(coll,id):null;temporaryImage=item?.image||null;temporaryOriginal=item?.imageOriginal||item?.image||null;$('formTitle').textContent=(item?'Edit ':'Add ')+({competition:'Competition',club:'Club',player:'Player',green:'Green',match:'Match',team:'Team',slot:'Time Slot'}[type]);let html='';if(type==='competition')html=fld('Competition name','name',item?.name||'')+fld('Description (optional)','description',item?.description||'')+`
These rules are applied automatically when this competition is selected for a new match. Player assignments remain match-specific.
${sel('Match format','format',Object.keys(positions).map(x=>[x,x]),item?.format||'Pairs')}${fld('Number of ends','ends',item?.ends||db.settings.ends,'number','min="1" max="60"')}
${ck('Points mode (first to target score)','pointsMode',item?.pointsMode)}${fld('Points target','target',item?.target||db.settings.points,'number','min="1"')}${ck('Enable Power Ends','power',item?.power??db.settings.power)}${sel('Power End multiplier','mult',[['2','×2'],['3','×3']],item?.mult||db.settings.mult)}`;if(type==='club'||type==='player'){html=fld(type==='club'?'Club name':'Player name','name',item?.name||'');if(type==='club')html+=fld('Short name (optional)','short',item?.short||'');else html+=`
`;html+=`

Click the photo or logo to adjust its crop. Drag to position and zoom to fit. Images are stored locally.

Preview
`}if(type==='green')html=fld('Green name','name',item?.name||'Green A')+fld('Number of rinks','rinks',item?.rinks||6,'number','min="1" max="40"');if(type==='match'){html=`
${sel('Rink number','rink',[],item?.rink||1)}${fld('Scheduled date and time','date',item?.date||dateNow(),'datetime-local')}
${teamFieldHTML('A',item)}${teamFieldHTML('B',item)}
${fld('Team A name','nameA',item?.nameA||'Team A')}${fld('Team B name','nameB',item?.nameB||'Team B')}
${sel('Match format','format',Object.keys(positions).map(x=>[x,x]),item?.format||'Pairs')}${fld('Number of ends','ends',item?.ends||db.settings.ends,'number','min="1" max="60"')}
${ck('Points mode (first to target score)','pointsMode',item?.pointsMode)}${fld('Points target','target',item?.target||db.settings.points,'number','min="1"')}${ck('Enable Power Ends','power',item?.power??db.settings.power)}${sel('Power End multiplier','mult',[['2','×2'],['3','×3']],item?.mult||db.settings.mult)}
Assign each player to their position. Select an existing club player or enter a name for a casual match. The referee can review or amend these details when the connected system is developed.
`}if(type==='slot')html=fld('Time slot name','name',item?.name||'Time Slot '+(db.slots.length+1))+fld('Date and time','date',item?.date||dateNow(),'datetime-local','required'); if(type==='team')html=fld('Team name (optional — auto from players)','name',item?.name||'')+sel('Team format','format',Object.keys(positions).map(x=>[x,x]),item?.format||'Pairs')+teamPositionsHTML(item); $('formFields').innerHTML=html;if(type==='match'){ $('f_greenId').addEventListener('change',()=>updateMatchRinkOptions()); updateMatchRinkOptions(item?.rink); matchPowerDraft={A:[...(item?.powerA||[])],B:[...(item?.powerB||[])]}; for(const name of ['power','ends','pointsMode'])$('f_'+name)?.addEventListener('change',renderMatchPowerChoices); $('f_ends')?.addEventListener('input',renderMatchPowerChoices); renderMatchPowerChoices(); } if(type==='team'){$('f_format').addEventListener('change',()=>updateTeamPositionFields(item));wireTeamSelects()} if(type==='match'){for(const side of ['A','B']){const initial=item?.['name'+side]||'';const generated=(positions[item?.format||'Pairs']||[]).map(pos=>item?.lineups?.[side]?.[pos]?.name?.trim()||'').filter(Boolean).join(' / ');teamNameManual[side]=!!item&&!!initial&&initial!==generated&&initial!==`Team ${side}`;const field=$('formFields').querySelector(`[name="name${side}"]`);field.addEventListener('input',()=>{teamNameManual[side]=!!field.value.trim();if(!teamNameManual[side])updateAutomaticTeamNames()})}for(const side of ['A','B'])$('f_savedTeam'+side).addEventListener('change',()=>applySavedTeam(side));$('f_slotId').addEventListener('change',e=>setSlotDate(e.target.value));const fmt=$('f_format');fmt.addEventListener('change',()=>{drawPositionFields(fmt.value);refreshSavedTeamOptions()});drawPositionFields(fmt.value,item);refreshSavedTeamOptions();const comp=$('formFields').querySelector('[name=competitionId]');comp.addEventListener('change',()=>applyCompetitionDefaults(comp.value));if(!item&&comp.value)applyCompetitionDefaults(comp.value);refreshSavedTeamOptions()}if(type==='club'||type==='player'){$('imageFile').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;if(!['image/png','image/jpeg','image/webp'].includes(file.type))return alert('Choose a PNG, JPEG or WebP image.');if(file.size>3000000)return alert('Choose an image smaller than 3 MB for local storage.');temporaryOriginal=await new Promise((resolve,reject)=>{const r=new FileReader;r.onload=()=>resolve(r.result);r.onerror=reject;r.readAsDataURL(file)});openPhotoCrop(temporaryOriginal)});$('imagePreview').onclick=()=>{if(temporaryOriginal||temporaryImage)openPhotoCrop(temporaryOriginal||temporaryImage)};$('removeImage').onclick=()=>{temporaryImage=null;temporaryOriginal=null;$('imagePreview').classList.add('hidden');$('imageFile').value=''}}$('editor').showModal()} $('editForm').onsubmit=e=>{e.preventDefault();const fd=new FormData(e.currentTarget),type=formType,coll=type==='green'?'greens':type==='match'?'matches':type+'s',existing=editId?find(coll,editId):null;let x={...existing,id:editId||uid()};for(const [k,v] of fd.entries())x[k]=String(v).trim();if(type==='club'||type==='player'){x.image=temporaryImage;x.imageOriginal=temporaryOriginal;} if(type==='slot'){x.name=normalizedSlotName(x.name);if(!x.name||!x.date)return alert('Enter a time slot name and date/time.');if(existing&&existing.date!==x.date){const linked=db.matches.filter(m=>m.slotId===x.id);if(linked.length&&!confirm(`Update the scheduled date/time of ${linked.length} match(es) in this slot?`))return;linked.forEach(m=>m.date=x.date)}} if(type==='team'){x.format=fd.get('format');x.lineup={};const used=new Set();for(const pos of positions[x.format]){const pid=fd.get('pick_'+pos)||'',name=String(fd.get('name_'+pos)||'').trim(),key=(pid||name.toLowerCase());if(key&&used.has(key))return alert('Each player can only occupy one position in a team.');if(key)used.add(key);x.lineup[pos]={playerId:pid,name}}if(!x.name)x.name=positions[x.format].map(pos=>x.lineup[pos].name).filter(Boolean).join(' / ');if(!x.name)return alert('Assign at least one player or enter a team name.')}if(type==='green'){x.rinks=Number(x.rinks);if(!Number.isInteger(x.rinks)||x.rinks<1||x.rinks>40)return alert('Rinks must be between 1 and 40.');if(existing&&db.matches.some(m=>m.greenId===x.id&&Number(m.rink)>x.rinks))return alert('Cannot reduce the number of rinks while matches are assigned to higher-numbered rinks.')}if(type==='competition'){x.ends=Number(x.ends);x.target=Number(x.target);x.mult=Number(x.mult);x.pointsMode=fd.has('pointsMode');x.power=fd.has('power');if(x.ends<1||x.ends>60||x.target<1)return alert('Check competition ends and points target.')}if(type==='match'){if(x.slotId){const slot=find('slots',x.slotId);if(!slot)return alert('Choose a valid time slot.');x.date=slot.date;}else{if(!x.date||Number.isNaN(new Date(x.date).getTime()))return alert('Enter a valid scheduled date and time.');let slot=db.slots.find(t=>t.date===x.date);if(!slot){slot={id:uid(),name:'Time Slot '+(db.slots.length+1),date:x.date};db.slots.push(slot)}x.slotId=slot.id;}x.rink=Number(x.rink);x.ends=Number(x.ends);x.target=Number(x.target);x.mult=Number(x.mult);x.pointsMode=fd.has('pointsMode');x.power=fd.has('power');x.powerA=[...matchPowerDraft.A];x.powerB=[...matchPowerDraft.B];x.lineups={A:{},B:{}};for(const side of ['A','B'])for(const pos of positions[x.format]){const base=side+'_'+pos.replaceAll(' ','_');x.lineups[side][pos]={playerId:fd.get('pick_'+base)||'',name:String(fd.get('name_'+base)||'').trim()};}const usedIds=new Set(),usedNames=new Set();for(const side of ['A','B'])for(const pos of positions[x.format]){const entry=x.lineups[side][pos],pid=entry.playerId,nm=entry.name.trim().toLocaleLowerCase();if(pid&&usedIds.has(pid))return alert('A player can only be assigned to one position in a match. Please choose a different player for '+side+' '+pos+'.');if(nm&&usedNames.has(nm))return alert('The same player name appears more than once in this match. Please choose a different player for '+side+' '+pos+'.');if(pid)usedIds.add(pid);if(nm)usedNames.add(nm);}if(x.teamAId&&x.teamBId&&x.teamAId===x.teamBId)return alert('A team cannot play against itself.');for(const side of ['A','B']){const selected=x['team'+side+'Id']?find('teams',x['team'+side+'Id']):null;if(selected&&selected.format!==x.format)return alert('Saved Team '+side+' does not match the match format.')}x.status=existing?.status||'scheduled';const green=find('greens',x.greenId);if(!green)return alert('Choose a green first.');if(!Number.isInteger(x.rink)||x.rink<1||x.rink>Number(green.rinks))return alert('Select a valid rink within the selected green.');if(x.ends<1||x.ends>60||x.target<1)return alert('Check ends and target values.');const clash=db.matches.some(m=>m.id!==x.id&&m.greenId===x.greenId&&Number(m.rink)===x.rink&&(x.slotId?slotKey(m)===slotKey(x):!m.slotId&&m.date===x.date));if(clash)return alert('This rink already has an unfinished assigned match. Move or complete that match first.');}else if(type==='competition'||type==='club'||type==='player'||type==='green'){if(!x.name)return alert('Enter a name.')}if(type==='competition'&&existing){ const linked=db.matches.filter(m=>m.competitionId===x.id); const changed=['format','ends','target','mult','pointsMode','power'].some(k=>String(existing[k])!==String(x[k])); if(changed&&linked.length){ const active=linked.filter(m=>m.status==='inplay'||m.status==='completed').length; if(!confirm('Update '+linked.length+' existing match(es) using this competition to the new rules?\n\nPlayer names already assigned will be preserved. New positions will be left empty for you to fill in.'+(active?'\n\nWARNING: '+active+' match(es) are in play or completed. Their existing scores will not be recalculated.':'')))return; for(const m of linked){ m.format=x.format;m.ends=x.ends;m.target=x.target;m.mult=x.mult;m.pointsMode=x.pointsMode;m.power=x.power; const old=m.lineups||{};const updated={A:{},B:{}}; for(const side of ['A','B'])for(const pos of positions[x.format])updated[side][pos]=old[side]?.[pos]||{playerId:'',name:''}; m.lineups=updated; } } } if(existing)Object.assign(existing,x);else db[coll].push(x);save();$('editor').close();render();toast((existing?'Updated ':'Added ')+type)}; function removeItem(type,id){ const coll=type==='green'?'greens':type==='match'?'matches':type+'s',x=find(coll,id);if(!x)return; if(type==='slot'){ const linked=db.matches.filter(m=>m.slotId===id); if(linked.length){ const details=linked.slice(0,6).map(m=>'• '+(m.nameA||'Team A')+' vs '+(m.nameB||'Team B')+' — '+greenName(m.greenId)+' · Rink '+m.rink).join('\n'); const extra=linked.length>6?'\n… and '+(linked.length-6)+' more.':''; const otherSlots=db.slots.filter(t=>t.id!==id); const choice=prompt('"'+(x.name||'Time slot')+'" has '+linked.length+' assigned match(es):\n'+details+extra+'\n\nChoose an action:\n1 = Cancel and keep the time slot\n2 = Move these matches to another time slot'+(otherSlots.length?'':' (unavailable: no other slots)')+'\n3 = Delete this time slot AND its '+linked.length+' match(es), including their scores\n\nEnter 1, 2 or 3:', '1'); if(choice==='2'){ if(!otherSlots.length)return alert('Create another time slot first, then try again.'); const options=otherSlots.map((t,i)=>(i+1)+'. '+normalizedSlotName(t.name)+' — '+t.date.replace('T',' ')).join('\n'); const target=prompt('Move all '+linked.length+' matches to which time slot?\n'+options+'\n\nEnter its number:'); if(target===null)return; const index=Number(target)-1,dest=otherSlots[index]; if(!Number.isInteger(index)||!dest)return alert('No changes made. Select a valid destination number.'); const movingIds=new Set(linked.map(m=>m.id)); const occupied=db.matches.some(m=>!movingIds.has(m.id)&&m.slotId===dest.id&&linked.some(l=>l.greenId===m.greenId&&Number(l.rink)===Number(m.rink))); if(occupied)return alert('Cannot move: a destination rink already has a match in that time slot. Use Move / Swap on the Overview to resolve conflicts first.'); if(!confirm('Move '+linked.length+' match(es) to '+normalizedSlotName(dest.name)+' and remove '+normalizedSlotName(x.name)+'? Match results will be preserved.'))return; linked.forEach(m=>{m.slotId=dest.id;m.date=dest.date}); db.slots=db.slots.filter(t=>t.id!==id);save();render();toast('Matches moved and time slot deleted');return; } if(choice==='3'){ if(!confirm('WARNING: Delete '+normalizedSlotName(x.name)+' and permanently delete ALL '+linked.length+' assigned match(es), including recorded results?'))return; const typed=prompt('To confirm permanent deletion, type DELETE '+linked.length+':'); if(typed!=='DELETE '+linked.length)return alert('Deletion cancelled. Nothing was changed.'); db.matches=db.matches.filter(m=>m.slotId!==id);db.slots=db.slots.filter(t=>t.id!==id);save();render();toast('Time slot and assigned matches deleted');return; } return; } } if(type==='green'&&db.matches.some(m=>m.greenId===id))return alert('Move or delete matches assigned to this green before deleting it.'); if(!confirm(`Delete ${x.name||'this match'}? This cannot be undone.`))return; db[coll]=db[coll].filter(y=>y.id!==id);save();render();toast('Deleted') };function saveSettings(){const ends=Number($('defaultEnds').value),points=Number($('defaultPoints').value);if(!Number.isInteger(ends)||ends<1||ends>60||!Number.isInteger(points)||points<1)return alert('Check the default values.');db.settings={...db.settings,ends,points,power:$('defaultPower').checked,mult:Number($('defaultMult').value)};save();toast('Defaults saved')};function exportData(){const b=new Blob([JSON.stringify(db,null,2)],{type:'application/json'}),u=URL.createObjectURL(b),a=document.createElement('a');a.href=u;a.download='lawn_bowls_admin_backup_'+new Date().toISOString().slice(0,10)+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)}async function importData(e){const f=e.target.files[0];if(!f)return;try{const x=JSON.parse(await f.text());if(!Array.isArray(x.clubs)||!Array.isArray(x.players)||!Array.isArray(x.greens)||!Array.isArray(x.matches)||!Array.isArray(x.competitions))throw Error('Invalid backup');if(!confirm('RESTORE COMPLETE EVENT BACKUP?\n\nThis will overwrite ALL current competitions, clubs, players, teams, time slots, greens, matches, scores and settings.\n\nThis cannot be undone. Continue?'))return;db={...blank(),...x};for(const group of ['competitions','teams','matches'])for(const item of db[group]||[])if(item.format==='Triples')item.format='Trips';if(!Array.isArray(db.teams)||!Array.isArray(db.slots))throw Error('Invalid teams or time slots');save();render();toast('Complete event backup restored')}catch(err){alert('Could not import: '+err.message)}finally{e.target.value=''}}// Import/export individual lists in the same JSON format as the full prototype backup. let pendingListImport=null; function exportList(kind){ if(!['clubs','players'].includes(kind))return; if(!confirm('Export your '+kind+' list ('+db[kind].length+' entries) as a JSON file?'))return; const payload={type:'lawn-bowls-'+kind,version:1,exportedAt:new Date().toISOString(),[kind]:db[kind]}; const blob=new Blob([JSON.stringify(payload,null,2)],{type:'application/json'}); const url=URL.createObjectURL(blob),link=document.createElement('a'); link.href=url;link.download='lawn_bowls_'+kind+'_'+new Date().toISOString().slice(0,10)+'.json'; document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),1000); } function chooseListImport(kind){ if(!['clubs','players'].includes(kind))return; pendingListImport=kind;const input=$('listImportFile');input.value='';input.click(); } $('listImportFile').addEventListener('change',async event=>{ const kind=pendingListImport,file=event.target.files?.[0];event.target.value='';pendingListImport=null; if(!file||!['clubs','players'].includes(kind))return; try{ const payload=JSON.parse(await file.text()); const records=Array.isArray(payload)?payload:payload?.[kind]; if(!Array.isArray(records))throw Error('Expected a JSON '+kind+' list or a backup containing a '+kind+' list.'); if(records.length>10000)throw Error('The list is too large.'); const ids=new Set(); const validated=records.map((entry,i)=>{ if(!entry||typeof entry!=='object'||Array.isArray(entry)||typeof entry.name!=='string'||!entry.name.trim())throw Error('Entry '+(i+1)+' needs a name.'); if(entry.id!=null&&typeof entry.id!=='string')throw Error('Entry '+(i+1)+' has an invalid ID.'); const id=entry.id||uid();if(ids.has(id))throw Error('Duplicate ID in imported list: '+id);ids.add(id); const clean={id,name:entry.name.trim()}; if(kind==='clubs'){ clean.short=typeof entry.short==='string'?entry.short:''; }else{ clean.clubId=typeof entry.clubId==='string'?entry.clubId:''; } if(typeof entry.image==='string'&&/^data:image\/(png|jpeg|webp);base64,/i.test(entry.image))clean.image=entry.image; return clean; }); const dependent=kind==='clubs'?'Existing player club links may no longer match the imported clubs.':'Existing match lineups may refer to players that are replaced.'; if(!confirm('REPLACE ALL '+kind.toUpperCase()+'?\n\nImport '+validated.length+' entries and overwrite your current '+db[kind].length+' '+kind+'.\n\n'+dependent+'\n\nThis cannot be undone. Continue?'))return; db[kind]=validated;save();render();toast(kind==='clubs'?'Clubs replaced successfully':'Players replaced successfully'); }catch(error){alert('Import failed: '+error.message)} }); function resetDemo(){if(!confirm('Clear ALL local administrator prototype data?'))return;db=blank();save();render();toast('Prototype data cleared')}render(); /* V32 stage 1: read-only connectivity check. Do not load database records into the local application or change the existing save() function yet. */ (async function checkV32Database() { const status = document.getElementById('v32DbStatus'); try { const response = await fetch('/bowls_staging/api/admin_records.php', { method: 'GET', credentials: 'same-origin', cache: 'no-store' }); if (response.status === 401) { status.textContent = 'MySQL: Login required'; return; } if (!response.ok) throw new Error('HTTP ' + response.status); const result = await response.json(); if (result.status !== 'ok' || !Array.isArray(result.records)) { throw new Error('Unexpected database response'); } status.textContent = 'MySQL: Connected (read-only)'; status.title = 'Database records available: ' + result.records.length + '. Browser data remains unchanged.'; } catch (error) { status.textContent = 'MySQL: Connection unavailable'; status.title = String(error.message || error); console.warn('V32 read-only database check failed:', error); } })(); /* V33 stage 2: explicit, create-only competition upload. No changes to save(). Revisions, deletes, and automatic writes require further API integration. */ (function setupV33CompetitionUpload(){ const message = document.getElementById('v33SyncMessage'); const checkButton = document.getElementById('v33CheckButton'); const uploadButton = document.getElementById('v33UploadButton'); let busy = false; async function readRecords(){ const response = await fetch('/bowls_staging/api/admin_records.php', {credentials:'same-origin', cache:'no-store'}); if(!response.ok) throw new Error('MySQL read failed (HTTP '+response.status+')'); const payload = await response.json(); if(payload.status !== 'ok' || !Array.isArray(payload.records)) throw new Error('Unexpected MySQL response'); return payload.records; } function setBusy(value){busy=value;checkButton.disabled=value;uploadButton.disabled=value;} checkButton.addEventListener('click', async function(){ if(busy)return; setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='competition'); const ids=new Set(remote.map(r=>String(r.record_id))); const pending=db.competitions.filter(c=>!ids.has(String(c.id))); message.textContent='Browser competitions: '+db.competitions.length+'; MySQL competitions: '+remote.length+'; new competitions available to upload: '+pending.length+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); uploadButton.addEventListener('click', async function(){ if(busy)return; setBusy(true); try{ const records=await readRecords(); const ids=new Set(records.filter(r=>r.record_type==='competition').map(r=>String(r.record_id))); const pending=db.competitions.filter(c=>c&&typeof c.id==='string'&&c.id&&!ids.has(c.id)); if(!pending.length){message.textContent='No new competitions to upload. Existing MySQL records were left unchanged.';return;} if(!confirm('Upload '+pending.length+' NEW competition(s) to MySQL?\n\nExisting database competitions will not be changed. This does not activate automatic synchronisation.'))return; let uploaded=0, conflicts=0, failures=0; for(const competition of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php', { method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'competition',record_id:competition.id,expected_revision:0,data:competition}) }); const result=await response.json(); if(response.ok&&result.status==='ok')uploaded++; else if(response.status===409)conflicts++; else {failures++;console.warn('V33 competition upload rejected:',competition.id,response.status,result.message);} }catch(e){failures++;console.warn('V33 competition upload failed:',competition.id,e);} } message.textContent='Upload finished: '+uploaded+' created, '+conflicts+' already existed/conflicted, '+failures+' failed. Browser data was not changed.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V34: explicit revision-checked update of a single existing competition. No changes to V30 save(), browser data, or deletion behavior. */ (function setupV34CompetitionUpdates(){ const select=document.getElementById('v34CompetitionSelect'); const compare=document.getElementById('v34CompareButton'); const update=document.getElementById('v34UpdateButton'); const message=document.getElementById('v34UpdateMessage'); let checked=null, busy=false; function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const current=select.value; select.replaceChildren(); for(const c of db.competitions){ const opt=document.createElement('option'); opt.value=String(c.id);opt.textContent=String(c.name||c.id); select.appendChild(opt); } if([...select.options].some(o=>o.value===current))select.value=current; if(!select.options.length)message.textContent='No browser competitions available.'; } async function remoteRecord(id){ const response=await fetch('/bowls_staging/api/admin_records.php',{credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records.find(r=>r.record_type==='competition'&&String(r.record_id)===id)||null; } function setBusy(v){busy=v;compare.disabled=v;select.disabled=v;update.disabled=v||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return; invalidate();refreshOptions(); const id=select.value, local=db.competitions.find(c=>String(c.id)===id); if(!local){message.textContent='Choose a competition first.';return;} setBusy(true); try{ const remote=await remoteRecord(id); if(!remote){message.textContent='This competition is not in MySQL yet. Use the new competition upload feature.';return;} if(JSON.stringify(local)===JSON.stringify(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.'; return; } checked={id,revision:Number(remote.revision),localSnapshot:JSON.stringify(local),remoteSnapshot:JSON.stringify(remote.data)}; message.textContent='Differences found for "'+local.name+'". MySQL revision '+remote.revision+'. Review the competition in the browser before confirming the update.'; }catch(e){message.textContent='Comparison failed: '+e.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const c=db.competitions.find(x=>String(x.id)===checked.id); if(!c||JSON.stringify(c)!==checked.localSnapshot){ invalidate();message.textContent='Browser competition changed since comparison. Compare again.';return; } const revision=checked.revision,id=checked.id,snapshot=checked.localSnapshot; if(!confirm('Update the existing MySQL record for "'+c.name+'"?\n\nThis replaces that competition record only. Browser data will not be changed. Database revision must still match '+revision+'.'))return; setBusy(true); try{ const latest=await remoteRecord(id); if(!latest||Number(latest.revision)!==revision||JSON.stringify(latest.data)!==checked.remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.'; return; } if(JSON.stringify(db.competitions.find(x=>String(x.id)===id))!==snapshot){ message.textContent='Update stopped: browser competition changed. Compare again.'; return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'competition',record_id:id,expected_revision:revision,data:JSON.parse(snapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok'){ message.textContent='MySQL competition updated successfully to revision '+result.revision+'. Browser data unchanged.'; }else if(response.status===409){ message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; }else{ message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); } }catch(e){message.textContent='Update failed: '+e.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V36: controlled, create-only upload for browser clubs. */ (function setupV36ClubUpload(){ const check=document.getElementById('v36ClubCheck'); const upload=document.getElementById('v36ClubUpload'); const message=document.getElementById('v36ClubMessage'); let busy=false; function setBusy(v){busy=v;check.disabled=v;upload.disabled=v;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function pendingClubs(records){ const ids=new Set(records.filter(r=>r.record_type==='club').map(r=>String(r.record_id))); return db.clubs.filter(c=>c&&typeof c.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(c.id)&&!ids.has(c.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='club'); const pending=pendingClubs(records); const invalid=db.clubs.filter(c=>!c||typeof c.id!=='string'||!/^[a-zA-Z0-9_-]+$/.test(c.id)).length; message.textContent='Browser clubs: '+db.clubs.length+'; MySQL clubs: '+remote.length+'; new clubs available to upload: '+pending.length+(invalid?'; invalid club IDs skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingClubs(records); if(!pending.length){message.textContent='No new clubs to upload. Existing MySQL clubs were left unchanged.';return;} if(!window.confirm('Upload '+pending.length+' NEW club(s) to MySQL?\n\nExisting MySQL records will not be overwritten. Club images, if present, are included. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const club of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'club',record_id:club.id,expected_revision:0,data:club}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else {failed++;console.warn('V36 club upload rejected',club.id,response.status,result.message);} }catch(e){failed++;console.warn('V36 club upload failed',club.id,e);} } message.textContent='Club upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V37: explicit revision-checked update of one existing club; browser data stays authoritative. */ (function setupV37ClubUpdates(){ const select=document.getElementById('v37ClubSelect'); const compare=document.getElementById('v37ClubCompare'); const update=document.getElementById('v37ClubUpdate'); const message=document.getElementById('v37ClubMessage'); let checked=null,busy=false; function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const current=select.value; select.replaceChildren(); for(const c of db.clubs){ if(!c||typeof c.id!=='string')continue; const opt=document.createElement('option');opt.value=c.id;opt.textContent=String(c.name||c.id); select.appendChild(opt); } if([...select.options].some(o=>o.value===current))select.value=current; if(!select.options.length)message.textContent='No browser clubs available.'; } async function remoteRecord(id){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records.find(r=>r.record_type==='club'&&String(r.record_id)===id)||null; } function setBusy(value){busy=value;compare.disabled=value;select.disabled=value;update.disabled=value||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return; invalidate(); const id=select.value,local=db.clubs.find(c=>String(c.id)===id); if(!local){message.textContent='Choose a club first.';return;} setBusy(true); try{ const remote=await remoteRecord(id); if(!remote){message.textContent='This club is not in MySQL yet. Use the new club upload feature.';return;} if(JSON.stringify(local)===JSON.stringify(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.'; return; } checked={id,revision:Number(remote.revision),localSnapshot:JSON.stringify(local),remoteSnapshot:JSON.stringify(remote.data)}; message.textContent='Differences found for "'+local.name+'". Browser short name: '+(local.short||'(empty)')+'; MySQL short name: '+(remote.data?.short||'(empty)')+'. MySQL revision '+remote.revision+'. Review the club before confirming.'; }catch(e){message.textContent='Comparison failed: '+e.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const club=db.clubs.find(c=>String(c.id)===checked.id); if(!club||JSON.stringify(club)!==checked.localSnapshot){ invalidate();message.textContent='Browser club changed since comparison. Compare again.';return; } const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL record for "'+club.name+'"?\n\nOnly this club will be updated. Browser data stays unchanged. The database revision must still match '+revision+'.'))return; setBusy(true); try{ const latest=await remoteRecord(id); if(!latest||Number(latest.revision)!==revision||JSON.stringify(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(JSON.stringify(db.clubs.find(c=>String(c.id)===id))!==localSnapshot){ message.textContent='Update stopped: browser club changed. Compare again.';return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'club',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok')message.textContent='MySQL club updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(e){message.textContent='Update failed: '+e.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V35: isolated, test-only MySQL deletion. Does not modify db, save(), or V34. */ (function setupV35TestDeletion(){ const allowed=[ '32ede844-d499-4cac-83fa-3e3120454691', '32f0f0df-70f9-4a97-83bd-f2fada1b89f7' ]; const select=document.getElementById('v35DeleteSelect'); const check=document.getElementById('v35CheckDelete'); const details=document.getElementById('v35DeleteDetails'); const phrase=document.getElementById('v35DeletePhrase'); const remove=document.getElementById('v35DeleteButton'); const message=document.getElementById('v35DeleteMessage'); let checked=null,busy=false; allowed.forEach((id,i)=>{ const option=document.createElement('option'); option.value=id; option.textContent='Test competition '+(i+1)+' ('+id.slice(0,8)+'…)'; select.appendChild(option); }); function invalidate(){ checked=null;phrase.value='';phrase.disabled=true;remove.disabled=true; details.classList.add('hidden');details.replaceChildren(); } function setBusy(value){ busy=value;check.disabled=value;select.disabled=value; phrase.disabled=value||!checked; remove.disabled=value||!checked||phrase.value!=='DELETE TEST COMPETITION'; } async function getRemote(id){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Unexpected MySQL response'); return payload.records.find(r=>r.record_type==='competition'&&String(r.record_id)===id)||null; } select.addEventListener('change',()=>{ invalidate();message.textContent='Selection changed. Check MySQL again before deleting.'; }); phrase.addEventListener('input',()=>{ remove.disabled=busy||!checked||phrase.value!=='DELETE TEST COMPETITION'; }); check.addEventListener('click',async()=>{ if(busy)return; invalidate(); const id=select.value; if(!allowed.includes(id))return; setBusy(true); try{ const remote=await getRemote(id); if(!remote){message.textContent='This test competition does not exist in MySQL. Nothing to delete.';return;} const rev=Number(remote.revision); if(!Number.isSafeInteger(rev)||rev<1)throw Error('Invalid MySQL revision'); checked={id,revision:rev,snapshot:JSON.stringify(remote.data)}; const heading=document.createElement('strong'); heading.textContent='MySQL record: '+String(remote.data?.name||'(unnamed competition)'); const lines=document.createElement('div'); lines.style.marginTop='7px'; lines.textContent='ID: '+id+' | Revision: '+rev+' | Last updated: '+String(remote.updated_at||'not supplied'); details.append(heading,lines);details.classList.remove('hidden'); message.textContent='Record found. Check its identity and revision above before typing the deletion phrase.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); remove.addEventListener('click',async()=>{ if(busy||!checked||phrase.value!=='DELETE TEST COMPETITION')return; const target={...checked}; if(!allowed.includes(target.id))return; const name=details.querySelector('strong')?.textContent||target.id; if(!window.confirm('PERMANENT MySQL DELETION\n\n'+name+'\nRecord ID: '+target.id+'\nChecked revision: '+target.revision+'\n\nThis deletes the MySQL record ONLY. Browser data is unchanged. There is no undo.\n\nContinue?'))return; setBusy(true); try{ const latest=await getRemote(target.id); if(!latest||Number(latest.revision)!==target.revision||JSON.stringify(latest.data)!==target.snapshot){ message.textContent='Deletion stopped: MySQL record changed or disappeared. Check again.'; return; } const response=await fetch('/bowls_staging/api/admin_delete.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'competition',record_id:target.id,expected_revision:target.revision,confirm_delete:'DELETE TEST COMPETITION'}) }); const result=await response.json(); if(response.ok&&result.status==='ok'){ message.textContent='MySQL test competition deleted successfully. Browser data unchanged. Check MySQL records to verify.'; }else if(response.status===409){ message.textContent='Deletion blocked: MySQL revision conflict. Check again.'; }else{ message.textContent='Deletion failed (HTTP '+response.status+'): '+String(result.message||'Unknown error'); } }catch(e){message.textContent='Deletion request failed: '+e.message;} finally{invalidate();setBusy(false);} }); })(); /* V31 Administrator logout (separate from V30 functionality). */ document.getElementById('adminLogoutV31').addEventListener('click', async function () { if (!window.confirm('Log out of the Administrator dashboard?')) return; const button = this; button.disabled = true; button.textContent = 'Logging Out...'; try { const response = await fetch('/bowls_staging/api/logout.php', { method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json'}, body: '{}' }); const result = await response.json(); if (!response.ok || result.status !== 'ok') { throw new Error(result.message || 'Logout failed'); } window.location.replace('login.html'); } catch (error) { alert('Unable to log out: ' + error.message + '. Please try again.'); button.disabled = false; button.textContent = 'Log Out'; } }); /* V38: controlled create-only upload of browser players; no browser mutation. */ (function setupV38PlayerUpload(){ const check=document.getElementById('v38PlayerCheck'); const upload=document.getElementById('v38PlayerUpload'); const message=document.getElementById('v38PlayerMessage'); let busy=false; function setBusy(v){busy=v;check.disabled=v;upload.disabled=v;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function pendingPlayers(records){ const ids=new Set(records.filter(r=>r.record_type==='player').map(r=>String(r.record_id))); return db.players.filter(p=>p&&typeof p.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(p.id)&&!ids.has(p.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='player'); const pending=pendingPlayers(records); const invalid=db.players.filter(p=>!p||typeof p.id!=='string'||!/^[a-zA-Z0-9_-]+$/.test(p.id)).length; message.textContent='Browser players: '+db.players.length+'; MySQL players: '+remote.length+'; new players available to upload: '+pending.length+(invalid?'; invalid player IDs skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingPlayers(records); if(!pending.length){message.textContent='No new players to upload. Existing MySQL players were left unchanged.';return;} const remoteClubIds=new Set(records.filter(r=>r.record_type==='club').map(r=>String(r.record_id))); const missingClub=pending.filter(p=>p.clubId&&!remoteClubIds.has(String(p.clubId))); if(missingClub.length){message.textContent='Upload stopped: '+missingClub.length+' new player(s) reference a club not yet saved in MySQL. Upload those clubs first.';return;} if(!window.confirm('Upload '+pending.length+' NEW player(s) to MySQL?\n\nExisting MySQL records will not be overwritten. Player photos and club affiliations, if present, are included. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const player of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'player',record_id:player.id,expected_revision:0,data:player}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else{failed++;console.warn('V38 player upload rejected',player.id,response.status,result.message);} }catch(e){failed++;console.warn('V38 player upload failed',player.id,e);} } message.textContent='Player upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V39: explicit revision-protected update of one existing player; no browser mutation. */ (function setupV39PlayerUpdates(){ const select=document.getElementById('v39PlayerSelect'); const compare=document.getElementById('v39PlayerCompare'); const update=document.getElementById('v39PlayerUpdate'); const message=document.getElementById('v39PlayerMessage'); let checked=null,busy=false; const snapshot=x=>JSON.stringify(x); function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const previous=select.value; select.replaceChildren(); for(const p of db.players){ if(!p||typeof p.id!=='string')continue; const option=document.createElement('option');option.value=p.id; option.textContent=String(p.name||p.id);select.appendChild(option); } if([...select.options].some(o=>o.value===previous))select.value=previous; if(!select.options.length)message.textContent='No browser players available.'; } async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records; } function findRemote(records,id){return records.find(r=>r.record_type==='player'&&String(r.record_id)===id)||null;} function setBusy(v){busy=v;select.disabled=v;compare.disabled=v;update.disabled=v||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return; invalidate(); const id=select.value,local=db.players.find(p=>String(p.id)===id); if(!local){message.textContent='Choose a player first.';return;} setBusy(true); try{ const records=await readRecords(); const remote=findRemote(records,id); if(!remote){message.textContent='This player is not in MySQL yet. Use the new player upload feature.';return;} if(snapshot(local)===snapshot(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.';return; } const differences=[]; if(local.name!==remote.data?.name)differences.push('name: browser "'+String(local.name||'(empty)')+'"; MySQL "'+String(remote.data?.name||'(empty)')+'"'); if((local.clubId||'')!==(remote.data?.clubId||''))differences.push('club affiliation differs'); if((local.image||null)!==(remote.data?.image||null)||(local.imageOriginal||null)!==(remote.data?.imageOriginal||null))differences.push('photograph differs'); if(!differences.length)differences.push('other player fields differ'); checked={id,revision:Number(remote.revision),localSnapshot:snapshot(local),remoteSnapshot:snapshot(remote.data)}; message.textContent='Differences found for "'+String(local.name||id)+'". '+differences.join('; ')+'. MySQL revision '+remote.revision+'. Review before confirming.'; }catch(e){message.textContent='Comparison failed: '+e.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const local=db.players.find(p=>String(p.id)===checked.id); if(!local||snapshot(local)!==checked.localSnapshot){ invalidate();message.textContent='Browser player changed since comparison. Compare again.';return; } const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL record for "'+local.name+'"?\n\nOnly this player will be updated. Browser data stays unchanged. The database revision must still match '+revision+'.'))return; setBusy(true); try{ const records=await readRecords(); const latest=findRemote(records,id); if(!latest||Number(latest.revision)!==revision||snapshot(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(snapshot(db.players.find(p=>String(p.id)===id))!==localSnapshot){ message.textContent='Update stopped: browser player changed. Compare again.';return; } const clubId=local.clubId; if(clubId&&!records.some(r=>r.record_type==='club'&&String(r.record_id)===String(clubId))){ message.textContent='Update stopped: player club does not exist in MySQL. Upload the club first.';return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'player',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok')message.textContent='MySQL player updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(e){message.textContent='Update failed: '+e.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V40: explicit create-only team upload. Team data is transmitted without modification. */ (function setupV40TeamUpload(){ const check=document.getElementById('v40TeamCheck'); const upload=document.getElementById('v40TeamUpload'); const message=document.getElementById('v40TeamMessage'); let busy=false; function setBusy(value){busy=value;check.disabled=value;upload.disabled=value;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function pendingTeams(records){ const ids=new Set(records.filter(r=>r.record_type==='team').map(r=>String(r.record_id))); return db.teams.filter(t=>t&&typeof t.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(t.id)&&!ids.has(t.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='team'); const pending=pendingTeams(records); const invalid=db.teams.filter(t=>!t||typeof t.id!=='string'||!/^[a-zA-Z0-9_-]+$/.test(t.id)).length; message.textContent='Browser teams: '+db.teams.length+'; MySQL teams: '+remote.length+'; new teams available to upload: '+pending.length+(invalid?'; invalid team IDs skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingTeams(records); if(!pending.length){message.textContent='No new teams to upload. Existing MySQL teams were left unchanged.';return;} const remotePlayers=new Set(records.filter(r=>r.record_type==='player').map(r=>String(r.record_id))); const missing=[]; for(const team of pending){ for(const entry of Object.values(team.lineup||{})){ if(entry&&entry.playerId&&!remotePlayers.has(String(entry.playerId)))missing.push(team.name||team.id); } } if(missing.length){message.textContent='Upload stopped: '+new Set(missing).size+' new team(s) reference registered players not yet in MySQL. Upload those players first.';return;} if(!window.confirm('Upload '+pending.length+' NEW team(s) to MySQL?\n\nExisting MySQL teams will not be overwritten. Team format and lineups are included. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const team of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'team',record_id:team.id,expected_revision:0,data:team}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else{failed++;console.warn('V40 team upload rejected',team.id,response.status,result.message);} }catch(e){failed++;console.warn('V40 team upload failed',team.id,e);} } message.textContent='Team upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V41: explicit revision-checked team updates; never modifies browser data. */ (function setupV41TeamUpdates(){ const select=document.getElementById('v41TeamSelect'); const compare=document.getElementById('v41TeamCompare'); const update=document.getElementById('v41TeamUpdate'); const message=document.getElementById('v41TeamMessage'); let checked=null,busy=false; const snapshot=x=>JSON.stringify(x); function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const previous=select.value;select.replaceChildren(); for(const t of db.teams){if(!t||typeof t.id!=='string')continue; const o=document.createElement('option');o.value=t.id;o.textContent=String(t.name||t.id);select.appendChild(o); } if([...select.options].some(o=>o.value===previous))select.value=previous; if(!select.options.length)message.textContent='No browser teams available.'; } async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records; } const findRemote=(records,id)=>records.find(r=>r.record_type==='team'&&String(r.record_id)===id)||null; function setBusy(v){busy=v;select.disabled=v;compare.disabled=v;update.disabled=v||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return;invalidate(); const id=select.value,local=db.teams.find(t=>String(t.id)===id); if(!local){message.textContent='Choose a team first.';return;} setBusy(true); try{ const records=await readRecords(),remote=findRemote(records,id); if(!remote){message.textContent='This team is not in MySQL yet. Use the new team upload feature.';return;} if(snapshot(local)===snapshot(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.';return; } const differences=[]; if(local.name!==remote.data?.name)differences.push('name: browser "'+String(local.name||'(empty)')+'"; MySQL "'+String(remote.data?.name||'(empty)')+'"'); if(local.format!==remote.data?.format)differences.push('team format differs'); if(snapshot(local.lineup||{})!==snapshot(remote.data?.lineup||{}))differences.push('player lineup differs'); if(!differences.length)differences.push('other team fields differ'); checked={id,revision:Number(remote.revision),localSnapshot:snapshot(local),remoteSnapshot:snapshot(remote.data)}; message.textContent='Differences found for "'+String(local.name||id)+'". '+differences.join('; ')+'. MySQL revision '+remote.revision+'. Review before confirming.'; }catch(e){message.textContent='Comparison failed: '+e.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const local=db.teams.find(t=>String(t.id)===checked.id); if(!local||snapshot(local)!==checked.localSnapshot){invalidate();message.textContent='Browser team changed since comparison. Compare again.';return;} const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL record for "'+local.name+'"?\n\nOnly this team will be updated. Browser data stays unchanged. The database revision must still match '+revision+'.'))return; setBusy(true); try{ const records=await readRecords(),latest=findRemote(records,id); if(!latest||Number(latest.revision)!==revision||snapshot(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(snapshot(db.teams.find(t=>String(t.id)===id))!==localSnapshot){message.textContent='Update stopped: browser team changed. Compare again.';return;} const playerIds=new Set(records.filter(r=>r.record_type==='player').map(r=>String(r.record_id))); for(const entry of Object.values(local.lineup||{})){ if(entry&&entry.playerId&&!playerIds.has(String(entry.playerId))){ message.textContent='Update stopped: a registered lineup player is not in MySQL. Upload the player first.';return; } } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'team',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok')message.textContent='MySQL team updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(e){message.textContent='Update failed: '+e.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V42: explicit create-only time slot upload. Browser records remain unchanged. */ (function setupV42SlotUpload(){ const check=document.getElementById('v42SlotCheck'); const upload=document.getElementById('v42SlotUpload'); const message=document.getElementById('v42SlotMessage'); let busy=false; function setBusy(value){busy=value;check.disabled=value;upload.disabled=value;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function pendingSlots(records){ const ids=new Set(records.filter(r=>r.record_type==='slot').map(r=>String(r.record_id))); return db.slots.filter(t=>t&&typeof t.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(t.id)&&!ids.has(t.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='slot'); const pending=pendingSlots(records); const invalid=db.slots.filter(t=>!t||typeof t.id!=='string'||!/^[a-zA-Z0-9_-]+$/.test(t.id)).length; message.textContent='Browser time slots: '+db.slots.length+'; MySQL time slots: '+remote.length+'; new time slots available to upload: '+pending.length+(invalid?'; invalid time slot IDs skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingSlots(records); if(!pending.length){message.textContent='No new time slots to upload. Existing MySQL time slots were left unchanged.';return;} if(!window.confirm('Upload '+pending.length+' NEW time slot(s) to MySQL?\n\nExisting MySQL time slots will not be overwritten. Dates and times are included. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const slot of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'slot',record_id:slot.id,expected_revision:0,data:slot}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else{failed++;console.warn('V42 time slot upload rejected',slot.id,response.status,result.message);} }catch(e){failed++;console.warn('V42 time slot upload failed',slot.id,e);} } message.textContent='Time slot upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V43: explicit revision-checked time slot updates; browser data is never changed. */ (function setupV43SlotUpdates(){ const select=document.getElementById('v43SlotSelect'); const compare=document.getElementById('v43SlotCompare'); const update=document.getElementById('v43SlotUpdate'); const message=document.getElementById('v43SlotMessage'); let checked=null,busy=false; const snapshot=x=>JSON.stringify(x); function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const previous=select.value;select.replaceChildren(); for(const slot of db.slots){ if(!slot||typeof slot.id!=='string')continue; const option=document.createElement('option');option.value=slot.id; option.textContent=String(slot.name||slot.id)+' · '+String(slot.date||'');select.appendChild(option); } if([...select.options].some(option=>option.value===previous))select.value=previous; if(!select.options.length)message.textContent='No browser time slots available.'; } async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records; } const findRemote=(records,id)=>records.find(record=>record.record_type==='slot'&&String(record.record_id)===id)||null; function setBusy(value){busy=value;select.disabled=value;compare.disabled=value;update.disabled=value||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return;invalidate(); const id=select.value,local=db.slots.find(slot=>String(slot.id)===id); if(!local){message.textContent='Choose a time slot first.';return;} setBusy(true); try{ const records=await readRecords(),remote=findRemote(records,id); if(!remote){message.textContent='This time slot is not in MySQL yet. Use the new time slot upload feature.';return;} if(snapshot(local)===snapshot(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.';return; } const differences=[]; if(local.name!==remote.data?.name)differences.push('name: browser "'+String(local.name||'(empty)')+'"; MySQL "'+String(remote.data?.name||'(empty)')+'"'); if(local.date!==remote.data?.date)differences.push('date/time: browser "'+String(local.date||'(empty)')+'"; MySQL "'+String(remote.data?.date||'(empty)')+'"'); if(!differences.length)differences.push('other time slot fields differ'); checked={id,revision:Number(remote.revision),localSnapshot:snapshot(local),remoteSnapshot:snapshot(remote.data)}; message.textContent='Differences found for "'+String(local.name||id)+'". '+differences.join('; ')+'. MySQL revision '+remote.revision+'. Review before confirming.'; }catch(error){message.textContent='Comparison failed: '+error.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const local=db.slots.find(slot=>String(slot.id)===checked.id); if(!local||snapshot(local)!==checked.localSnapshot){invalidate();message.textContent='Browser time slot changed since comparison. Compare again.';return;} const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL record for "'+local.name+'"?\n\nOnly this time slot will be updated. Browser data stays unchanged. The database revision must still match '+revision+'.'))return; setBusy(true); try{ const records=await readRecords(),latest=findRemote(records,id); if(!latest||Number(latest.revision)!==revision||snapshot(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(snapshot(db.slots.find(slot=>String(slot.id)===id))!==localSnapshot){ message.textContent='Update stopped: browser time slot changed. Compare again.';return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'slot',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok')message.textContent='MySQL time slot updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(error){message.textContent='Update failed: '+error.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V44: explicit create-only green upload. Existing MySQL greens are never overwritten. */ (function setupV44GreenUpload(){ const check=document.getElementById('v44GreenCheck'); const upload=document.getElementById('v44GreenUpload'); const message=document.getElementById('v44GreenMessage'); let busy=false; function setBusy(value){busy=value;check.disabled=value;upload.disabled=value;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function validGreen(g){return g&&typeof g.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(g.id)&&typeof g.name==='string'&&g.name.trim().length>0&&Number.isInteger(Number(g.rinks))&&Number(g.rinks)>=1&&Number(g.rinks)<=40;} function pendingGreens(records){ const ids=new Set(records.filter(r=>r.record_type==='green').map(r=>String(r.record_id))); return db.greens.filter(g=>validGreen(g)&&!ids.has(g.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='green'); const pending=pendingGreens(records); const invalid=db.greens.filter(g=>!validGreen(g)).length; message.textContent='Browser greens: '+db.greens.length+'; MySQL greens: '+remote.length+'; new greens available to upload: '+pending.length+(invalid?'; invalid greens skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingGreens(records); if(!pending.length){message.textContent='No new greens to upload. Existing MySQL greens were left unchanged.';return;} if(!window.confirm('Upload '+pending.length+' NEW green(s) to MySQL?\n\nEach green name and rink count will be included. Existing MySQL greens will not be overwritten. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const green of pending){ try{ const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'green',record_id:green.id,expected_revision:0,data:green}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else{failed++;console.warn('V44 green upload rejected',green.id,response.status,result.message);} }catch(e){failed++;console.warn('V44 green upload failed',green.id,e);} } message.textContent='Green upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V45: explicit revision-checked green updates. Browser data remains the working copy. */ (function setupV45GreenUpdates(){ const select=document.getElementById('v45GreenSelect'); const compare=document.getElementById('v45GreenCompare'); const update=document.getElementById('v45GreenUpdate'); const message=document.getElementById('v45GreenMessage'); let checked=null,busy=false; const snapshot=x=>JSON.stringify(x); function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const previous=select.value;select.replaceChildren(); for(const green of db.greens){ if(!green||typeof green.id!=='string')continue; const option=document.createElement('option');option.value=green.id; option.textContent=String(green.name||green.id)+' · '+String(green.rinks||0)+' rinks';select.appendChild(option); } if([...select.options].some(option=>option.value===previous))select.value=previous; if(!select.options.length)message.textContent='No browser greens available.'; } async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records; } const findRemote=(records,id)=>records.find(record=>record.record_type==='green'&&String(record.record_id)===id)||null; function setBusy(value){busy=value;select.disabled=value;compare.disabled=value;update.disabled=value||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return;invalidate(); const id=select.value,local=db.greens.find(green=>String(green.id)===id); if(!local){message.textContent='Choose a green first.';return;} setBusy(true); try{ const records=await readRecords(),remote=findRemote(records,id); if(!remote){message.textContent='This green is not in MySQL yet. Use the new green upload feature.';return;} if(snapshot(local)===snapshot(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.';return; } const differences=[]; if(local.name!==remote.data?.name)differences.push('name: browser "'+String(local.name||'(empty)')+'"; MySQL "'+String(remote.data?.name||'(empty)')+'"'); if(Number(local.rinks)!==Number(remote.data?.rinks))differences.push('rinks: browser '+String(local.rinks)+'; MySQL '+String(remote.data?.rinks)); if(!differences.length)differences.push('other green fields differ'); checked={id,revision:Number(remote.revision),localSnapshot:snapshot(local),remoteSnapshot:snapshot(remote.data)}; message.textContent='Differences found for "'+String(local.name||id)+'". '+differences.join('; ')+'. MySQL revision '+remote.revision+'. Review before confirming.'; }catch(error){message.textContent='Comparison failed: '+error.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const local=db.greens.find(green=>String(green.id)===checked.id); if(!local||snapshot(local)!==checked.localSnapshot){invalidate();message.textContent='Browser green changed since comparison. Compare again.';return;} if(typeof local.name!=='string'||!local.name.trim()||!Number.isInteger(Number(local.rinks))||Number(local.rinks)<1||Number(local.rinks)>40){ invalidate();message.textContent='Invalid green name or rink count (must be 1–40).';return; } const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL record for "'+local.name+'"?\n\nOnly this green will be updated. Browser data stays unchanged. The database revision must still match '+revision+'.'))return; setBusy(true); try{ const records=await readRecords(),latest=findRemote(records,id); if(!latest||Number(latest.revision)!==revision||snapshot(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(snapshot(db.greens.find(green=>String(green.id)===id))!==localSnapshot){ message.textContent='Update stopped: browser green changed. Compare again.';return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'green',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); const result=await response.json(); if(response.ok&&result.status==='ok')message.textContent='MySQL green updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(error){message.textContent='Update failed: '+error.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })(); /* V46: explicit create-only match upload. No automatic synchronisation. */ (function setupV46MatchUpload(){ const check=document.getElementById('v46MatchCheck'); const upload=document.getElementById('v46MatchUpload'); const message=document.getElementById('v46MatchMessage'); let busy=false; function setBusy(value){busy=value;check.disabled=value;upload.disabled=value;} async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const data=await response.json(); if(data.status!=='ok'||!Array.isArray(data.records))throw Error('Unexpected MySQL response'); return data.records; } function validMatch(m){return m&&typeof m.id==='string'&&/^[a-zA-Z0-9_-]+$/.test(m.id)&& typeof m==='object'&&!Array.isArray(m)&&typeof m.nameA==='string'&&typeof m.nameB==='string'&& m.nameA.trim().length>0&&m.nameB.trim().length>0;} function pendingMatches(records){ const ids=new Set(records.filter(r=>r.record_type==='match').map(r=>String(r.record_id))); return db.matches.filter(m=>validMatch(m)&&!ids.has(m.id)); } check.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const remote=records.filter(r=>r.record_type==='match'); const pending=pendingMatches(records); const invalid=db.matches.filter(m=>!validMatch(m)).length; message.textContent='Browser matches: '+db.matches.length+'; MySQL matches: '+remote.length+'; new matches available to upload: '+pending.length+(invalid?'; invalid matches skipped: '+invalid:'')+'.'; }catch(e){message.textContent='Check failed: '+e.message;} finally{setBusy(false);} }); upload.addEventListener('click',async()=>{ if(busy)return;setBusy(true); try{ const records=await readRecords(); const pending=pendingMatches(records); if(!pending.length){message.textContent='No new matches to upload. Existing MySQL matches were left unchanged.';return;} if(!window.confirm('Create '+pending.length+' NEW scheduled match(es) in MySQL?\n\nOnly clean scheduled matches without scoring history are accepted. Existing MySQL matches will not be overwritten. Browser data remains unchanged. Browser data remains unchanged.'))return; let created=0,conflicts=0,failed=0; for(const match of pending){ try{ const response=await fetch('/bowls_staging/api/admin_match_create.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({match_id:match.id,data:match}) }); const result=await response.json(); if(response.ok&&result.status==='ok')created++; else if(response.status===409)conflicts++; else{failed++;console.warn('V46 match upload rejected',match.id,response.status,result.message);} }catch(e){failed++;console.warn('V46 match upload failed',match.id,e);} } message.textContent='Match upload finished: '+created+' created, '+conflicts+' already existed/conflicted, '+failed+' failed. Browser data unchanged.'; }catch(e){message.textContent='Upload stopped: '+e.message;} finally{setBusy(false);} }); })(); /* V47: explicit revision-checked full match update; no automatic sync. */ (function setupV47MatchUpdates(){ const select=document.getElementById('v47MatchSelect'); const compare=document.getElementById('v47MatchCompare'); const update=document.getElementById('v47MatchUpdate'); const message=document.getElementById('v47MatchMessage'); let checked=null,busy=false; const snapshot=value=>JSON.stringify(value); function invalidate(){checked=null;update.disabled=true;} function refreshOptions(){ const previous=select.value; select.replaceChildren(); for(const match of db.matches){ if(!match||typeof match.id!=='string')continue; const option=document.createElement('option'); option.value=match.id; option.textContent=String(match.nameA||'Team A')+' vs '+String(match.nameB||'Team B')+' · '+String(match.status||'scheduled')+' · '+String(match.id).slice(0,8); select.appendChild(option); } if([...select.options].some(o=>o.value===previous))select.value=previous; if(!select.options.length)message.textContent='No browser matches available.'; } async function readRecords(){ const response=await fetch('/bowls_staging/api/admin_records.php',{method:'GET',credentials:'same-origin',cache:'no-store'}); if(!response.ok)throw Error('MySQL read failed (HTTP '+response.status+')'); const payload=await response.json(); if(payload.status!=='ok'||!Array.isArray(payload.records))throw Error('Invalid database response'); return payload.records; } const findRemote=(records,id)=>records.find(r=>r.record_type==='match'&&String(r.record_id)===id)||null; function setBusy(value){busy=value;select.disabled=value;compare.disabled=value;update.disabled=value||!checked;} select.addEventListener('change',()=>{invalidate();message.textContent='Selection changed. Compare again before updating.';}); compare.addEventListener('click',async()=>{ if(busy)return; invalidate(); const id=select.value,local=db.matches.find(m=>String(m.id)===id); if(!local){message.textContent='Choose a match first.';return;} setBusy(true); try{ const remote=findRemote(await readRecords(),id); if(!remote){message.textContent='This match is not in MySQL yet. Use the new match upload feature.';return;} if(snapshot(local)===snapshot(remote.data)){ message.textContent='Browser and MySQL match. Database revision '+remote.revision+'. No update needed.';return; } const differences=[]; const keys=new Set([...Object.keys(local),...Object.keys(remote.data||{})]); for(const key of keys){ if(snapshot(local[key])!==snapshot(remote.data?.[key]))differences.push(key); } checked={id,revision:Number(remote.revision),localSnapshot:snapshot(local),remoteSnapshot:snapshot(remote.data)}; message.textContent='Differences found for "'+String(local.nameA||'Team A')+' vs '+String(local.nameB||'Team B')+'". Changed fields: '+differences.join(', ')+'. MySQL revision '+remote.revision+'. Review before confirming.'; }catch(error){message.textContent='Comparison failed: '+error.message;} finally{setBusy(false);} }); update.addEventListener('click',async()=>{ if(busy||!checked)return; const local=db.matches.find(m=>String(m.id)===checked.id); if(!local||snapshot(local)!==checked.localSnapshot){invalidate();message.textContent='Browser match changed since comparison. Compare again.';return;} if(typeof local.nameA!=='string'||!local.nameA.trim()||typeof local.nameB!=='string'||!local.nameB.trim()){ invalidate();message.textContent='Invalid match: both team names are required.';return; } const {id,revision,localSnapshot,remoteSnapshot}=checked; if(!window.confirm('Update the existing MySQL match "'+local.nameA+' vs '+local.nameB+'"?\n\nAll match fields, including scoring and history, will be saved. Browser data stays unchanged. MySQL revision must still match '+revision+'.'))return; setBusy(true); try{ const latest=findRemote(await readRecords(),id); if(!latest||Number(latest.revision)!==revision||snapshot(latest.data)!==remoteSnapshot){ message.textContent='Update stopped: MySQL changed since comparison. Compare again.';return; } if(snapshot(db.matches.find(m=>String(m.id)===id))!==localSnapshot){ message.textContent='Update stopped: browser match changed. Compare again.';return; } const response=await fetch('/bowls_staging/api/admin_save.php',{ method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'}, body:JSON.stringify({record_type:'match',record_id:id,expected_revision:revision,data:JSON.parse(localSnapshot)}) }); let result; try{result=await response.json();}catch{throw Error('Unexpected response from MySQL save endpoint (HTTP '+response.status+')');} if(response.ok&&result.status==='ok')message.textContent='MySQL match updated successfully to revision '+result.revision+'. Browser data unchanged.'; else if(response.status===409)message.textContent='Revision conflict: MySQL was updated elsewhere. No overwrite occurred. Compare again.'; else message.textContent='Update failed (HTTP '+response.status+'): '+(result.message||'Unknown error'); }catch(error){message.textContent='Update failed: '+error.message;} finally{invalidate();setBusy(false);} }); refreshOptions(); const originalRender=window.render; if(typeof originalRender==='function'){ window.render=function(...args){const result=originalRender.apply(this,args);refreshOptions();invalidate();return result;}; } })();

Adjust image

Drag to reposition and use the slider to zoom.

Crop preview