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
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# your_app/api.py

from flask import Blueprint, request, jsonify, current_app, redirect
from bson.objectid import ObjectId
from datetime import datetime
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from .extensions import bcrypt, mongo
from .xero_utils import trigger_po_creation, trigger_contact_creation
from .email_utils import send_order_confirmation_email, send_registration_email, send_login_notification_email, send_cart_reminder_email



api_bp = Blueprint('api', __name__)

@api_bp.route('/clear')
def clear_all():
    mongo.db.orders.delete_many({})
    return "✅"

@api_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')
    company_name = data.get('businessName') 
    
    if not all([email, password, company_name]): 
        return jsonify({"msg": "Missing required fields: Email, Password, and Business Name"}), 400
    if mongo.db.users.find_one({'email': email}): 
        return jsonify({"msg": "A user with this email already exists"}), 409
    
    hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
    
    user_document = data.copy()
    user_document['password'] = hashed_password
    user_document['company_name'] = company_name
    user_document['is_approved'] = True
    user_document['is_admin'] = False
    
    mongo.db.users.insert_one(user_document)
    trigger_contact_creation(data)

    try:
        send_registration_email(data)
    except Exception as e:
        current_app.logger.error(f"Failed to send registration email to {email}: {e}")

    return jsonify({"msg": "Registration successful! Your application is being processed."}), 201

# ... (the rest of your api.py file remains unchanged)
@api_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    email, password = data.get('email'), data.get('password')
    user = mongo.db.users.find_one({'email': email})

    if user and user.get('password') and bcrypt.check_password_hash(user['password'], password):
        if not user.get('is_approved', False): return jsonify({"msg": "Account pending approval"}), 403
        
        try:
            send_login_notification_email(user)
        except Exception as e:
            current_app.logger.error(f"Failed to send login notification email to {email}: {e}")

        access_token = create_access_token(identity=email)
        return jsonify(access_token=access_token, email=user['email'], companyName=user['businessName'],contactPerson=user.get('contactPerson', '')) , 200
    
    return jsonify({"msg": "Bad email or password"}), 401

@api_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_user_profile():
    user_email = get_jwt_identity()
    user = mongo.db.users.find_one({'email': user_email})

    if not user:
        return jsonify({"msg": "User not found"}), 404

    profile_data = {
        'deliveryAddress': user.get('businessAddress', ''),
        'mobileNumber': user.get('phoneNumber', '')
    }
    
    return jsonify(profile_data), 200

@api_bp.route('/products', methods=['GET'])
def get_products():
    products = [{
        'id': str(p['_id']), 'name': p.get('name'), 'category': p.get('category'),
        'unit': p.get('unit'), 'image_url': p.get('image_url', ''), 'price': p.get('price', '')
    } for p in mongo.db.products.find()]
    return jsonify(products)


@api_bp.route('/cart', methods=['GET', 'POST'])
@jwt_required()
def handle_cart():
    user_email = get_jwt_identity()

    if request.method == 'GET':
        cart = mongo.db.carts.find_one({'user_email': user_email})
        if not cart:
            return jsonify({'items': [], 'deliveryDate': None})

        populated_items = []
        if cart.get('items'):
            product_ids = [ObjectId(item['productId']) for item in cart['items']]
            if product_ids:
                products = {str(p['_id']): p for p in mongo.db.products.find({'_id': {'$in': product_ids}})}
                for item in cart['items']:
                    details = products.get(item['productId'])
                    if details:
                        populated_items.append({
                            'product': {'id': str(details['_id']), 'name': details.get('name'), 'unit': details.get('unit'), 'image_url': details.get('image_url'), 'price': details.get('price')},
                            'quantity': item['quantity'],
                            'mode': item.get('mode', 'pieces')
                        })
        
        return jsonify({
            'items': populated_items,
            'deliveryDate': cart.get('deliveryDate')
        })

    if request.method == 'POST':
        data = request.get_json()
        
        update_doc = {
            'user_email': user_email,
            'updated_at': datetime.utcnow()
        }
        
        if 'items' in data:
            update_doc['items'] = data['items']

        if 'deliveryDate' in data:
            update_doc['deliveryDate'] = data['deliveryDate']

        mongo.db.carts.update_one(
            {'user_email': user_email},
            {'$set': update_doc},
            upsert=True
        )
        return jsonify({"msg": "Cart updated successfully"})

@api_bp.route('/orders', methods=['GET', 'POST'])
@jwt_required()
def handle_orders():
    user_email = get_jwt_identity()

    if request.method == 'POST':
        cart = mongo.db.carts.find_one({'user_email': user_email})
        if not cart or not cart.get('items'): return jsonify({"msg": "Your cart is empty"}), 400
        
        data = request.get_json()
        if not all([data.get('deliveryDate'), data.get('deliveryAddress'), data.get('mobileNumber')]): return jsonify({"msg": "Missing delivery information"}), 400

        user = mongo.db.users.find_one({'email': user_email})
        if not user:
            return jsonify({"msg": "User not found"}), 404

        order_doc = {
            'user_email': user_email, 'items': cart['items'], 'delivery_date': data['deliveryDate'],
            'delivery_address': data['deliveryAddress'], 'mobile_number': data['mobileNumber'],
            'additional_info': data.get('additionalInfo'), 'total_amount': data.get('totalAmount'),
            'status': 'pending', 'created_at': datetime.utcnow()
        }
        order_id = mongo.db.orders.insert_one(order_doc).inserted_id
        order_doc['_id'] = order_id

        order_details_for_xero = {
            "order_id": str(order_id), "user_email": user_email, "items": cart['items'],
            "delivery_address": data['deliveryAddress'], "mobile_number": data['mobileNumber'],"deliverydate":data["deliveryDate"]
        }
        trigger_po_creation(order_details_for_xero)
        
        try:
            product_ids = [ObjectId(item['productId']) for item in cart['items']]
            products_map = {str(p['_id']): p for p in mongo.db.products.find({'_id': {'$in': product_ids}})}
            
            order_doc['populated_items'] = [{
                "name": products_map.get(item['productId'], {}).get('name', 'N/A'),
                "quantity": item['quantity'],
                "mode": item.get('mode', 'pieces')
            } for item in cart['items']]
            
            send_order_confirmation_email(order_doc, user)

        except Exception as e:
            current_app.logger.error(f"Failed to send confirmation email for order {order_id}: {e}")
        
        mongo.db.carts.delete_one({'user_email': user_email})
        return jsonify({"msg": "Order placed successfully! You will be redirected shortly to the Orders Page!", "orderId": str(order_id)}), 201

    if request.method == 'GET':
        user_orders = list(mongo.db.orders.find({'user_email': user_email}).sort('created_at', -1))
        if not user_orders: return jsonify([])
        
        all_product_ids = {ObjectId(item['productId']) for order in user_orders for item in order.get('items', [])}
        products = {str(p['_id']): p for p in mongo.db.products.find({'_id': {'$in': list(all_product_ids)}})}
        
        for order in user_orders:
            order['items'] = [
                {
                    'quantity': item['quantity'], 
                    'mode': item.get('mode', 'pieces'),
                    'product': {
                        'id': str(p['_id']), 
                        'name': p.get('name'), 
                        'unit': p.get('unit'), 
                        'image_url': p.get('image_url')
                    }
                } 
                for item in order.get('items', []) if (p := products.get(item['productId']))
            ]
            order['_id'] = str(order['_id'])
            order['created_at'] = order['created_at'].isoformat()
            order['delivery_date'] = order['delivery_date'] if isinstance(order['delivery_date'], str) else order['delivery_date'].isoformat()
        return jsonify(user_orders)

@api_bp.route('/orders/<order_id>', methods=['GET'])
@jwt_required()
def get_order(order_id):
    user_email = get_jwt_identity()
    try:
        order = mongo.db.orders.find_one({'_id': ObjectId(order_id), 'user_email': user_email})
        if not order:
            return jsonify({"msg": "Order not found or access denied"}), 404
        
        order['_id'] = str(order['_id'])
        return jsonify(order), 200
    except Exception as e:
        return jsonify({"msg": f"Invalid Order ID format: {e}"}), 400

@api_bp.route('/orders/<order_id>', methods=['PUT'])
@jwt_required()
def update_order(order_id):
    user_email = get_jwt_identity()
    
    order = mongo.db.orders.find_one({'_id': ObjectId(order_id), 'user_email': user_email})
    if not order:
        return jsonify({"msg": "Order not found or access denied"}), 404
    
    if order.get('status') not in ['pending', 'confirmed']:
        return jsonify({"msg": f"Order with status '{order.get('status')}' cannot be modified."}), 400

    cart = mongo.db.carts.find_one({'user_email': user_email})
    if not cart or not cart.get('items'):
        return jsonify({"msg": "Cannot update with an empty cart. Please add items."}), 400

    data = request.get_json()
    update_doc = {
        'items': cart['items'],
        'delivery_date': data['deliveryDate'],
        'delivery_address': data['deliveryAddress'],
        'mobile_number': data['mobileNumber'],
        'additional_info': data.get('additionalInfo'),
        'total_amount': data.get('totalAmount'),
        'updated_at': datetime.utcnow()
    }

    mongo.db.orders.update_one({'_id': ObjectId(order_id)}, {'$set': update_doc})
    mongo.db.carts.delete_one({'user_email': user_email})
        
    return jsonify({"msg": "Order updated successfully!", "orderId": order_id}), 200

@api_bp.route('/orders/<order_id>/cancel', methods=['POST'])
@jwt_required()
def cancel_order(order_id):
    user_email = get_jwt_identity()
    order = mongo.db.orders.find_one({'_id': ObjectId(order_id), 'user_email': user_email})

    if not order:
        return jsonify({"msg": "Order not found or access denied"}), 404
    
    if order.get('status') in ['delivered', 'cancelled']:
        return jsonify({"msg": "This order can no longer be cancelled."}), 400
    
    mongo.db.orders.update_one(
        {'_id': ObjectId(order_id)},
        {'$set': {'status': 'cancelled', 'updated_at': datetime.utcnow()}}
    )
    
    return jsonify({"msg": "Order has been cancelled."}), 200

@api_bp.route('/sendmail', methods=['GET'])
def send_cart_reminders():
    try:
        carts_with_items = list(mongo.db.carts.find({'items': {'$exists': True, '$ne': []}}))
        
        if not carts_with_items:
            return jsonify({"msg": "No users with pending items in cart."}), 200

        user_emails = [cart['user_email'] for cart in carts_with_items]
        all_product_ids = {
            ObjectId(item['productId']) 
            for cart in carts_with_items 
            for item in cart.get('items', [])
        }

        users_cursor = mongo.db.users.find({'email': {'$in': user_emails}})
        products_cursor = mongo.db.products.find({'_id': {'$in': list(all_product_ids)}})

        users_map = {user['email']: user for user in users_cursor}
        products_map = {str(prod['_id']): prod for prod in products_cursor}

        emails_sent_count = 0
        
        for cart in carts_with_items:
            user = users_map.get(cart['user_email'])
            if not user:
                current_app.logger.warning(f"Cart found for non-existent user: {cart['user_email']}")
                continue

            populated_items = []
            for item in cart.get('items', []):
                product_details = products_map.get(item['productId'])
                if product_details:
                    populated_items.append({
                        'product': {
                            'id': str(product_details['_id']), 
                            'name': product_details.get('name'), 
                        },
                        'quantity': item['quantity']
                    })
            
            if populated_items:
                try:
                    send_cart_reminder_email(user, populated_items)
                    emails_sent_count += 1
                except Exception as e:
                    current_app.logger.error(f"Failed to send cart reminder to {user['email']}: {e}")

        return jsonify({"msg": f"Cart reminder process finished. Emails sent to {emails_sent_count} users."}), 200

    except Exception as e:
        current_app.logger.error(f"Error in /sendmail endpoint: {e}")
        return jsonify({"msg": "An internal error occurred while sending reminders."}), 500

@api_bp.route('/admin/users/approve/<user_id>', methods=['POST'])
@jwt_required()
def approve_user(user_id):
    mongo.db.users.update_one({'_id': ObjectId(user_id)}, {'$set': {'is_approved': True}})
    return jsonify({"msg": f"User {user_id} approved"})

# +++ START: NEW ENDPOINT FOR ITEM REQUESTS +++
@api_bp.route('/request-item', methods=['POST'])
@jwt_required()
def request_item():
    """

    Allows a logged-in user to request an item that is not in the catalog.

    The request is saved to the database for admin review.

    """
    user_email = get_jwt_identity()
    data = request.get_json()

    if not data or not data.get('details'):
        return jsonify({"msg": "Item details are required."}), 400

    details = data.get('details').strip()
    if not details:
        return jsonify({"msg": "Item details cannot be empty."}), 400

    try:
        # Fetch user info for more context in the request
        user = mongo.db.users.find_one({'email': user_email}, {'company_name': 1})
        company_name = user.get('company_name', 'N/A') if user else 'N/A'

        request_doc = {
            'user_email': user_email,
            'company_name': company_name,
            'details': details,
            'status': 'new',  # Possible statuses: 'new', 'reviewed', 'sourced', 'rejected'
            'requested_at': datetime.utcnow()
        }

        # The collection 'item_requests' will be created if it doesn't exist
        mongo.db.item_requests.insert_one(request_doc)

        # Optional: Here you could add a call to an email utility to notify admins
        # For example: send_item_request_notification(user_email, company_name, details)
        
        return jsonify({"msg": "Your item request has been submitted. We will look into it!"}), 201

    except Exception as e:
        current_app.logger.error(f"Error processing item request for {user_email}: {e}")
        return jsonify({"msg": "An internal server error occurred."}), 500