
from flask import Blueprint, render_template, request, jsonify
slots_bp = Blueprint('slots', __name__)

@slots_bp.route('/slots')
def slots_page():
    # اگر ثبت نشده بود باید به صفحه رجیستر ریدایرکت شود!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    return render_template("slots.html")



@slots_bp.route('/api/available_time_slots', methods=['GET'])
def available_time_slots():
    phone = request.args.get('phone_number')
    if not phone:
        return jsonify({'error': _('وارد کردن شماره موبایل اجباری است')}), 400

    #EXAMPLE
    existing_booking = [{"day": 21, "time": "10:30"}]
    return jsonify({'available_slots': existing_booking}), 200


@slots_bp.route('/api/book_time_slot', methods=['POST'])
def book_time_slot():
    phone = request.json.get('phone_number')
    day = request.json.get('day')
    time_slot = request.json.get('time')

    if not phone or not day or not time_slot:
        return jsonify({'error': 'phone_number, day, and time are required'}), 400

    success, message = db.book_time_slot(phone, day, time_slot)

    # Send notification SMS
    if success:
        sms_data = {
            "op": "pattern",
            "user": IPPANEL_USER,
            "pass": IPPANEL_PASS,
            "fromNum": FROM_NUMBER,
            "toNum": NOTIFY_NUMBER,
            "patternCode": PATTERN_CODE_BOOKING,
            "inputData": [{"number": phone, "date": f"{day} ساعت {time_slot}"}]
        }
        try:
            sms_response = requests.post(IPPANEL_URL, json=sms_data, timeout=5).json()
        except Exception as e:
            sms_response = {"error": str(e)}
        print(f"Time slot booked by {phone}: {day} {time_slot}. SMS: {sms_response}")
        return jsonify({'message': message, 'sms_response': sms_response}), 200
    else:
        return jsonify({'error': message}), 400