from pathlib import Path
import re
r=Path(__file__).resolve().parents[1]
p=r/'resources/views/hotel_workspace/layout.blade.php'
s=p.read_text(encoding='utf-8-sig')
if s.startswith('<!doctype'):
    css=s.split('<style>',1)[1].split('</style>',1)[0]
    def scoped(css):
        out='';i=0
        while i<len(css):
            j=css.find('{',i)
            if j<0:break
            selector=css[i:j].strip();depth=1;k=j+1
            while k<len(css) and depth:
                if css[k]=='{':depth+=1
                if css[k]=='}':depth-=1
                k+=1
            body=css[j+1:k-1]
            if selector.startswith('@'):
                out+=selector+'{'+scoped(body)+'}'
            else:
                selectors=[]
                for x in selector.split(','):
                    x=x.strip()
                    if x.startswith(('header','nav','main','body')):continue
                    selectors.append('.hotel-workspace '+x)
                if selectors:out+=','.join(selectors)+'{'+body+'}'
            i=k
        return out
    js=s.split('window.hotelUuid=',1)[1].split('</script>',1)[0]
    p.write_text("@extends('layouts.app')\n@section('content')\n<meta name=\"csrf-token\" content=\"{{ csrf_token() }}\">\n<style>"+scoped(css)+"</style>\n<script src=\"{{ asset('js/document-print.js') }}\"></script>\n<script>window.hotelUuid="+js+"</script>\n<div class=\"hotel-workspace\">@if(session('success'))<div class=\"message\">{{ session('success') }}</div>@endif @if($errors->any())<div class=\"error\">{{ $errors->first() }}</div>@endif @yield('hotel-content')</div>\n@stack('scripts')\n@endsection\n",encoding='utf-8')
for name in ['store','restaurant','room_setup','reports']:
    p=r/f'resources/views/hotel_workspace/{name}.blade.php';s=p.read_text(encoding='utf-8-sig').replace("@section('content')","@section('hotel-content')");p.write_text(s,encoding='utf-8')
p=r/'resources/views/accommodation/index.blade.php';s=p.read_text(encoding='utf-8-sig')
s=s.replace("@section('content')","@section(($simpleHotel ?? false) ? 'hotel-content' : 'content')",1)
s=s.replace('''<a class="btn" href="{{ url('/hotel-rooms/setup') }}">Setup</a>''','')
start=s.index('                <div class="chips">@foreach($activeFloors')
end=s.index('                @else',start)
s=s[:start]+'''                <form class="auto-filter-form" method="get" action="{{ url('/hotel-rooms') }}"><div class="chips"><input type="hidden" name="floor_id" value="{{ $selectedFloor }}">@foreach($activeFloors as $floor)<a class="btn {{ $selectedFloor == $floor->id ? '' : 'btn-light' }}" href="{{ url('/hotel-rooms?floor_id='.$floor->id) }}">{{ $floor->name }}</a>@endforeach<a class="btn {{ $selectedFloor==='all' ? '' : 'btn-light' }}" href="{{ url('/hotel-rooms?floor_id=all') }}">All Floors</a><select class="form-control" name="room_type_id" aria-label="Room Type" style="width:190px"><option value="">All Room Types</option>@foreach($activeRoomTypes as $type)<option value="{{ $type->id }}" @selected(request('room_type_id')==$type->id)>{{ $type->name }}</option>@endforeach</select></div></form>
'''+s[end:]
p.write_text(s,encoding='utf-8')
p=r/'resources/views/hotel_workspace/item_form.blade.php';s=p.read_text(encoding='utf-8-sig').replace('<select name="kind"><option value="consumable">','<select name="kind" required><option value="" selected disabled>Select item type</option><option value="consumable">');p.write_text(s,encoding='utf-8')
p=r/'resources/views/hotel_workspace/store.blade.php';s=p.read_text(encoding='utf-8-sig');s=s.replace('<div class="card table-wrap"><table>', '''<div class="chips"><a class="btn" href="{{ url('/hotel-store?kind=consumable') }}">Consumables</a><a class="btn" href="{{ url('/hotel-store?kind=asset') }}">Fixed Assets</a></div><div class="card table-wrap"><table>''',1);p.write_text(s,encoding='utf-8')
p=r/'resources/views/hotel_workspace/room_setup.blade.php';s=p.read_text(encoding='utf-8-sig').replace('<h1>Room Setup</h1>','<h1>Settings</h1>').replace("url('/hotel-rooms/setup')","url('/hotel-settings/rooms')")
idx=s.index('<div class="card"><h2>Rooms')
s=s[:idx]+'''<div class="card"><h2>Exchange Rate</h2><form method="post" action="{{ url('/hotel-settings/rate') }}" class="fields">@csrf<div><label>SSP for 1 USD</label><input name="ssp_per_usd" type="number" step="0.000001" min="0.000001" value="{{ app(\\App\\Services\\HotelWorkspaceService::class)->rate(auth()->user()->branch_id) }}" required></div><div style="align-self:end"><button class="primary">Save Rate</button></div></form></div>
'''+s[idx:];p.write_text(s,encoding='utf-8')
p=r/'resources/views/hotel_workspace/restaurant.blade.php';s=p.read_text(encoding='utf-8-sig');s=s.replace('<button data-open="rateDialog">Exchange Rate</button>','<button class="primary" data-open="postBillDialog">Post Bill</button>')
start=s.index('<div style="display:grid;grid-template-columns:');end=s.index('<div class="card table-wrap"><h2>Bills',start)
old=s[start:end];cart=old[old.index('<div class="card"><h2>New Bill'):];cart=cart.rsplit('</div></div>',1)[0]+'</div>'
table='''<div class="card table-wrap"><h2>Restaurant Items</h2><input id="menuSearch" placeholder="Search items"><table><thead><tr><th>Item</th><th class="num">Price (SSP)</th><th class="num">Quantity</th><th>Action</th></tr></thead><tbody>@forelse($items as $item)<tr class="menu-item" data-name="{{ strtolower($item->name) }}"><td>{{ $item->name }}</td><td class="num">{{ number_format($item->retail_price,2) }}</td><td class="num">{{ number_format($item->stock_quantity,2) }}</td><td><button onclick="menuStock({{ $item->id }})">Add Stock</button></td></tr>@empty<tr><td colspan="4">Add food and drink items to get started.</td></tr>@endforelse</tbody></table></div>
<dialog id="postBillDialog"><h2>Post Bill</h2><label>Item</label><div class="fields"><select id="postItem"><option value="">Select item</option>@foreach($items as $item)<option value="{{ $item->id }}">{{ $item->name }}</option>@endforeach</select><button type="button" onclick="if(document.getElementById('postItem').value)addMenu(Number(document.getElementById('postItem').value))">Add Item</button></div>'''
s=s[:start]+table+cart+'<div class="buttons"><button type="button" data-close>Close</button></div></dialog>\n'+s[end:]
start=s.index('<dialog id="rateDialog">');end=s.index('<dialog id="menuStockDialog">',start);s=s[:start]+s[end:]
s=s.replace("document.getElementById('rateDialog').showModal()","document.getElementById('saleError').textContent='Set the exchange rate in Settings first.'")
p.write_text(s,encoding='utf-8')
for file in ['app/Http/Middleware/EnsureModuleAccess.php','app/Http/Middleware/EnsurePermissionAccess.php']:
    p=r/file;s=p.read_text(encoding='utf-8-sig').replace("'hotel-store', 'hotel-restaurant', 'hotel-rooms' =>", "'hotel-dashboard', 'hotel-settings', 'hotel-users', 'hotel-store', 'hotel-restaurant', 'hotel-rooms' =>").replace('(hotel-store|hotel-restaurant|hotel-rooms)', '(hotel-dashboard|hotel-settings|hotel-users|hotel-store|hotel-restaurant|hotel-rooms)');p.write_text(s,encoding='utf-8')
print('Hotel workspace now uses the shared JEVAPOS layout.')
