from odoo import http, _
from odoo.http import request
import datetime
import pytz

class TableReservationController(http.Controller):

    @http.route(['/reservation'], type='http', auth="public", website=True)
    def reservation_form(self, **post):
        floors = request.env['restaurant.floor'].sudo().search([])
        tables = request.env['restaurant.table'].sudo().search([])
        return request.render("dine360_reservation.reservation_page_template", {
            'floors': floors,
            'tables': tables,
        })

    @http.route(['/reservation/submit'], type='http', auth="public", website=True, methods=['POST'], csrf=True)
    def reservation_submit(self, **post):
        # Extract data from post
        customer_name = post.get('customer_name')
        phone = post.get('phone')
        email = post.get('email')
        floor_id = int(post.get('floor_id'))
        table_id = int(post.get('table_id'))
        start_time_str = post.get('start_time') # Format: 2024-05-20T18:00
        num_people = int(post.get('num_people', 1))

        # Convert start_time to datetime object and localize to restaurant timezone (Brampton)
        restaurant_tz = pytz.timezone('America/Toronto')
        local_start = datetime.datetime.strptime(start_time_str, '%Y-%m-%dT%H:%M')
        local_start = restaurant_tz.localize(local_start)
        
        # Convert to UTC for Odoo
        start_time = local_start.astimezone(pytz.utc).replace(tzinfo=None)
        
        # Standard duration of 1 hour for now
        end_time = start_time + datetime.timedelta(hours=1)

        # Create reservation
        try:
            reservation = request.env['restaurant.reservation'].sudo().create({
                'customer_name': customer_name,
                'phone': phone,
                'email': email,
                'floor_id': floor_id,
                'table_id': table_id,
                'start_time': start_time,
                'end_time': end_time,
                'num_people': num_people,
                'state': 'draft'
            })
            return request.render("dine360_reservation.reservation_success_template", {
                'reservation': reservation,
            })
        except Exception as e:
            return request.render("dine360_reservation.reservation_page_template", {
                'error': str(e),
                'floors': request.env['restaurant.floor'].sudo().search([]),
                'tables': request.env['restaurant.table'].sudo().search([]),
                'post': post,
            })
