<?php
require_once('class.php');
require_once('connect.php');

// Set JSON header
header('Content-Type: application/json');

// Initialize response
$response = array(
    'success' => false,
    'message' => '',
    'application_number' => ''
);

try {
    // Check request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    // Validate required fields
    $requiredFields = [
        'full_name',
        'sacco_account_no',
        'phone_no',
        'email',
        'occupation',
        'loan_type_id',
        'loan_amount_applied',
        'repayment_period_months',
        'applied_date'
    ];

    foreach ($requiredFields as $field) {
        if (!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
            throw new Exception('Missing required field: ' . $field);
        }
    }

    // Sanitize inputs
    $fullName = trim($_POST['full_name']);
    $saccoAccountNo = trim($_POST['sacco_account_no']);
    $employmentNo = isset($_POST['employment_no']) ? trim($_POST['employment_no']) : '';
    $employerName = isset($_POST['employer_name']) ? trim($_POST['employer_name']) : '';
    $employerAddress = isset($_POST['employer_address']) ? trim($_POST['employer_address']) : '';
    $placeOfResident = isset($_POST['place_of_resident']) ? trim($_POST['place_of_resident']) : '';
    $phoneNo = trim($_POST['phone_no']);
    $email = trim($_POST['email']);
    $occupation = trim($_POST['occupation']);
    $basicSalary = isset($_POST['basic_salary']) && !empty($_POST['basic_salary']) ? floatval($_POST['basic_salary']) : NULL;
    $nextOfKin = isset($_POST['next_of_kin']) ? trim($_POST['next_of_kin']) : '';
    $nextOfKinPhone = isset($_POST['next_of_kin_phone']) ? trim($_POST['next_of_kin_phone']) : '';
    $relation = isset($_POST['relation']) ? trim($_POST['relation']) : '';
    $physicalAddress = isset($_POST['physical_address']) ? trim($_POST['physical_address']) : '';
    
    // Bank Details
    $bankName = isset($_POST['bank_name']) ? trim($_POST['bank_name']) : '';
    $bankAccountNo = isset($_POST['bank_account_no']) ? trim($_POST['bank_account_no']) : '';
    $accountName = isset($_POST['account_name']) ? trim($_POST['account_name']) : '';
    $branchName = isset($_POST['branch_name']) ? trim($_POST['branch_name']) : '';
    
    // Loan Information
    $loanTypeId = intval($_POST['loan_type_id']);
    $loanAmountApplied = floatval($_POST['loan_amount_applied']);
    $totalInterest = isset($_POST['total_interest']) && !empty($_POST['total_interest']) ? floatval($_POST['total_interest']) : NULL;
    $totalRepaymentAmount = isset($_POST['total_repayment_amount']) && !empty($_POST['total_repayment_amount']) ? floatval($_POST['total_repayment_amount']) : NULL;
    $repaymentPeriodMonths = intval($_POST['repayment_period_months']);
    $monthlyRepaymentAmount = isset($_POST['monthly_repayment_amount']) && !empty($_POST['monthly_repayment_amount']) ? floatval($_POST['monthly_repayment_amount']) : NULL;
    $appliedDate = trim($_POST['applied_date']);
    
    // Guarantor Information
    $guarantorFullName = isset($_POST['guarantor_full_name']) ? trim($_POST['guarantor_full_name']) : '';
    $guarantorEmployerName = isset($_POST['guarantor_employer_name']) ? trim($_POST['guarantor_employer_name']) : '';
    $guarantorPostalAddress = isset($_POST['guarantor_postal_address']) ? trim($_POST['guarantor_postal_address']) : '';
    $guarantorPhysicalAddress = isset($_POST['guarantor_physical_address']) ? trim($_POST['guarantor_physical_address']) : '';
    $guarantorPhoneNo = isset($_POST['guarantor_phone_no']) ? trim($_POST['guarantor_phone_no']) : '';
    $guarantorIdNo = isset($_POST['guarantor_id_no']) ? trim($_POST['guarantor_id_no']) : '';
    
    // Declaration & Signatures
    $applicantSignatureDate = isset($_POST['applicant_signature_date']) ? trim($_POST['applicant_signature_date']) : NULL;
    $witnessName = isset($_POST['witness_name']) ? trim($_POST['witness_name']) : '';
    $witnessSignatureDate = isset($_POST['witness_signature_date']) ? trim($_POST['witness_signature_date']) : NULL;
    $hrManagerName = isset($_POST['hr_finance_manager_name']) ? trim($_POST['hr_finance_manager_name']) : '';
    $hrManagerDate = isset($_POST['hr_finance_manager_date']) ? trim($_POST['hr_finance_manager_date']) : NULL;
    $loanRecommendation = isset($_POST['loan_recommendation']) ? trim($_POST['loan_recommendation']) : '';

    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Invalid email address');
    }

    // Validate loan amount
    if ($loanAmountApplied < 1000) {
        throw new Exception('Loan amount must be at least MWK 1,000');
    }

    // Validate repayment period
    if ($repaymentPeriodMonths < 1 || $repaymentPeriodMonths > 60) {
        throw new Exception('Repayment period must be between 1 and 60 months');
    }

    // Process file uploads
    $applicantSignatureFile = '';
    $witnessSignatureFile = '';
    $hrManagerSignatureFile = '';

    // Upload handler function
    function handleFileUpload($fileKey, $uploadType) {
        if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../../assets/uploads/loan_applications/';
            
            // Create directory if it doesn't exist
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $fileName = $_FILES[$fileKey]['name'];
            $fileSize = $_FILES[$fileKey]['size'];
            $fileTmpName = $_FILES[$fileKey]['tmp_name'];
            $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
            
            // Validate file
            $allowedExt = array('jpg', 'jpeg', 'png', 'pdf');
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if (!in_array(strtolower($fileExt), $allowedExt)) {
                throw new Exception('Invalid file type for ' . $fileKey . '. Allowed: JPG, PNG, PDF');
            }

            if ($fileSize > $maxFileSize) {
                throw new Exception('File size for ' . $fileKey . ' exceeds 5MB limit');
            }

            // Generate unique filename
            $newFileName = $uploadType . '_' . time() . '_' . uniqid() . '.' . $fileExt;
            $uploadPath = $uploadDir . $newFileName;

            // Move uploaded file
            if (!move_uploaded_file($fileTmpName, $uploadPath)) {
                throw new Exception('Failed to upload ' . $fileKey);
            }

            return 'assets/uploads/loan_applications/' . $newFileName;
        }
        return '';
    }

    // Handle file uploads
    if (isset($_FILES['applicant_signature_file'])) {
        $applicantSignatureFile = handleFileUpload('applicant_signature_file', 'applicant_signature');
    }

    if (isset($_FILES['witness_signature_file']) && $_FILES['witness_signature_file']['error'] !== UPLOAD_ERR_NO_FILE) {
        $witnessSignatureFile = handleFileUpload('witness_signature_file', 'witness_signature');
    }

    if (isset($_FILES['hr_finance_manager_signature_file']) && $_FILES['hr_finance_manager_signature_file']['error'] !== UPLOAD_ERR_NO_FILE) {
        $hrManagerSignatureFile = handleFileUpload('hr_finance_manager_signature_file', 'hr_manager_signature');
    }

    // Handle assets description
    $assetsDescription = '';
    if (isset($_POST['asset_name']) && is_array($_POST['asset_name'])) {
        $assets = array();
        for ($i = 0; $i < count($_POST['asset_name']); $i++) {
            if (!empty($_POST['asset_name'][$i]) || !empty($_POST['asset_value'][$i])) {
                $assets[] = array(
                    'name' => trim($_POST['asset_name'][$i]),
                    'value' => floatval($_POST['asset_value'][$i])
                );
            }
        }
        if (!empty($assets)) {
            $assetsDescription = json_encode($assets);
        }
    }

    // Database connection
    $con = new DB();

    // Generate unique application number
    $applicationNumber = 'APP-' . date('Ymd') . '-' . strtoupper(uniqid());

    // Prepare data for insertion
    $data = array(
        'application_number' => $applicationNumber,
        'full_name' => $fullName,
        'sacco_account_no' => $saccoAccountNo,
        'employment_no' => $employmentNo,
        'employer_name' => $employerName,
        'employer_address' => $employerAddress,
        'place_of_resident' => $placeOfResident,
        'phone_no' => $phoneNo,
        'email' => $email,
        'occupation' => $occupation,
        'basic_salary' => $basicSalary,
        'next_of_kin' => $nextOfKin,
        'next_of_kin_phone' => $nextOfKinPhone,
        'relation' => $relation,
        'physical_address' => $physicalAddress,
        'bank_name' => $bankName,
        'bank_account_no' => $bankAccountNo,
        'account_name' => $accountName,
        'branch_name' => $branchName,
        'loan_type_id' => $loanTypeId,
        'loan_amount_applied' => $loanAmountApplied,
        'total_interest' => $totalInterest,
        'total_repayment_amount' => $totalRepaymentAmount,
        'repayment_period_months' => $repaymentPeriodMonths,
        'monthly_repayment_amount' => $monthlyRepaymentAmount,
        'applied_date' => $appliedDate,
        'assets_description' => $assetsDescription,
        'guarantor_full_name' => $guarantorFullName,
        'guarantor_employer_name' => $guarantorEmployerName,
        'guarantor_postal_address' => $guarantorPostalAddress,
        'guarantor_physical_address' => $guarantorPhysicalAddress,
        'guarantor_phone_no' => $guarantorPhoneNo,
        'guarantor_id_no' => $guarantorIdNo,
        'applicant_signature_file' => $applicantSignatureFile,
        'applicant_signature_date' => $applicantSignatureDate,
        'witness_name' => $witnessName,
        'witness_signature_file' => $witnessSignatureFile,
        'witness_signature_date' => $witnessSignatureDate,
        'hr_finance_manager_name' => $hrManagerName,
        'hr_finance_manager_signature_file' => $hrManagerSignatureFile,
        'hr_finance_manager_date' => $hrManagerDate,
        'loan_recommendation' => $loanRecommendation,
        'status' => 'submitted',
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    );

    // Insert into database
    $result = $con->insert('individual_loan_applications', $data);

    if ($result) {
        $response['success'] = true;
        $response['message'] = 'Application submitted successfully';
        $response['application_number'] = $applicationNumber;
    } else {
        throw new Exception('Failed to save application to database');
    }

} catch (Exception $e) {
    $response['success'] = false;
    $response['message'] = $e->getMessage();
    http_response_code(400);
}

// Return JSON response
echo json_encode($response);
exit();
?>