from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
import os

# --- 1. SETUP: COLORS & FONTS ---

# Define a professional color palette
COLORS = {
    'primary': colors.HexColor("#003366"),      # A deep, professional blue
    'secondary': colors.HexColor("#0056b3"),    # A lighter blue for emphasis
    'accent': colors.HexColor("#F7A400"),       # The original orange for highlights
    'text': colors.HexColor("#333333"),         # Dark grey for body text (softer than black)
    'light_grey': colors.HexColor("#f2f2f2"),   # For table row backgrounds
    'header_bg': colors.HexColor("#004080"),    # Dark blue for table headers
}

# Standard fonts are built-in, no need to register them
FONT_BOLD = 'Helvetica-Bold'
FONT_NORMAL = 'Helvetica'
FONT_BODY = 'Times-Roman'

# --- 2. HELPER FUNCTION FOR FOOTER ---

def add_footer(canvas, doc):
    """
    Adds a footer with page number to each page.
    """
    canvas.saveState()
    footer_text = f"Page {canvas.getPageNumber()}"
    canvas.setFont(FONT_NORMAL, 9)
    canvas.setFillColor(COLORS['text'])
    canvas.drawCentredString(doc.pagesize[0] / 2, 0.5 * inch, footer_text)
    canvas.restoreState()

# --- 3. DOCUMENT SETUP ---


# Get the user's desktop path automatically
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
file_path = os.path.join(desktop_path, "Easinovation_SWAP_CNG_Proposal_Full.pdf")

# Create a custom document template to include the footer
doc = BaseDocTemplate(
    file_path,
    pagesize=A4,
    rightMargin=72,
    leftMargin=72,
    topMargin=72,
    bottomMargin=72
)

# Create a frame for the content area
frame = Frame(
    doc.leftMargin,
    doc.bottomMargin + 0.5 * inch, # Add space for footer
    doc.width,
    doc.height - 0.5 * inch, # Reduce height for footer
    leftPadding=0,
    rightPadding=0
)

# Create a PageTemplate and add the footer
template = PageTemplate(id='main', frames=[frame], onPage=add_footer)
doc.addPageTemplates([template])

# --- 4. STYLES ---

styles = getSampleStyleSheet()

# Title Style
title_style = ParagraphStyle(
    name="CustomTitle",
    parent=styles['Title'],
    fontName=FONT_BOLD,
    fontSize=24,
    leading=30,
    textColor=COLORS['primary'],
    alignment=TA_CENTER,
    spaceAfter=20
)

# Header Style for sections
header_style = ParagraphStyle(
    name="CustomHeader",
    parent=styles['Heading1'],
    fontName=FONT_BOLD,
    fontSize=16,
    leading=22,
    textColor=COLORS['primary'],
    borderWidth=0,
    borderColor=COLORS['accent'],
    borderPadding=0,
    spaceBefore=20,
    spaceAfter=12
)

# Body Style
body_style = ParagraphStyle(
    name="CustomBody",
    parent=styles['Normal'],
    fontName=FONT_BODY,
    fontSize=11,
    leading=18,
    textColor=COLORS['text'],
    spaceAfter=12
)

# Style for sub-bullets or indented text
sub_body_style = ParagraphStyle(
    name="SubBody",
    parent=body_style,
    leftIndent=20,
    bulletIndent=10,
    spaceAfter=6
)

# --- 5. CONTENT ---

content = []

# Company Info
content.append(Paragraph("<b>EASINOVATION LTD</b>", title_style))
content.append(Paragraph(
    "Email: easinovation@gmail.com | Website: www.easinovation.com.ng | Tel: 08147513325",
    ParagraphStyle(name='ContactInfo', parent=body_style, alignment=TA_CENTER, fontSize=10)
))
content.append(Spacer(1, 0.2 * inch))

# Project Title
content.append(Paragraph("<b>PROJECT PROPOSAL</b>", header_style))
content.append(Paragraph("For <b>SWAP CNG Solutions</b>", body_style))
content.append(Spacer(1, 0.2 * inch))

# Introduction
content.append(Paragraph("1. Introduction", header_style))
content.append(Paragraph(
    "Easinovation Ltd is pleased to present this proposal for the design and development of the SWAP CNG web platform — a comprehensive digital solution for promoting and managing Nigeria’s CNG (Compressed Natural Gas) transportation ecosystem. This platform will provide seamless access to services including CNG conversions, vehicle registration, refill station tracking, and customer support.",
    body_style
))
content.append(Spacer(1, 0.1 * inch))

# Project Objectives
content.append(Paragraph("2. Project Objectives", header_style))
content.append(Paragraph(
    "The primary objective is to deliver a modern, responsive, and secure platform that enhances user experience, supports efficient administration, and integrates with key services like Google Maps for location-based monitoring. The system will include:",
    body_style
))
objectives = [
    "A professional landing page (based on client-provided design)",
    "A fully functional Admin Dashboard",
    "A User Dashboard with account and vehicle management",
    "Integration with Google Maps API for live station monitoring",
    "Backend API and database development",
    "Secure authentication and user management"
]
for obj in objectives:
    content.append(Paragraph(f"• {obj}", sub_body_style))
content.append(Spacer(1, 0.1 * inch))

# Scope of Work
content.append(Paragraph("3. Scope of Work", header_style))
scope_data = [
    ["1.", "Frontend Development (Landing Page, Admin Dashboard, User Dashboard)"],
    ["2.", "Backend Development (APIs, Authentication, Database Models)"],
    ["3.", "Google Maps API Integration for real-time monitoring"],
    ["4.", "Responsive Design for all devices"],
    ["5.", "Testing, Debugging, and Deployment"],
    ["6.", "Post-launch Technical Support (Optional Monthly Plan)"]
]
scope_table = Table(scope_data, colWidths=[0.5 * inch, 6 * inch])
scope_table.setStyle(TableStyle([
    ('BACKGROUND', (0, 0), (-1, -1), colors.white),
    ('ROWBACKGROUNDS', (0, 0), (-1, -1), [colors.white, COLORS['light_grey']]),
    ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ('FONTNAME', (0, 0), (-1, -1), FONT_NORMAL),
    ('FONTSIZE', (0, 0), (-1, -1), 10),
    ('LEFTPADDING', (0, 0), (-1, -1), 8),
    ('RIGHTPADDING', (0, 0), (-1, -1), 8),
    ('TOPPADDING', (0, 0), (-1, -1), 8),
    ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
]))
content.append(scope_table)
content.append(Spacer(1, 0.2 * inch))

# Technical Stack
content.append(Paragraph("4. Technical Stack", header_style))
content.append(Paragraph(
    "The platform will be developed using the following technologies:",
    body_style
))
stack_items = [
    ("<b>Frontend:</b> React.js (InertiaJS & TailwindCSS)"),
    ("<b>Backend:</b> Laravel (PHP) or Node.js (depending on API structure)"),
    ("<b>Database:</b> MySQL or PostgreSQL"),
    ("<b>Maps Integration:</b> Google Maps API"),
    ("<b>Hosting:</b> Client-provided server or recommended cloud provider")
]
for item in stack_items:
    content.append(Paragraph(f"• {item}", sub_body_style))
content.append(Spacer(1, 0.2 * inch))

# Timeline
content.append(Paragraph("5. Project Timeline", header_style))
timeline_table = Table([
    ["Project Phase", "Duration"],
    ["UI/UX Integration & Setup", "2 Weeks"],
    ["Frontend & Backend Development", "4 Weeks"],
    ["Testing & QA", "1 Week"],
    ["Deployment & Review", "1 Week"],
    ["<b>Total Duration</b>", "<b>8 Weeks</b>"]
], colWidths=[4 * inch, 2.5 * inch])
timeline_table.setStyle(TableStyle([
    ('BACKGROUND', (0, 0), (-1, 0), COLORS['header_bg']),
    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
    ('ALIGN', (1, 0), (1, -1), 'CENTER'),
    ('FONTNAME', (0, 0), (-1, 0), FONT_BOLD),
    ('FONTNAME', (0, 1), (-1, -1), FONT_NORMAL),
    ('FONTSIZE', (0, 0), (-1, -1), 10),
    ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, COLORS['light_grey']]),
    ('LEFTPADDING', (0, 0), (-1, -1), 8),
    ('RIGHTPADDING', (0, 0), (-1, -1), 8),
    ('TOPPADDING', (0, 0), (-1, -1), 10),
    ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
]))
content.append(timeline_table)
content.append(Spacer(1, 0.2 * inch))

# Cost
content.append(Paragraph("6. Project Cost", header_style))
content.append(Paragraph(
    "The total cost for the development of the full SWAP CNG platform is <b>₦950,000 (Nine Hundred and Fifty Thousand Naira)</b>.",
    body_style
))
content.append(Spacer(1, 0.1 * inch))
payment_data = [
    ["First Installment (50%)", "₦475,000 - Payable upfront before commencement"],
    ["Second Installment (50%)", "₦475,000 - Payable upon final delivery and approval"]
]
payment_table = Table(payment_data, colWidths=[2.5 * inch, 4 * inch])
payment_table.setStyle(TableStyle([
    ('BACKGROUND', (0, 0), (-1, -1), colors.white),
    ('ROWBACKGROUNDS', (0, 0), (-1, -1), [COLORS['light_grey'], colors.white]),
    ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
    ('FONTNAME', (0, 0), (-1, -1), FONT_NORMAL),
    ('FONTSIZE', (0, 0), (-1, -1), 10),
    ('LEFTPADDING', (0, 0), (-1, -1), 8),
    ('RIGHTPADDING', (0, 0), (-1, -1), 8),
    ('TOPPADDING', (0, 0), (-1, -1), 8),
    ('BOTTOMPADDING', (0, 0), (-1, -1), 8),
]))
content.append(payment_table)
content.append(Spacer(1, 0.2 * inch))

# Maintenance
content.append(Paragraph("7. Maintenance & Support (Optional)", header_style))
content.append(Paragraph(
    "Easinovation Ltd offers an optional monthly maintenance plan at <b>₦50,000 per month</b>.",
    body_style
))
content.append(Paragraph("This covers:", body_style))
maintenance_items = [
    "Regular updates and security patches",
    "Bug fixes and technical support",
    "Performance monitoring and optimization",
    "Minor feature improvements based on feedback"
]
for item in maintenance_items:
    content.append(Paragraph(f"• {item}", sub_body_style))
content.append(Spacer(1, 0.2 * inch))

# Terms
content.append(Paragraph("8. Terms & Conditions", header_style))
terms = [
    "All payments should be made to Easinovation Ltd before commencement of respective phases.",
    "Any major feature additions outside the agreed scope will be billed separately.",
    "Maintenance is optional and billed monthly post-deployment.",
    "Client shall provide necessary assets (logos, content, and access credentials) promptly to avoid delays."
]
for i, term in enumerate(terms, 1):
    content.append(Paragraph(f"{i}. {term}", body_style))
content.append(Spacer(1, 0.2 * inch))

# Acceptance & Signature
content.append(Paragraph("9. Acceptance", header_style))
content.append(Paragraph(
    "By signing below, both parties agree to the terms and conditions outlined in this proposal and authorize Easinovation Ltd to commence the SWAP CNG project as described.",
    body_style
))
content.append(Spacer(1, 0.4 * inch))

sign_table = Table([
    ["", ""],
    ["_________________________", "_________________________"],
    ["Easinovation Ltd", "SWAP CNG Solutions"],
    ["", ""],
    ["Date: _________________", "Date: _________________"]
], colWidths=[3.5 * inch, 3.5 * inch])
sign_table.setStyle(TableStyle([
    ('FONTNAME', (0, 0), (-1, -1), FONT_NORMAL),
    ('FONTSIZE', (0, 0), (-1, -1), 10),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
]))
content.append(sign_table)


# --- 6. BUILD PDF ---
doc.build(content)

print(f"✅ PDF generated successfully!")
print(f"📄 File saved as: {file_path}")
