# 📚 HƯỚNG DẪN NHANH - HỆ THỐNG QUẢN LÝ TÀI LIỆU

## 🎯 TỔNG QUAN

Hệ thống quản lý tài liệu pháp luật cho tab "Tổng hợp" với đầy đủ tính năng:
- ✅ Upload tài liệu với metadata đầy đủ
- ✅ Lưu trữ thông tin: tiêu đề, loại văn bản, định dạng, đường link
- ✅ Phân loại theo danh mục
- ✅ Tìm kiếm và lọc mạnh mẽ
- ✅ Quản lý tags, ratings, comments
- ✅ Thống kê và báo cáo

---

## 📁 CẤU TRÚC FILE ĐÃ TẠO

```
server_backend/
├── schema.sql              # Cấu trúc database hoàn chỉnh
├── sample_data.sql         # Dữ liệu mẫu để test
├── config.php              # File cấu hình chung
├── upload_file.php         # API upload tài liệu
├── get_user_files.php      # API lấy danh sách tài liệu
└── README.md               # Hướng dẫn chi tiết
```

---

## ⚡ BƯỚC CÀI ĐẶT NHANH

### 1️⃣ Import Database (QUAN TRỌNG!)

```bash
# Mở MySQL command line
mysql -u root -p

# Chạy lệnh
source E:/LAP TRINH JAVA 2026/app-luathinhsu-2025/server_backend/schema.sql
```

Hoặc dùng phpMyAdmin:
1. Mở phpMyAdmin
2. Tạo database mới: `luathinhsu_db`
3. Import file `schema.sql`

### 2️⃣ Import Dữ Liệu Mẫu (Tùy chọn)

```bash
mysql -u root -p < "E:/LAP TRINH JAVA 2026/app-luathinhsu-2025/server_backend/sample_data.sql"
```

### 3️⃣ Tạo Thư Mục Upload

```bash
mkdir server_backend/uploads
mkdir server_backend/uploads/documents
```

### 4️⃣ Cấu Hình Database

Mở file `config.php` và cập nhật:
```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'luathinhsu_db');
define('DB_USER', 'root');
define('DB_PASS', '');  // Nhập password MySQL của bạn
```

---

## 🗄️ CẤU TRÚC DATABASE

### Bảng Chính: `documents`

Lưu trữ TẤT CẢ thông tin tài liệu:

| Trường quan trọng | Mô tả |
|-------------------|-------|
| `document_title` | **Tiêu đề tài liệu** |
| `document_type` | **Loại văn bản** (van_ban_phap_luat, thong_tu, nghi_dinh, quyết_dinh, chi_thi, huong_dan, tai_lieu_tham_khao, bieu_mau, khac) |
| `file_format` | **Định dạng file** (pdf, doc, docx, xls, xlsx, ppt, pptx, txt, zip, rar) |
| `file_url` | **Đường link tải file** |
| `file_path` | Đường dẫn file trên server |
| `file_size` | Kích thước file (bytes) |
| `category_id` | Danh mục (Luật, Nghị định, Thông tư, ...) |
| `issuing_agency` | Cơ quan ban hành |
| `issuing_date` | Ngày ban hành |
| `description` | Mô tả chi tiết |
| `keywords` | Từ khóa tìm kiếm |
| `view_count` | Số lượt xem |
| `download_count` | Số lượt tải |

### Các Bảng Hỗ Trợ

- `document_categories` - Danh mục văn bản
- `document_tags` - Tags/nhãn
- `document_ratings` - Đánh giá
- `document_comments` - Bình luận
- `document_access_log` - Lịch sử truy cập
- `user_favorites` - Tài liệu yêu thích

---

## 🚀 SỬ DỤNG API

### 📤 Upload Tài Liệu

**URL:** `POST http://localhost/server_backend/upload_file.php`

**Ví dụ JavaScript:**

```javascript
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('document_title', 'Luật Hình sự 2015');
formData.append('document_type', 'van_ban_phap_luat');
formData.append('category_id', '1');
formData.append('description', 'Luật Hình sự...');
formData.append('keywords', 'luật, hình sự');
formData.append('issuing_agency', 'Quốc hội');
formData.append('issuing_date', '2015-11-27');
formData.append('is_public', '1');
formData.append('uploaded_by', '1');

const response = await fetch('http://localhost/server_backend/upload_file.php', {
  method: 'POST',
  body: formData
});

const result = await response.json();
console.log(result);
```

**Response:**
```json
{
  "success": true,
  "message": "Upload tài liệu thành công",
  "data": {
    "document_id": 1,
    "document": {
      "document_title": "Luật Hình sự 2015",
      "file_url": "http://localhost/server_backend/uploads/documents/2026/01/...",
      "file_format": "pdf",
      ...
    }
  }
}
```

---

### 📥 Lấy Danh Sách Tài Liệu

**URL:** `GET http://localhost/server_backend/get_user_files.php`

**Ví dụ:**

```javascript
// Lấy tất cả tài liệu
const response = await fetch('http://localhost/server_backend/get_user_files.php?page=1&limit=20');

// Tìm kiếm
const response = await fetch('http://localhost/server_backend/get_user_files.php?search=luật hình sự');

// Lọc theo loại
const response = await fetch('http://localhost/server_backend/get_user_files.php?document_type=van_ban_phap_luat');

// Lọc theo danh mục
const response = await fetch('http://localhost/server_backend/get_user_files.php?category_id=1');

// Kết hợp nhiều filter
const response = await fetch('http://localhost/server_backend/get_user_files.php?category_id=1&document_type=van_ban_phap_luat&page=1&limit=10&include_tags=1');

const result = await response.json();
console.log(result.data.documents);
```

**Response:**
```json
{
  "success": true,
  "data": {
    "documents": [
      {
        "document_id": 1,
        "document_title": "Luật Hình sự 2015",
        "document_type": "van_ban_phap_luat",
        "file_url": "http://...",
        "file_format": "pdf",
        "file_size": 2048000,
        "category_name": "Luật",
        "view_count": 150,
        "download_count": 45,
        ...
      }
    ],
    "pagination": {
      "current_page": 1,
      "total_records": 100,
      "total_pages": 5
    },
    "stats": {
      "total_documents": 100,
      "total_views": 5000,
      "new_this_week": 5
    }
  }
}
```

---

## 📊 CÁC LOẠI VĂN BẢN HỖ TRỢ

```
document_type:
- van_ban_phap_luat    (Văn bản pháp luật)
- thong_tu             (Thông tư)
- nghi_dinh            (Nghị định)
- quyet_dinh           (Quyết định)
- chi_thi              (Chỉ thị)
- huong_dan            (Hướng dẫn)
- tai_lieu_tham_khao   (Tài liệu tham khảo)
- bieu_mau             (Biểu mẫu)
- khac                 (Khác)
```

## 📄 ĐỊNH DẠNG FILE HỖ TRỢ

```
✅ PDF (.pdf)
✅ Word (.doc, .docx)
✅ Excel (.xls, .xlsx)
✅ PowerPoint (.ppt, .pptx)
✅ Text (.txt)
✅ Archive (.zip, .rar)
```

**Kích thước tối đa:** 50MB (có thể tùy chỉnh trong `config.php`)

---

## 🔍 TÌM KIẾM VÀ LỌC

API `get_user_files.php` hỗ trợ:

| Parameter | Mô tả | Ví dụ |
|-----------|-------|-------|
| `search` | Tìm kiếm full-text | `?search=luật hình sự` |
| `category_id` | Lọc theo danh mục | `?category_id=1` |
| `document_type` | Lọc theo loại văn bản | `?document_type=van_ban_phap_luat` |
| `file_format` | Lọc theo định dạng | `?file_format=pdf` |
| `is_featured` | Chỉ tài liệu nổi bật | `?is_featured=1` |
| `issuing_date_from` | Từ ngày ban hành | `?issuing_date_from=2020-01-01` |
| `issuing_date_to` | Đến ngày ban hành | `?issuing_date_to=2025-12-31` |
| `page` | Trang hiện tại | `?page=1` |
| `limit` | Số bản ghi/trang | `?limit=20` |
| `order_by` | Sắp xếp theo | `?order_by=created_at` |
| `order_dir` | Hướng sắp xếp | `?order_dir=DESC` |

---

## 🎨 TÍCH HỢP VÀO FRONTEND

### React Component Mẫu

```jsx
import { useState, useEffect } from 'react';

function DocumentList() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchDocuments();
  }, []);
  
  const fetchDocuments = async () => {
    try {
      const response = await fetch('http://localhost/server_backend/get_user_files.php?page=1&limit=20');
      const result = await response.json();
      
      if (result.success) {
        setDocuments(result.data.documents);
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };
  
  if (loading) return <div>Đang tải...</div>;
  
  return (
    <div>
      <h2>Danh sách tài liệu</h2>
      {documents.map(doc => (
        <div key={doc.document_id}>
          <h3>{doc.document_title}</h3>
          <p>Loại: {doc.document_type}</p>
          <p>Định dạng: {doc.file_format}</p>
          <p>Lượt xem: {doc.view_count}</p>
          <a href={doc.file_url} target="_blank">Tải về</a>
        </div>
      ))}
    </div>
  );
}
```

---

## ⚠️ LƯU Ý QUAN TRỌNG

1. **Bảo mật:**
   - Hiện tại chưa có authentication
   - Cần thêm JWT hoặc session authentication cho production
   - Validate input để tránh SQL injection (đã có sẵn PDO prepared statements)

2. **Performance:**
   - Đã có indexes cho các trường thường query
   - Sử dụng pagination để tránh load quá nhiều dữ liệu
   - Có thể cache kết quả nếu cần

3. **Storage:**
   - File upload được lưu trong `uploads/documents/YYYY/MM/`
   - Backup thư mục này thường xuyên
   - Cân nhắc dùng cloud storage (S3, Google Cloud) cho production

---

## 🐛 TROUBLESHOOTING

### Lỗi kết nối database?
→ Kiểm tra MySQL đã chạy và thông tin trong `config.php`

### Không upload được file?
→ Kiểm tra thư mục `uploads/documents/` đã tồn tại và có quyền ghi

### File quá lớn?
→ Tăng `upload_max_filesize` trong `php.ini`

### Lỗi CORS?
→ Đã có CORS headers trong code, kiểm tra browser console

---

## 📞 LIÊN HỆ & HỖ TRỢ

Nếu cần hỗ trợ thêm, vui lòng cung cấp:
- Thông báo lỗi chi tiết
- Screenshot nếu có
- Phiên bản PHP và MySQL đang dùng

---

**🎉 Chúc bạn triển khai thành công!**
