# 🔍 DEBUG: Tại sao `student_daily_study_time` không được update?

## 📋 LUỒNG HOẠT ĐỘNG

### **1. Khi nào `distributeDailyTime()` chạy?**

`distributeDailyTime()` được gọi từ `endSessionWithTime()` (line 324), và `endSessionWithTime()` được gọi từ:

| Method | Khi nào | Line |
|--------|---------|------|
| `submitSession()` | Khi học sinh click **Submit** | 163 |
| `stopSession()` | Khi học sinh click **Stop** | 193 |
| `continueSession()` | Khi học sinh click **Continue** (end session cũ) | 90 |
| `autoEndInactiveSessions()` | Khi cron job auto-end session (sau 10 phút không heartbeat) | 266 |

---

### **2. Khi nào `updateDailyStudyTime()` chạy?**

`updateDailyStudyTime()` được gọi từ **bên trong loop** của `distributeDailyTime()` (line 372), và chỉ chạy khi:

✅ **Điều kiện:**
1. `$currentDate <= $endDate` (loop chạy)
2. `$secondsInDay > 0` (không bị skip)

❌ **Không chạy nếu:**
- `$secondsInDay <= 0` → Bị skip (line 358-361)

---

## 🔍 LOGIC TRONG `distributeDailyTime()`

### **Step 1: Tính toán date range**
```php
$currentDate = $startTime->copy()->startOfDay();  // VD: 2025-12-05 00:00:00
$endDate = $endTime->copy()->startOfDay();        // VD: 2025-12-05 00:00:00 (cùng ngày)
```

### **Step 2: Loop qua các ngày**
```php
while ($currentDate <= $endDate) {
    // Với cùng ngày: loop chạy 1 lần
}
```

### **Step 3: Tính toán thời gian trong ngày**
```php
$dayStart = $currentDate->copy();           // 2025-12-05 00:00:00
$dayEnd = $currentDate->copy()->endOfDay(); // 2025-12-05 23:59:59

$sessionStartInDay = $startTime->greaterThan($dayStart) ? $startTime : $dayStart;
$sessionEndInDay = $endTime->lessThan($dayEnd) ? $endTime : $dayEnd;

$secondsInDay = $sessionEndInDay->diffInSeconds($sessionStartInDay);
```

### **Step 4: Kiểm tra và update**
```php
if ($secondsInDay <= 0) {
    continue; // ❌ SKIP - Không update
}

// ✅ UPDATE
$this->updateDailyStudyTime(...);
```

---

## ⚠️ VẤN ĐỀ CÓ THỂ XẢY RA

### **Vấn đề 1: `$secondsInDay <= 0`**

**Nguyên nhân:**
- `$startTime` và `$endTime` quá gần nhau (ví dụ: cùng giây)
- Logic tính toán sai

**Cách kiểm tra:**
```bash
# Xem log
tail -f storage/logs/laravel.log | grep "distributeDailyTime"
```

**Log sẽ hiển thị:**
```
distributeDailyTime LOOP: {
    "secondsInDay": 0,  // ❌ Nếu = 0 thì sẽ bị skip
    "will_skip": true
}
```

---

### **Vấn đề 2: `$tenantConnection` là `null`**

**Nguyên nhân:**
- `$tenantConnection` không được truyền đúng từ API

**Cách kiểm tra:**
```bash
# Xem log
tail -f storage/logs/laravel.log | grep "updateDailyStudyTime"
```

**Log sẽ hiển thị:**
```
updateDailyStudyTime: tenantConnection is null  // ❌ Warning
```

---

### **Vấn đề 3: Exception trong `updateDailyStudyTime()`**

**Nguyên nhân:**
- Database connection lỗi
- Constraint violation
- Table không tồn tại

**Cách kiểm tra:**
```bash
# Xem log
tail -f storage/logs/laravel.log | grep "Failed to update daily study time"
```

---

## ✅ CÁCH DEBUG

### **1. Kiểm tra log khi Submit:**

```bash
# Xem toàn bộ log liên quan
tail -f storage/logs/laravel.log | grep -E "distributeDailyTime|updateDailyStudyTime"
```

**Log mong đợi:**
```
[INFO] distributeDailyTime START: {
    "session_id": 123,
    "startTime": "2025-12-05 10:00:00",
    "endTime": "2025-12-05 10:15:00",
    "durationSeconds": 900,
    "adjustedSeconds": 300  // Min 5 phút
}

[INFO] distributeDailyTime LOOP: {
    "loop_count": 1,
    "secondsInDay": 900,
    "will_skip": false
}

[INFO] distributeDailyTime CALLING updateDailyStudyTime: {
    "student_id": 456,
    "date": "2025-12-05",
    "adjustedMinutesInDay": 5.0
}

[INFO] Updated daily study time: {
    "student_id": 456,
    "date": "2025-12-05",
    "minutes": 5.0
}
```

---

### **2. Kiểm tra database:**

```sql
-- Xem sessions
SELECT id, student_id, status, session_start_at, session_end_at, 
       duration_seconds, adjusted_duration_seconds
FROM student_study_sessions 
WHERE student_id = YOUR_STUDENT_ID 
ORDER BY session_start_at DESC 
LIMIT 5;

-- Xem daily study time
SELECT * FROM student_daily_study_time 
WHERE student_id = YOUR_STUDENT_ID 
ORDER BY study_date DESC;
```

---

### **3. Test thủ công:**

```php
// Trong tinker
$service = app(\App\Services\HeatUser\StudySessionService::class);
$session = \App\Models\HeatUser\StudentStudySession::find(SESSION_ID);
$tenantConnection = 'tenant_connection_name';

$service->submitSession($session->id, $session->student_id, $tenantConnection);
```

---

## 🔧 CÁC TRƯỜNG HỢP CẦN KIỂM TRA

### **Case 1: Start và Submit trong cùng ngày**

**Luồng:**
```
1. Start: 2025-12-05 10:00:00
2. Submit: 2025-12-05 10:15:00
3. distributeDailyTime() chạy:
   - $currentDate = 2025-12-05 00:00:00
   - $endDate = 2025-12-05 00:00:00
   - Loop chạy 1 lần
   - $secondsInDay = 900 (15 phút)
   - ✅ updateDailyStudyTime() được gọi
```

**Kiểm tra:**
- Log có `distributeDailyTime CALLING updateDailyStudyTime`?
- Log có `Updated daily study time`?
- Database có record trong `student_daily_study_time`?

---

### **Case 2: Start → Tắt browser → Auto-end (sau 10 phút)**

**Luồng:**
```
1. Start: 2025-12-05 10:00:00
2. Tắt browser (không heartbeat)
3. Cron job chạy (sau 10 phút): 2025-12-05 10:10:00
4. autoEndInactiveSessions() chạy
5. endSessionWithTime() với endTime = 2025-12-05 10:05:00 (last_heartbeat_at)
6. distributeDailyTime() chạy
7. ✅ updateDailyStudyTime() được gọi
```

**Kiểm tra:**
- Cron job có chạy không? (`php artisan sessions:auto-end`)
- Log có `Auto ended X inactive sessions`?
- Log có `distributeDailyTime`?

---

### **Case 3: Start → Continue → Submit (nhiều ngày)**

**Luồng:**
```
1. Start: 2025-12-05 23:00:00
2. Tắt browser
3. Auto-end: 2025-12-05 23:05:00
   → updateDailyStudyTime() cho 2025-12-05 ✅
4. Continue: 2025-12-06 10:00:00
5. Submit: 2025-12-06 10:15:00
   → updateDailyStudyTime() cho 2025-12-06 ✅
```

**Kiểm tra:**
- Có 2 records trong `student_daily_study_time`?
- Mỗi ngày có đúng thời gian?

---

## 📊 TÓM TẮT

| Vấn đề | Nguyên nhân | Cách fix |
|--------|-------------|----------|
| `updateDailyStudyTime()` không chạy | `$secondsInDay <= 0` | Kiểm tra log `distributeDailyTime LOOP` |
| `tenantConnection is null` | Không truyền đúng từ API | Kiểm tra controller có truyền `$tenantConnection` |
| Exception trong update | Database lỗi | Xem log `Failed to update daily study time` |
| Không có record trong DB | Transaction rollback | Kiểm tra exception trong log |

---

## 🎯 CHECKLIST DEBUG

- [ ] Log có `distributeDailyTime START`?
- [ ] Log có `distributeDailyTime LOOP` với `will_skip: false`?
- [ ] Log có `distributeDailyTime CALLING updateDailyStudyTime`?
- [ ] Log có `Updated daily study time`?
- [ ] Log có `Create new daily study time` hoặc update existing?
- [ ] Database có record trong `student_daily_study_time`?
- [ ] `$tenantConnection` không null?
- [ ] Không có exception trong log?

