<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class CompanySettingsController extends Controller
{
    /**
     * Show the company settings page.
     */
    public function index()
    {
        $companyId = session('CompanyID');
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }

        $company = DB::table('company')->where('CompanyID', $companyId)->first();
        
        if (!$company) {
            return redirect()->back()->with('error', 'Company not found.');
        }

        // Debug: Log the company data
        Log::info('Company settings loaded', [
            'company_id' => $companyId,
            'company_data' => $company,
            'email_template' => $company->email_message_template ?? 'NULL',
            'sms_template' => $company->sms_message_template ?? 'NULL',
            'subject_template' => $company->email_subject_template ?? 'NULL'
        ]);

        // Set default templates if not already set
        $defaultEmailTemplate = "Dear {customer_name},

Please find attached your bill #{bill_id} for {billing_period}.

Account Number: {account_number}

Total Amount: {total_amount}

If you have any questions, please don't hesitate to contact us.

Thank you for your business.

Best regards,
{company_name}";

        $defaultSmsTemplate = "Dear {customer_name}, Your bill #{bill_id} for {billing_period} is ready. Amount: {total_amount}. Account: {account_number}. Thank you for your business. {company_name}";

        $defaultSubjectTemplate = "Bill #{bill_id} - {billing_period} - {company_name}";

        return view('company.settings', compact('company', 'defaultEmailTemplate', 'defaultSmsTemplate', 'defaultSubjectTemplate'));
    }

    /**
     * Get company templates as JSON for AJAX requests.
     */
    public function getTemplates(Request $request)
    {
        $companyId = session('CompanyID');
        
        if (!$companyId) {
            return response()->json(['error' => 'No company associated with this account.'], 400);
        }

        try {
            $company = DB::table('company')->where('CompanyID', $companyId)->first();
            
            if (!$company) {
                return response()->json(['error' => 'Company not found.'], 404);
            }

            // Prepare sample variables for template preview
            $sampleVariables = [
                'customer_name' => 'Sample Customer',
                'bill_id' => 'SAMPLE001',
                'billing_period' => '202505',
                'account_number' => 'CUST-12345',
                'total_amount' => 'KES 50,000.00',
                'company_name' => $company->CompanyName ?? config('app.name')
            ];

            // Get templates with variables replaced
            $emailSubject = $this->getSubjectTemplate($companyId, $sampleVariables);
            $emailMessage = $this->getEmailTemplate($companyId, $sampleVariables);
            $smsMessage = $this->getSmsTemplate($companyId, $sampleVariables);

            return response()->json([
                'email_subject' => $emailSubject,
                'email_message' => $emailMessage,
                'sms_message' => $smsMessage,
                'has_custom_templates' => [
                    'email_subject' => !empty($company->email_subject_template),
                    'email_message' => !empty($company->email_message_template),
                    'sms_message' => !empty($company->sms_message_template)
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('Failed to fetch company templates', [
                'company_id' => $companyId,
                'error' => $e->getMessage()
            ]);

            return response()->json(['error' => 'Failed to fetch templates: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Update the company message templates.
     */
    public function update(Request $request)
    {
        $request->validate([
            'email_message_template' => 'nullable|string',
            'sms_message_template' => 'nullable|string',
            'email_subject_template' => 'nullable|string|max:255',
        ]);

        $companyId = session('CompanyID');
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }

        try {
            $updateData = [
                'email_message_template' => $request->email_message_template,
                'sms_message_template' => $request->sms_message_template,
                'email_subject_template' => $request->email_subject_template,
            ];

            // Only add UpdatedAt if it exists
            if (Schema::hasColumn('company', 'UpdatedAt')) {
                $updateData['UpdatedAt'] = now();
            }

            DB::table('company')
                ->where('CompanyID', $companyId)
                ->update($updateData);

            Log::info('Company message templates updated', [
                'company_id' => $companyId,
                'email_template' => $request->email_message_template ? 'Updated' : 'Not changed',
                'sms_template' => $request->sms_message_template ? 'Updated' : 'Not changed',
                'subject_template' => $request->email_subject_template ? 'Updated' : 'Not changed',
            ]);

            return redirect()->back()->with('success', 'Message templates updated successfully.');

        } catch (\Exception $e) {
            Log::error('Failed to update company message templates', [
                'company_id' => $companyId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return redirect()->back()->with('error', 'Failed to update message templates: ' . $e->getMessage())->withInput();
        }
    }

    /**
     * Get the company's email template with variables replaced.
     */
    public static function getEmailTemplate($companyId, $variables = [])
    {
        $company = DB::table('company')->where('CompanyID', $companyId)->first();
        
        if (!$company || !$company->email_message_template) {
            // Use default template
            $template = "Dear {customer_name},

Please find attached your bill #{bill_id} for {billing_period}.

Account Number: {account_number}

Total Amount: {total_amount}

If you have any questions, please don't hesitate to contact us.

Thank you for your business.

Best regards,
{company_name}";
            Log::info('Using default email template', ['company_id' => $companyId, 'variables' => $variables]);
        } else {
            $template = $company->email_message_template;
            Log::info('Using company email template', ['company_id' => $companyId, 'template' => $template, 'variables' => $variables]);
        }

        // Replace variables
        foreach ($variables as $key => $value) {
            $oldValue = $template;
            $template = str_replace('{' . $key . '}', $value, $template);
            if ($oldValue !== $template) {
                Log::info("Replaced variable: {$key} = {$value}");
            }
        }

        Log::info('Final email template', ['template' => $template]);
        return $template;
    }

    /**
     * Get the company's SMS template with variables replaced.
     */
    public static function getSmsTemplate($companyId, $variables = [])
    {
        $company = DB::table('company')->where('CompanyID', $companyId)->first();
        
        if (!$company || !$company->sms_message_template) {
            // Use default template
            $template = "Dear {customer_name}, Your bill #{bill_id} for {billing_period} is ready. Amount: {total_amount}. Account: {account_number}. Thank you for your business. {company_name}";
        } else {
            $template = $company->sms_message_template;
        }

        // Replace variables
        foreach ($variables as $key => $value) {
            $template = str_replace('{' . $key . '}', $value, $template);
        }

        return $template;
    }

    /**
     * Get the company's subject template with variables replaced.
     */
    public static function getSubjectTemplate($companyId, $variables = [])
    {
        $company = DB::table('company')->where('CompanyID', $companyId)->first();
        
        if (!$company || !$company->email_subject_template) {
            // Use default template
            $template = "Bill #{bill_id} - {billing_period} - {company_name}";
            Log::info('Using default subject template', ['company_id' => $companyId, 'variables' => $variables]);
        } else {
            $template = $company->email_subject_template;
            Log::info('Using company subject template', ['company_id' => $companyId, 'template' => $template, 'variables' => $variables]);
        }

        // Replace variables
        foreach ($variables as $key => $value) {
            $oldValue = $template;
            $template = str_replace('{' . $key . '}', $value, $template);
            if ($oldValue !== $template) {
                Log::info("Replaced subject variable: {$key} = {$value}");
            }
        }

        Log::info('Final subject template', ['template' => $template]);
        return $template;
    }

    /**
     * Update the company information.
     */
    public function updateInfo(Request $request)
    {
        $request->validate([
            'CompanyName' => 'required|string|max:255',
            'ContactPerson' => 'nullable|string|max:255',
            'Email' => 'nullable|email|max:255',
            'TelNo' => 'nullable|string|max:50',
            'Address1' => 'nullable|string|max:255',
            'Address2' => 'nullable|string|max:255',
            'ChequePayableTo' => 'nullable|string|max:255',
            'CompanyLogo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048', // 2MB max
        ]);

        $companyId = session('CompanyID');

        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }

        try {
            // Get current company data to check for existing logo
            $currentCompany = DB::table('company')->where('CompanyID', $companyId)->first();

            $updateData = [
                'CompanyName' => $request->CompanyName,
                'ContactPerson' => $request->ContactPerson,
                'Email' => $request->Email,
                'TelNo' => $request->TelNo,
                'Address1' => $request->Address1,
                'Address2' => $request->Address2,
                'ChequePayableTo' => $request->ChequePayableTo,
                'LastUpdatedBy' => auth()->id(),
                'LastUpdatedOn' => now(),
            ];

            // Handle logo upload
            if ($request->hasFile('CompanyLogo')) {
                $logoFile = $request->file('CompanyLogo');
                
                // Delete existing logo file if it exists
                if ($currentCompany && $currentCompany->CompanyLogo && file_exists(public_path('logo/' . $currentCompany->CompanyLogo))) {
                    unlink(public_path('logo/' . $currentCompany->CompanyLogo));
                    Log::info('Existing company logo deleted', [
                        'company_id' => $companyId,
                        'old_filename' => $currentCompany->CompanyLogo
                    ]);
                }
                
                // Use consistent filename for logo (company-specific)
                $extension = $logoFile->getClientOriginalExtension();
                $filename = 'company_' . $companyId . '_logo.' . $extension;
                
                // Store the file in public/logo directory
                $logoFile->move(public_path('logo'), $filename);
                
                $updateData['CompanyLogo'] = $filename;
                
                Log::info('Company logo uploaded', [
                    'company_id' => $companyId,
                    'filename' => $filename,
                    'original_name' => $logoFile->getClientOriginalName()
                ]);
            }

            DB::table('company')
                ->where('CompanyID', $companyId)
                ->update($updateData);

            Log::info('Company information updated', [
                'company_id' => $companyId,
                'updated_by' => auth()->id(),
                'fields_updated' => array_keys($updateData),
                'logo_uploaded' => $request->hasFile('CompanyLogo')
            ]);

            return redirect()->back()->with('success', 'Company information updated successfully.');

        } catch (\Exception $e) {
            Log::error('Failed to update company information', [
                'company_id' => $companyId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);

            return redirect()->back()->with('error', 'Failed to update company information: ' . $e->getMessage())->withInput();
        }
    }
}
