#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import json
from datetime import datetime
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib import colors
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import zipfile
import traceback

# Try to register Bengali font
FONT_NAME = "Helvetica"
try:
    # Download from: https://github.com/ShafinKhadem/SolaimanLipi/raw/master/SolaimanLipi.ttf
    if os.path.exists('SolaimanLipi.ttf'):
        pdfmetrics.registerFont(TTFont('SolaimanLipi', 'SolaimanLipi.ttf'))
        FONT_NAME = 'SolaimanLipi'
        print("Bengali font loaded successfully.", file=sys.stderr)
    else:
        print("Warning: SolaimanLipi.ttf not found. Using default font.", file=sys.stderr)
except Exception as e:
    print(f"Font loading error: {e}", file=sys.stderr)

class IDCardGenerator:
    def __init__(self):
        self.output_dir = "generated_cards"
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
            print(f"Created directory: {self.output_dir}", file=sys.stderr)
    
    def get_employee_data(self, employee_ids):
        """Get employee data - using sample data for testing"""
        # Sample data matching the format you provided
        sample_data = {
            'MAA-0403': {
                'id': 'MAA-0403',
                'name': 'ফরহাদ হোসেন',
                'designation': 'Junior Operator',
                'job_type': 'অস্থায়ী',
                'department': 'সুইং',
                'joining_date': '18-07-2026',
                'issue_date': '18-07-2026',
                'address': 'গ্রামঃ বক্তারপুর, পোষ্টঃ গোয়ালবাথান, উপজেলাঃ কালিয়াকৈর, জেলাঃ গাজীপুর',
                'mobile': '01316459944',
                'nid': '3715684282',
                'blood_group': 'A+',
                'company_address': 'বক্তারপুর, কালিয়াকৈর, গাজীপুর',
                'company_mobile': '০১৭১১-১৭৪৩১৮',
                'company_email': 'maaenterprise711@gmail.com'
            },
            'MAA-0404': {
                'id': 'MAA-0404',
                'name': 'মোঃ রফিকুল ইসলাম',
                'designation': 'Senior Operator',
                'job_type': 'স্থায়ী',
                'department': 'সুইং',
                'joining_date': '15-06-2025',
                'issue_date': '15-06-2025',
                'address': 'গ্রামঃ দত্তপাড়া, পোষ্টঃ কালিয়াকৈর, উপজেলাঃ কালিয়াকৈর, জেলাঃ গাজীপুর',
                'mobile': '01712345678',
                'nid': '1234567890',
                'blood_group': 'B+',
                'company_address': 'বক্তারপুর, কালিয়াকৈর, গাজীপুর',
                'company_mobile': '০১৭১১-১৭৪৩১৮',
                'company_email': 'maaenterprise711@gmail.com'
            },
            'MAA-0405': {
                'id': 'MAA-0405',
                'name': 'মোঃ জাকির হোসেন',
                'designation': 'Machine Operator',
                'job_type': 'অস্থায়ী',
                'department': 'সুইং',
                'joining_date': '20-08-2026',
                'issue_date': '20-08-2026',
                'address': 'গ্রামঃ বোয়ালী, পোষ্টঃ কালিয়াকৈর, উপজেলাঃ কালিয়াকৈর, জেলাঃ গাজীপুর',
                'mobile': '01812345678',
                'nid': '8765432109',
                'blood_group': 'O+',
                'company_address': 'বক্তারপুর, কালিয়াকৈর, গাজীপুর',
                'company_mobile': '০১৭১১-১৭৪৩১৮',
                'company_email': 'maaenterprise711@gmail.com'
            }
        }
        
        employees = []
        for emp_id in employee_ids:
            if emp_id in sample_data:
                employees.append(sample_data[emp_id])
            else:
                print(f"Warning: No data found for ID: {emp_id}", file=sys.stderr)
                # Create a default entry
                employees.append({
                    'id': emp_id,
                    'name': 'Unknown Employee',
                    'designation': 'N/A',
                    'job_type': 'N/A',
                    'department': 'N/A',
                    'joining_date': 'N/A',
                    'issue_date': 'N/A',
                    'address': 'N/A',
                    'mobile': 'N/A',
                    'nid': 'N/A',
                    'blood_group': 'N/A',
                    'company_address': 'বক্তারপুর, কালিয়াকৈর, গাজীপুর',
                    'company_mobile': '০১৭১১-১৭৪৩১৮',
                    'company_email': 'maaenterprise711@gmail.com'
                })
        
        return employees
    
    def wrap_text(self, text, max_chars=55):
        """Wrap text for display"""
        if not text or text == 'N/A':
            return [text]
        
        # Split by spaces
        words = text.split()
        lines = []
        current_line = []
        current_length = 0
        
        for word in words:
            word_len = len(word)
            if current_length + word_len + 1 <= max_chars:
                current_line.append(word)
                current_length += word_len + 1
            else:
                if current_line:
                    lines.append(' '.join(current_line))
                current_line = [word]
                current_length = word_len
        
        if current_line:
            lines.append(' '.join(current_line))
        
        return lines if lines else [text]
    
    def generate_single_card(self, data):
        """Generate a single ID card PDF"""
        try:
            emp_id = data.get('id', 'unknown')
            filename = f"{emp_id}.pdf"
            filepath = os.path.join(self.output_dir, filename)
            
            # Create PDF with landscape A4
            c = canvas.Canvas(filepath, pagesize=landscape(A4))
            page_width, page_height = landscape(A4)
            
            # Card dimensions (standard ID card size: 85.6mm x 54mm)
            card_width = 85.6 * mm
            card_height = 54 * mm
            
            # Center card on page
            x = (page_width - card_width) / 2
            y = (page_height - card_height) / 2
            
            # Draw the card
            self.draw_card(c, x, y, card_width, card_height, data)
            
            c.save()
            print(f"Generated: {filename}", file=sys.stderr)
            return filepath
        except Exception as e:
            print(f"Error generating card: {e}", file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            return None
    
    def draw_card(self, c, x, y, card_width, card_height, data):
        """Draw the complete ID card"""
        try:
            # === BACKGROUND ===
            c.setFillColor(colors.white)
            c.rect(x, y, card_width, card_height, fill=1, stroke=0)
            
            # === BORDER ===
            c.setStrokeColor(colors.black)
            c.setLineWidth(0.5)
            c.rect(x, y, card_width, card_height, fill=0, stroke=1)
            
            # === HEADER ===
            header_height = 9 * mm
            c.setFillColor(colors.Color(0.15, 0.35, 0.55))  # Blue
            c.rect(x, y + card_height - header_height, card_width, header_height, fill=1, stroke=0)
            
            # Company name in header
            c.setFillColor(colors.white)
            c.setFont(FONT_NAME, 11)
            c.drawCentredString(x + card_width/2, y + card_height - 6*mm, "মা এন্টারপ্রাইজ")
            
            # === CONTENT ===
            margin_left = 2.5 * mm
            margin_top = 12 * mm
            current_y = y + card_height - margin_top
            c.setFillColor(colors.black)
            c.setFont(FONT_NAME, 6.5)
            
            # ID Number
            c.drawString(x + margin_left, current_y, f"আইডি নংঃ {data.get('id', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Name
            c.drawString(x + margin_left, current_y, f"নামঃ {data.get('name', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Designation
            c.drawString(x + margin_left, current_y, f"পদবিঃ {data.get('designation', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Job Type
            c.drawString(x + margin_left, current_y, f"কাজের ধরনঃ {data.get('job_type', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Department
            c.drawString(x + margin_left, current_y, f"বিভাগঃ {data.get('department', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Joining Date
            c.drawString(x + margin_left, current_y, f"যোগদানঃ {data.get('joining_date', 'N/A')}")
            current_y -= 3.8 * mm
            
            # Issue Date
            c.drawString(x + margin_left, current_y, f"ইস্যুঃ {data.get('issue_date', 'N/A')}")
            current_y -= 4 * mm
            
            # === SEPARATOR LINE ===
            c.setStrokeColor(colors.gray)
            c.setLineWidth(0.3)
            c.line(x + margin_left, current_y, x + card_width - margin_left, current_y)
            current_y -= 2.5 * mm
            
            # === TWO COLUMN SECTION ===
            left_col = x + margin_left
            right_col = x + card_width / 2 + 1 * mm
            
            # Column headers
            c.setFont(FONT_NAME, 5.5)
            c.drawString(left_col, current_y, "কার্ডধারী")
            c.drawString(right_col, current_y, "মালিক/ব্যবস্থাপক")
            current_y -= 2.5 * mm
            
            # Personal Information Header
            c.setFont(FONT_NAME, 5)
            c.drawString(left_col, current_y, "ক. কর্মীর ব্যক্তিগত তথ্য :")
            current_y -= 2.5 * mm
            
            # Address (wrap text)
            c.setFont(FONT_NAME, 4.5)
            address_lines = self.wrap_text(data.get('address', 'N/A'), 32)
            for line in address_lines:
                c.drawString(left_col + 0.5, current_y, line)
                current_y -= 2.2 * mm
            
            # Mobile
            c.drawString(left_col + 0.5, current_y, f"মোবাইল নম্বর : {data.get('mobile', 'N/A')}")
            current_y -= 2.2 * mm
            
            # NID
            c.drawString(left_col + 0.5, current_y, f"এনআইডি/বিআর : {data.get('nid', 'N/A')}")
            current_y -= 2.2 * mm
            
            # Blood Group
            blood_group = data.get('blood_group', '')
            c.drawString(left_col + 0.5, current_y, f"রক্তের গ্রুপ : {blood_group}")
            current_y -= 2.5 * mm
            
            # Company Information
            c.setFont(FONT_NAME, 5)
            c.drawString(right_col, current_y, "খ. প্রতিষ্ঠানের তথ্য :")
            current_y -= 2.5 * mm
            
            # Company Address
            c.setFont(FONT_NAME, 4.5)
            company_address_lines = self.wrap_text(data.get('company_address', 'N/A'), 32)
            for line in company_address_lines:
                c.drawString(right_col + 0.5, current_y, line)
                current_y -= 2.2 * mm
            
            # Company Mobile
            c.drawString(right_col + 0.5, current_y, f"মোবাইল : {data.get('company_mobile', 'N/A')}")
            current_y -= 2.2 * mm
            
            # Company Email
            c.drawString(right_col + 0.5, current_y, f"ই-মেইল : {data.get('company_email', 'N/A')}")
            current_y -= 2.5 * mm
            
            # === TERMS AND CONDITIONS ===
            current_y = y + 2.5 * mm
            c.setFont(FONT_NAME, 3.2)
            c.setFillColor(colors.Color(0.3, 0.3, 0.3))
            
            terms = "গ. শর্তাবলী: এই কার্ডের মেয়াদ প্রতিষ্ঠানের সাথে কর্মরত অবস্থায় থাকা পর্যন্ত। যে কোনভাবে চাকুরীর অবসানের সাথে সাথে এই কার্ডের মেয়াদ উত্তীর্ন বলে গন্য হবে এবং চাকুরী ত্যাগকালে এই কার্ড অবশ্যই কর্তৃপক্ষের নিকট ফেরত দিতে হবে। এই কার্ড অন্য কাউকে হস্তান্তর যোগ্য নয় এবং চাহিবা মাত্র নিরাপত্তা বিভাগকে দেখাতে বাধ্য থাকবেন। হারিয়ে গেলে বা নষ্ট করলে তৎক্ষনাত কর্তৃপক্ষকে অবহিত করতে হবে। এই কার্ডের অবৈধ ব্যবহার অসদাচরণ এবং আইনত অপরাধ হিসেবে গন্য।"
            
            terms_lines = self.wrap_text(terms, 65)
            for line in terms_lines:
                c.drawString(x + margin_left, current_y, line)
                current_y -= 1.8 * mm
            
            current_y -= 0.5 * mm
            request = "ঘ. অনুরোধ: সংশ্লিষ্ট কর্মী ছাড়া অন্য কোন ব্যক্তি এই কার্ড পেয়ে থাকলে প্রতিষ্ঠানের ঠিকানায় জমা প্রদানের জন্য অনুরোধ করা হলো।"
            request_lines = self.wrap_text(request, 65)
            for line in request_lines:
                c.drawString(x + margin_left, current_y, line)
                current_y -= 1.8 * mm
                
        except Exception as e:
            print(f"Error in draw_card: {e}", file=sys.stderr)
            raise
    
    def generate_cards(self, employee_ids):
        """Generate ID cards for multiple employees"""
        try:
            print(f"Generating cards for: {employee_ids}", file=sys.stderr)
            
            # Get employee data
            employees = self.get_employee_data(employee_ids)
            
            if not employees:
                print("No employee data found", file=sys.stderr)
                return None
            
            print(f"Found {len(employees)} employees", file=sys.stderr)
            
            # Generate individual cards
            generated_files = []
            for employee in employees:
                filepath = self.generate_single_card(employee)
                if filepath and os.path.exists(filepath):
                    generated_files.append(filepath)
            
            if not generated_files:
                print("No cards generated", file=sys.stderr)
                return None
            
            # Create ZIP file
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            zip_filename = f"id_cards_{timestamp}.zip"
            zip_path = os.path.join(self.output_dir, zip_filename)
            
            print(f"Creating ZIP: {zip_path}", file=sys.stderr)
            
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for filepath in generated_files:
                    zipf.write(filepath, os.path.basename(filepath))
            
            # Return just the filename
            return zip_filename
            
        except Exception as e:
            print(f"Error in generate_cards: {e}", file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            return None

# Main execution
if __name__ == "__main__":
    try:
        print("Starting ID Card Generator...", file=sys.stderr)
        
        if len(sys.argv) < 2:
            print("ERROR: No IDs provided", file=sys.stderr)
            print("Usage: python generate_id_card.py 'ID1,ID2,ID3'", file=sys.stderr)
            sys.exit(1)
        
        ids_param = sys.argv[1]
        print(f"Processing IDs: {ids_param}", file=sys.stderr)
        
        employee_ids = [id.strip() for id in ids_param.split(',') if id.strip()]
        
        if not employee_ids:
            print("ERROR: No valid IDs provided", file=sys.stderr)
            sys.exit(1)
        
        generator = IDCardGenerator()
        result = generator.generate_cards(employee_ids)
        
        if result:
            print(result)  # This is captured by PHP
            sys.exit(0)
        else:
            print("ERROR: Failed to generate cards", file=sys.stderr)
            sys.exit(1)
            
    except Exception as e:
        print(f"ERROR: {e}", file=sys.stderr)
        traceback.print_exc(file=sys.stderr)
        sys.exit(1)