#!/bin/bash
# Haven Grazuri Accounting System - cPanel Deployment Script
# This script deploys the accounting system to a production cPanel environment

echo "🚀 Deploying Accounting System to Production..."

# Step 1: Run migrations
echo "📦 Running database migrations..."
python manage.py makemigrations accounting
python manage.py migrate accounting
python manage.py migrate

# Step 2: Create Chart of Accounts
echo "💼 Setting up Chart of Accounts..."
python -c "
import os
import django
from decimal import Decimal
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()
from accounting.models import Account
from users.models import CustomUser

system_user = CustomUser.objects.filter(role='admin').first()

# Define microfinance Chart of Accounts
accounts_data = [
    # ASSETS (202xxx)
    {'code': '202001', 'name': 'Loan Portfolio - Principal', 'account_type': 'asset', 'subtype': 'loan_portfolio', 
     'description': 'Outstanding principal balance of all active loans', 'is_system_account': True},
    {'code': '202002', 'name': 'Accrued Interest Receivable', 'account_type': 'asset', 'subtype': 'current_asset',
     'description': 'Interest earned but not yet collected', 'is_system_account': True},
    {'code': '202003', 'name': 'Cash on Hand', 'account_type': 'asset', 'subtype': 'current_asset',
     'description': 'Physical cash in branches', 'is_system_account': True},
    {'code': '202004', 'name': 'Bank Account - Main', 'account_type': 'asset', 'subtype': 'current_asset',
     'description': 'Main operating bank account', 'is_system_account': True},
    {'code': '202005', 'name': 'M-Pesa Account', 'account_type': 'asset', 'subtype': 'current_asset',
     'description': 'M-Pesa business account balance', 'is_system_account': True},
    {'code': '202006', 'name': 'Allowance for Loan Losses', 'account_type': 'asset', 'subtype': 'loan_portfolio',
     'description': 'Reserve for expected loan defaults (contra-asset)', 'is_system_account': True},
    
    # LIABILITIES (302xxx)
    {'code': '302001', 'name': 'Client Savings Deposits', 'account_type': 'liability', 'subtype': 'client_savings',
     'description': 'Savings deposits from microfinance clients', 'is_system_account': True},
    {'code': '302002', 'name': 'Loan Payable - Bank', 'account_type': 'liability', 'subtype': 'borrowings',
     'description': 'Loans borrowed from financial institutions', 'is_system_account': False},
    {'code': '302003', 'name': 'Accrued Expenses Payable', 'account_type': 'liability', 'subtype': 'current_liability',
     'description': 'Expenses incurred but not yet paid', 'is_system_account': True},
    
    # EQUITY (320xxx)
    {'code': '320001', 'name': 'Share Capital', 'account_type': 'equity', 'subtype': None,
     'description': 'Owner investment in the institution', 'is_system_account': True},
    {'code': '320002', 'name': 'Retained Earnings', 'account_type': 'equity', 'subtype': None,
     'description': 'Accumulated profits retained in the business', 'is_system_account': True},
    {'code': '320003', 'name': 'Current Year Earnings', 'account_type': 'equity', 'subtype': None,
     'description': 'Net income for the current fiscal year', 'is_system_account': True},
    
    # INCOME (401xxx)
    {'code': '401001', 'name': 'Interest Income - Loans', 'account_type': 'income', 'subtype': 'interest_income',
     'description': 'Interest earned from loan products', 'is_system_account': True},
    {'code': '401002', 'name': 'Fee Income - Processing Fees', 'account_type': 'income', 'subtype': 'fee_income',
     'description': 'Loan processing and application fees', 'is_system_account': True},
    {'code': '401003', 'name': 'Fee Income - Late Payment Penalties', 'account_type': 'income', 'subtype': 'fee_income',
     'description': 'Penalties charged on late loan payments', 'is_system_account': True},
    
    # EXPENSES (501xxx)
    {'code': '501001', 'name': 'Salaries and Wages', 'account_type': 'expense', 'subtype': 'staff_costs',
     'description': 'Employee salaries and wages', 'is_system_account': True},
    {'code': '501002', 'name': 'Rent Expense', 'account_type': 'expense', 'subtype': 'operating_expense',
     'description': 'Office and branch rent payments', 'is_system_account': False},
    {'code': '501003', 'name': 'Utilities Expense', 'account_type': 'expense', 'subtype': 'operating_expense',
     'description': 'Electricity, water, and internet expenses', 'is_system_account': False},
    {'code': '501007', 'name': 'Loan Loss Provision Expense', 'account_type': 'expense', 'subtype': 'loan_loss_provision',
     'description': 'Expense for expected loan defaults', 'is_system_account': True},
]

created = 0
for account_data in accounts_data:
    acc, is_new = Account.objects.get_or_create(
        code=account_data['code'],
        defaults={
            'name': account_data['name'],
            'account_type': account_data['account_type'],
            'subtype': account_data['subtype'],
            'description': account_data['description'],
            'is_system_account': account_data['is_system_account'],
            'is_active': True,
            'created_by': system_user
        }
    )
    if is_new:
        created += 1
        print(f'Created: {acc.code} - {acc.name}')

print(f'Chart of Accounts: {created} new accounts created')
"

# Step 3: Create Fiscal Periods
echo "📅 Creating fiscal periods..."
python -c "
import os
import django
from datetime import datetime, timedelta
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()
from accounting.models import FiscalPeriod

year = datetime.now().year
created = 0

# Create monthly periods
for month in range(1, 13):
    start = datetime(year, month, 1).date()
    if month == 12:
        end = datetime(year, 12, 31).date()
    else:
        end = (datetime(year, month + 1, 1) - timedelta(days=1)).date()
    
    period, is_new = FiscalPeriod.objects.get_or_create(
        start_date=start,
        end_date=end,
        defaults={
            'name': start.strftime('%B %Y'),
            'period_type': 'monthly',
            'status': 'open'
        }
    )
    if is_new:
        created += 1

# Create annual period
period, is_new = FiscalPeriod.objects.get_or_create(
    name=f'FY {year}',
    period_type='annual',
    defaults={
        'start_date': datetime(year, 1, 1).date(),
        'end_date': datetime(year, 12, 31).date(),
        'status': 'open'
    }
)
if is_new:
    created += 1

print(f'Fiscal Periods: {created} new periods created')
"

# Step 4: Collect static files
echo "📁 Collecting static files..."
python manage.py collectstatic --noinput

# Step 5: Run system checks
echo "🔍 Running system checks..."
python manage.py check

echo "✅ Accounting System Deployment Complete!"
echo ""
echo "Next steps:"
echo "1. Access accounting dashboard: /accounting/dashboard/"
echo "2. Review Chart of Accounts: /accounting/accounts/"
echo "3. Setup user permissions for accounting module"
echo "4. Test loan transaction integration"
echo ""
