# Booking Lifecycle Restructuring & Timeouts

This plan details the implementation of the new booking flow, dynamic timeouts, logging mechanisms, and availability blocking based on your requirements.

## User Review Required

> [!IMPORTANT]
> Please review the "Open Questions" section below to clarify some business logic details before I start the implementation.

## Open Questions

1. **مهلة الـ 15 دقيقة أم ساعة:** في الرسالة ذكرت "15 دقيقة" لعدم رد المالك، ثم ذكرت "الوقت معاش 15 ساعة". هل المقصود أن المهلة الافتراضية هي **15 دقيقة** فعلاً؟
2. **وقت الدخول (Check-in time):** بالنسبة للطلبات بعد الساعة 10 ليلاً، هل نعتمد على حقل `check_in_time` الموجود في جدول `TblPropertyDetail` (مثلاً 14:00) لتمديد الطلب حتى قبل ساعة منه (أي 13:00 من يوم الحجز)؟
3. **تصكير الأيام (Availability):** كما اقترحت، أفضل وأسهل طريقة لمنع التضارب هي **تصكير الأيام في `tbl_availability` بمجرد أن يدير الزبون طلب الحجز (في الـ store)**. وفي حال الإلغاء (رفض المالك، أو انتهاء المهلة للزبون أو المالك)، نقوم بمسح هذه الأيام من `tbl_availability` لترجع متاحة. هل تعتمد هذه الطريقة؟
4. **مهلة الدفع للزبون (ساعة):** ذكرت "(المحفظة مش الكاش)". هل يعني هذا أن الزبون لو اختار الدفع "كاش" من البداية لا تطبق عليه مهلة الساعة؟ حالياً الزبون لا يختار طريقة الدفع إلا في خطوة الدفع `payBooking`. كيف سنعرف في مرحلة الـ `STATE_CONFIRM` إذا كان ناوياً الدفع كاش أم محفظة؟ (ربما نطبق الساعة على الجميع في مرحلة ما قبل الدفع، وبمجرد الدفع أو اختيار الكاش يثبت الحجز؟).

---

## Proposed Changes

### 1. Database Migrations

We need to create a unified table to log all booking cancellations, timeouts, and rejections.

#### [NEW] `create_booking_cancellation_logs_table.php` (Migration)
- **`booking_cancellation_logs`**: A unified table for all cancellation events.
  - Columns: 
    - `id`
    - `booking_id`
    - `user_id` (The ID of the user who caused the cancellation: Host or Customer)
    - `type` (Enum/String: `host_timeout`, `customer_timeout`, `host_rejected`, `customer_cancelled`, `admin_cancelled`)
    - `notes` (Text, nullable - used for host rejection reasons or extra context)
    - `created_at`, `updated_at`

---

### 2. Controllers

#### [MODIFY] `app/Http/Controllers/API/BookingController.php`
- **`store()`**: 
  - Save the booking with `STATE_WAITING` (if mobile) or `STATE_WEB_PAID` (if web).
  - Web bookings will continue to bypass the confirmation and timeout flow exactly as they currently do (since web bookings are made directly by the property owner and are not considered booking requests).
  - Immediately check dates dynamically against `tbl_booking` and `tbl_availability` for conflicts.
- **`payBooking()`**:
  - Remove the late `tbl_availability` lock logic since it will now be done in `store()`.
- **[NEW METHOD] `rejectBooking()`**:
  - Allow the owner to reject a `STATE_WAITING` booking.
  - Accept an optional `reason`.
  - Update state to `STATE_CANCELLED`, release `tbl_availability` dates, notify customer, and insert a record into `booking_cancellation_logs` with type `host_rejected` and `notes = reason`.

---

### 3. Console Commands (Cron Jobs)

#### [MODIFY] `app/Console/Commands/CancelAvailabilities.php`
- Modify the script to check for multiple timeout conditions instead of a hardcoded 24h:
  - **Host Timeout (STATE_WAITING):**
    - If created after 10 PM: Timeout is 1 hour before the property's `check_in_time` on the `start_date`.
    - If created before 10 PM: Timeout is 15 minutes.
    - Action: Cancel booking, free availability, notify customer, and insert into `booking_cancellation_logs` (type: `host_timeout`).
  - **Customer Timeout (STATE_CONFIRM):**
    - If state is `STATE_CONFIRM` and it's been more than 1 hour since the state changed (or since booking was confirmed).
    - Action: Cancel booking, free availability, insert into `booking_cancellation_logs` (type: `customer_timeout`).

*(Note: We might need to add a `confirmed_at` timestamp column to `tbl_booking` to track exactly when the owner confirmed, so we can accurately measure the 1 hour).*

---

### 4. Models

#### [MODIFY] `app/Models/TblBooking.php`
- Add relationships for the new log models.
- (Optional) Add a new column `confirmed_at` to track when the state changed to `STATE_CONFIRM`. If not, we can rely on `updated_at`, though a dedicated timestamp is safer.

#### [NEW] Log Models
- Create an Eloquent model for the new logging table:
  - `BookingCancellationLog.php`

---

## Verification Plan

### Automated/Manual Verification
1. **Host Timeout Logic:**
   - Create a booking before 10 PM. Run the cron job after 16 minutes -> verify it gets cancelled and logged in `host_no_response_logs`.
   - Create a booking after 10 PM. Run the cron job -> verify it does NOT get cancelled until 1 hour before check-in time.
2. **Customer Timeout Logic:**
   - Confirm a booking as an owner. Wait for 1 hour. Run the cron job -> verify it is cancelled, dates freed, and logged in `customer_timeout_logs`.
3. **Availability Lock:**
   - Create a booking. Ensure `tbl_availability` immediately reflects the booked dates so no one else can request them.
   - Cancel the booking -> verify the dates are deleted/released from `tbl_availability`.
4. **Owner Rejection:**
   - Hit the new `rejectBooking` endpoint with a reason -> verify the reason is logged and the customer is notified.
