import os
import openpyxl
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
import json

def format_num(n):
    if n is None: return "-"
    return f"{int(n):,}"

def format_pct(val):
    if val is None: return "-"
    return f"{val:+.1f}%"

def format_diff(val):
    if val is None: return "-"
    return f"{int(val):+,}"

# Read data
wb = openpyxl.load_workbook('File-lam-sach/MUA_HANG_26T9-26_DA-LAM-SACH.xlsx', data_only=True)
ws = wb.active

header_row = 5
data = []

# Read rows
for r in range(header_row + 1, ws.max_row + 1):
    val_stt = ws.cell(r, 1).value
    val_ma = ws.cell(r, 2).value
    val_ten = ws.cell(r, 3).value
    
    row_data = []
    for c in range(4, 13): # T1 to T9
        v = ws.cell(r, c).value
        try:
            row_data.append(float(v) if v is not None else 0.0)
        except:
            row_data.append(0.0)
            
    if str(val_ten).strip().lower() == "tổng cộng":
        continue
    
    if not val_ma:
        continue
        
    data.append({
        'stt': val_stt,
        'ma': val_ma,
        'ten': val_ten,
        'months': row_data
    })

# calculate tong cong ourselves
tong_cong_row = [0] * 9
for d in data:
    for i in range(9):
        tong_cong_row[i] += d['months'][i]

# Days: T1..T8, T9=26
days = [31, 28, 31, 30, 31, 30, 31, 31, 26]
months_name = ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Từ 1->26 T9/2026']

doc = Document()
# set font
style = doc.styles['Normal']
style.font.name = 'Times New Roman'
style.font.size = Pt(11)

title = doc.add_paragraph("BÁO CÁO MUA HÀNG THÁNG 9 - KỲ TỪ 1->26 THÁNG 09/2026")
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
for run in title.runs:
    run.font.bold = True
    run.font.size = Pt(16)

h1 = doc.add_paragraph("1. TỔNG HỢP TOÀN CÔNG TY")
for run in h1.runs:
    run.font.bold = True
    run.font.size = Pt(13)

# Table 1
table1 = doc.add_table(rows=1, cols=6)
table1.style = 'Table Grid'
hdr_cells = table1.rows[0].cells
headers1 = ['Kỳ', 'Tổng lượng (Kg)', 'Số ngày', 'TB/ngày (Kg)', 'Chênh lệch so với kỳ trước', '%']
for i, h in enumerate(headers1):
    hdr_cells[i].text = h
    hdr_cells[i].paragraphs[0].runs[0].font.bold = True

tb_ngay_cong_ty = [tong_cong_row[i] / days[i] for i in range(9)]

for i in range(9):
    row_cells = table1.add_row().cells
    row_cells[0].text = months_name[i]
    row_cells[1].text = format_num(tong_cong_row[i])
    row_cells[2].text = str(days[i])
    row_cells[3].text = format_num(tb_ngay_cong_ty[i])
    
    if i == 0:
        row_cells[4].text = "-"
        row_cells[5].text = "-"
    else:
        diff_kg = tb_ngay_cong_ty[i] - tb_ngay_cong_ty[i-1]
        pct = (diff_kg / tb_ngay_cong_ty[i-1] * 100) if tb_ngay_cong_ty[i-1] > 0 else 0
        row_cells[4].text = format_diff(diff_kg)
        row_cells[5].text = format_pct(pct)

doc.add_paragraph()
h2 = doc.add_paragraph("2. CHI TIẾT KHÁCH HÀNG")
for run in h2.runs:
    run.font.bold = True
    run.font.size = Pt(13)

# Table 2
table2 = doc.add_table(rows=1, cols=14)
table2.style = 'Table Grid'
hdr_cells2 = table2.rows[0].cells
headers2 = ['STT', 'Mã KH', 'Tên KH', 'TB T1', 'TB T2', 'TB T3', 'TB T4', 'TB T5', 'TB T6', 'TB T7', 'TB T8', 'TB T9 (1->26)', '+/- Kg', '%']
for i, h in enumerate(headers2):
    hdr_cells2[i].text = h
    hdr_cells2[i].paragraphs[0].runs[0].font.bold = True
    # font size
    for r in hdr_cells2[i].paragraphs[0].runs:
        r.font.size = Pt(10)

# Calculate for customers
for i, d in enumerate(data):
    row_cells = table2.add_row().cells
    row_cells[0].text = str(d['stt'] or i+1)
    row_cells[1].text = str(d['ma'])
    row_cells[2].text = str(d['ten'])
    
    tb_ngay_kh = [d['months'][m] / days[m] for m in range(9)]
    
    for m in range(9):
        row_cells[3+m].text = format_num(tb_ngay_kh[m])
        
    diff_kg = tb_ngay_kh[8] - tb_ngay_kh[7]
    pct = (diff_kg / tb_ngay_kh[7] * 100) if tb_ngay_kh[7] > 0 else 0
    
    row_cells[12].text = format_diff(diff_kg)
    row_cells[13].text = format_pct(pct)

# Save DOCX
os.makedirs('Bao_cao', exist_ok=True)
docx_path = 'Bao_cao/BAO_CAO_SO_SANH_MUA_HANG_T9_ky26.docx'
doc.save(docx_path)
print(f"Saved to {docx_path}")