<?php
// Save Membership Application Handler
header('Content-Type: application/json');

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

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

    // Collect form data
    $account_type = sanitize($_POST['account_type'] ?? '');
    $branch = sanitize($_POST['branch'] ?? '');
    $full_name = sanitize($_POST['full_name'] ?? '');
    $id_type = sanitize($_POST['id_type'] ?? '');
    $id_number = sanitize($_POST['id_number'] ?? '');
    $date_of_birth = sanitize($_POST['date_of_birth'] ?? '');
    $gender = sanitize($_POST['gender'] ?? '');
    $contact_address = sanitize($_POST['contact_address'] ?? '');
    $permanent_address = sanitize($_POST['permanent_address'] ?? '');
    $village = sanitize($_POST['village'] ?? '');
    $town = sanitize($_POST['town'] ?? '');
    $district = sanitize($_POST['district'] ?? '');
    $phone_number = sanitize($_POST['phone_number'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $marital_status = sanitize($_POST['marital_status'] ?? '');
    $spouse_name = sanitize($_POST['spouse_name'] ?? '');
    $spouse_id_type = sanitize($_POST['spouse_id_type'] ?? '');
    $spouse_id_number = sanitize($_POST['spouse_id_number'] ?? '');
    $spouse_phone = sanitize($_POST['spouse_phone'] ?? '');
    $spouse_email = sanitize($_POST['spouse_email'] ?? '');
    
    $occupation_type = sanitize($_POST['occupation_type'] ?? '');
    $occupation_other = sanitize($_POST['occupation_other'] ?? '');
    $institution_name = sanitize($_POST['institution_name'] ?? '');
    $institution_postal_address = sanitize($_POST['institution_postal_address'] ?? '');
    $institution_phone = sanitize($_POST['institution_phone'] ?? '');
    $profession_job_title = sanitize($_POST['profession_job_title'] ?? '');
    $mailing_address = sanitize($_POST['mailing_address'] ?? '');
    
    $monthly_savings = floatval($_POST['monthly_savings'] ?? 0);
    $monthly_shares = floatval($_POST['monthly_shares'] ?? 0);
    $monthly_fixed_deposit = floatval($_POST['monthly_fixed_deposit'] ?? 0);
    $kangachepe_funeral_cover = floatval($_POST['kangachepe_funeral_cover'] ?? 0);
    
    $next_of_kin_name = sanitize($_POST['next_of_kin_name'] ?? '');
    $next_of_kin_dob = sanitize($_POST['next_of_kin_dob'] ?? '');
    $next_of_kin_phone = sanitize($_POST['next_of_kin_phone'] ?? '');
    $next_of_kin_email = sanitize($_POST['next_of_kin_email'] ?? '');
    $next_of_kin_address = sanitize($_POST['next_of_kin_address'] ?? '');
    $next_of_kin_relationship = sanitize($_POST['next_of_kin_relationship'] ?? '');
    
    $nominated_kins = sanitize($_POST['nominated_kins'] ?? '[]');
    
    $referral_sources = sanitize($_POST['referral_sources'] ?? '[]');
    $referral_other = sanitize($_POST['referral_other'] ?? '');
    $referrer_name = sanitize($_POST['referrer_name'] ?? '');
    $sketch_map_description = sanitize($_POST['sketch_map_description'] ?? '');
    
    $applicant_name = sanitize($_POST['applicant_name'] ?? '');
    $applicant_signature_date = sanitize($_POST['applicant_signature_date'] ?? '');
    $applicant_signature = sanitize($_POST['applicant_signature'] ?? '');

    // Validate required fields
    $required_fields = [
        'account_type' => $account_type,
        'branch' => $branch,
        'full_name' => $full_name,
        'id_type' => $id_type,
        'id_number' => $id_number,
        'gender' => $gender,
        'phone_number' => $phone_number,
        'marital_status' => $marital_status,
        'occupation_type' => $occupation_type
    ];

    foreach ($required_fields as $field_name => $field_value) {
        if (empty($field_value)) {
            throw new Exception("Required field missing: " . ucfirst(str_replace('_', ' ', $field_name)));
        }
    }

    // Handle file upload for sketch map
    $sketch_map_file = null;
    if (!empty($_FILES['sketch_map_file']['name'])) {
        $file = $_FILES['sketch_map_file'];
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $max_file_size = 5 * 1024 * 1024; // 5MB

        if (!in_array($file_extension, $allowed_extensions)) {
            throw new Exception('Invalid file format. Only JPG, PNG, and GIF are allowed.');
        }

        if ($file['size'] > $max_file_size) {
            throw new Exception('File size exceeds 5MB limit.');
        }

        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('Error uploading file.');
        }

        // Create uploads directory if it doesn't exist
        $upload_dir = '../../assets/uploads/membership/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // Generate unique filename
        $sketch_map_file = 'sketch_' . time() . '_' . uniqid() . '.' . $file_extension;
        $file_path = $upload_dir . $sketch_map_file;

        if (!move_uploaded_file($file['tmp_name'], $file_path)) {
            throw new Exception('Failed to save uploaded file.');
        }
    }

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

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

    // Prepare data for insertion
    $data = array(
        'account_type' => $account_type,
        'branch' => $branch,
        'full_name' => $full_name,
        'id_type' => $id_type,
        'id_number' => $id_number,
        'date_of_birth' => $date_of_birth,
        'gender' => $gender,
        'contact_address' => $contact_address,
        'permanent_address' => $permanent_address,
        'village' => $village,
        'town' => $town,
        'district' => $district,
        'phone_number' => $phone_number,
        'email' => $email,
        'marital_status' => $marital_status,
        'spouse_name' => $spouse_name,
        'spouse_id_type' => $spouse_id_type,
        'spouse_id_number' => $spouse_id_number,
        'spouse_phone' => $spouse_phone,
        'spouse_email' => $spouse_email,
        'occupation_type' => $occupation_type,
        'occupation_other' => $occupation_other,
        'institution_name' => $institution_name,
        'institution_postal_address' => $institution_postal_address,
        'institution_phone' => $institution_phone,
        'profession_job_title' => $profession_job_title,
        'mailing_address' => $mailing_address,
        'monthly_savings' => $monthly_savings,
        'monthly_shares' => $monthly_shares,
        'monthly_fixed_deposit' => $monthly_fixed_deposit,
        'kangachepe_funeral_cover' => $kangachepe_funeral_cover,
        'next_of_kin_name' => $next_of_kin_name,
        'next_of_kin_dob' => $next_of_kin_dob,
        'next_of_kin_phone' => $next_of_kin_phone,
        'next_of_kin_email' => $next_of_kin_email,
        'next_of_kin_address' => $next_of_kin_address,
        'next_of_kin_relationship' => $next_of_kin_relationship,
        'nominated_kins' => $nominated_kins,
        'referral_sources' => $referral_sources,
        'referral_other' => $referral_other,
        'referrer_name' => $referrer_name,
        'sketch_map_description' => $sketch_map_description,
        'sketch_map_file' => $sketch_map_file,
        'applicant_name' => $applicant_name,
        'applicant_signature_date' => $applicant_signature_date,
        'applicant_signature' => $applicant_signature,
        'application_number' => $applicationNumber,
        'application_status' => 'pending',
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    );

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

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

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

function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
?>
