const db = require("../models");
const Customer = db.customer;
var bcrypt = require("bcryptjs");
const { splitSite } = require("../middlewares");
// Create and Save a new Customer
exports.createCustomer = (req, res) => {
  // Validate request
  if (!req.body.name) {
    res.status(400).send({ message: "Content can not be empty!" });
    return;
  }
  const site = splitSite.findSiteNumber(req);
  // Create a Customer
  const customer = new Customer({
    // Basic Info
    username: req.body.username || req.body.email || '',
    name: req.body.name || '',
    firstname: req.body.firstname || '',
    middle_name: req.body.middle_name || '',
    lastname: req.body.lastname || '',
    name_cn: req.body.name_cn || '',
    name_on_id: req.body.name_on_id || '',
    type: req.body.type || '',
    program_type: req.body.program_type || '',
    pay_source: req.body.pay_source || '',
    pay_source_other: req.body.pay_source_other || '',
    birth_date: req.body.birth_date || null,
    legal_sex: req.body.legal_sex || '',
    gender: req.body.gender || req.body.legal_sex || '',
    marital_status: req.body.marital_status || '',
    marriage_date: req.body.marriage_date || null,
    immigration_status: req.body.immigration_status || '',
    immigration_status_other: req.body.immigration_status_other || '',
    language_spoken: req.body.language_spoken || [],
    language_spoken_other: req.body.language_spoken_other || '',
    language: req.body.language || '',
    
    // Contact Info
    email: req.body.email || '',
    phone: req.body.phone || '',
    mobile_phone: req.body.mobile_phone || '',
    home_phone: req.body.home_phone || '',
    
    // Address 1
    address_line_1: req.body.address_line_1 || '',
    address_line_2: req.body.address_line_2 || '',
    city: req.body.city || '',
    state: req.body.state || '',
    zip_code: req.body.zip_code || '',
    address_note: req.body.address_note || '',
    
    // Address 2
    address2_line_1: req.body.address2_line_1 || '',
    address2_line_2: req.body.address2_line_2 || '',
    city2: req.body.city2 || '',
    state2: req.body.state2 || '',
    zip_code2: req.body.zip_code2 || '',
    address2_note: req.body.address2_note || '',
    
    // Address 3
    address3_line_1: req.body.address3_line_1 || '',
    address3_line_2: req.body.address3_line_2 || '',
    city3: req.body.city3 || '',
    state3: req.body.state3 || '',
    zip_code3: req.body.zip_code3 || '',
    address3_note: req.body.address3_note || '',
    
    // Address 4
    address4_line_1: req.body.address4_line_1 || '',
    address4_line_2: req.body.address4_line_2 || '',
    city4: req.body.city4 || '',
    state4: req.body.state4 || '',
    zip_code4: req.body.zip_code4 || '',
    address4_note: req.body.address4_note || '',
    
    // Address 5
    address5_line_1: req.body.address5_line_1 || '',
    address5_line_2: req.body.address5_line_2 || '',
    city5: req.body.city5 || '',
    state5: req.body.state5 || '',
    zip_code5: req.body.zip_code5 || '',
    address5_note: req.body.address5_note || '',
    
    // Legacy address fields
    address1: req.body.address1 || '',
    address2: req.body.address2 || '',
    address3: req.body.address3 || '',
    address4: req.body.address4 || '',
    address5: req.body.address5 || '',
    street_address_1: req.body.street_address_1 || '',
    city1: req.body.city1 || '',
    state1: req.body.state1 || '',
    zip_code1: req.body.zip_code1 || '',
    street_address_2: req.body.street_address_2 || '',
    street_address_3: req.body.street_address_3 || '',
    street_address_4: req.body.street_address_4 || '',
    street_address_5: req.body.street_address_5 || '',
    apartment: req.body.apartment || '',
    
    // Emergency Contact
    emergency_contact: req.body.emergency_contact || '',
    emergency_contact2: req.body.emergency_contact2 || '',
    emergency_contact_name: req.body.emergency_contact_name || '',
    emergency_contact_phone: req.body.emergency_contact_phone || '',
    emergency_contact_relationship: req.body.emergency_contact_relationship || '',
    emergency_contact_relationship_other: req.body.emergency_contact_relationship_other || '',
    emergency_contact_role: req.body.emergency_contact_role || [],
    emergency_contact2_name: req.body.emergency_contact2_name || '',
    emergency_contact2_phone: req.body.emergency_contact2_phone || '',
    emergency_contact2_relationship: req.body.emergency_contact2_relationship || '',
    emergency_contact2_relationship_other: req.body.emergency_contact2_relationship_other || '',
    emergency_contact2_role: req.body.emergency_contact2_role || [],
    
    // Schedule
    days_of_week: req.body.days_of_week || [],
    
    // Admission & Discharge Record
    admission_date: req.body.admission_date || null,
    enrolled_date: req.body.enrolled_date || null,
    create_by: req.body.create_by || '',
    create_date: new Date(),
    referral_source: req.body.referral_source || '',
    referral_source_other: req.body.referral_source_other || '',
    discharge_date: req.body.discharge_date || null,
    discharge_by: req.body.discharge_by || '',
    discharge_reason: req.body.discharge_reason || '',
    discharge_reason_other: req.body.discharge_reason_other || '',
    join_reason: req.body.join_reason || '',
    
    // Care & Services
    dietary_restrictions: req.body.dietary_restrictions || [],
    dietary_restrictions_other: req.body.dietary_restrictions_other || '',
    diet_texture: req.body.diet_texture || '',
    table_id: req.body.table_id || '',
    seat_number: req.body.seat_number || '',
    seating: req.body.seating || '',
    transportation_type: req.body.transportation_type || '',
    consent_to_text_messages: req.body.consent_to_text_messages || '',
    text_msg_enabled: req.body.text_msg_enabled || false,
    preferred_text_language: req.body.preferred_text_language || '',
    consent_to_media_use: req.body.consent_to_media_use || '',
    pickup_status: req.body.pickup_status || '',
    
    // Medical & Insurance - Providers
    care_provider: req.body.care_provider || '',
    primary_care_physician: req.body.primary_care_physician || '',
    pharmacy: req.body.pharmacy || '',
    pharmacy_id: req.body.pharmacy_id || '',
    
    // General Conditions
    diabetes_mellitus: req.body.diabetes_mellitus || '',
    eyes_on: req.body.eyes_on || '',
    disability: req.body.disability || false,
    wheelchair: req.body.wheelchair || '',
    special_needs: req.body.special_needs || '',
    health_condition: req.body.health_condition || '',
    allergy_info: req.body.allergy_info || '',
    meal_requirement: req.body.meal_requirement || '',
    service_requirement: req.body.service_requirement || '',
    
    // Legal
    molst: req.body.molst || '',
    provisions_for_advance_medical: req.body.provisions_for_advance_medical || '',
    hospice: req.body.hospice || '',
    burial_arrangements: req.body.burial_arrangements || '',
    power_of_attorney: req.body.power_of_attorney || '',
    
    // Rounding
    requires_rounding: req.body.requires_rounding || '',
    rounding_notes: req.body.rounding_notes || '',
    
    // Confidential Details
    medicare_number: req.body.medicare_number || '',
    medicaid_number: req.body.medicaid_number || '',
    social_security_number: req.body.social_security_number || '',
    adcaps_id: req.body.adcaps_id || '',
    
    // Compliance & Deadlines
    adcaps_completed_date: req.body.adcaps_completed_date || null,
    center_qualification_renew_date: req.body.center_qualification_renew_date || null,
    medicaid_renew_date: req.body.medicaid_renew_date || null,
    id_expiration_date: req.body.id_expiration_date || null,
    
    // Form Submission
    hipaa_authorization_form: req.body.hipaa_authorization_form || '',
    medication_management_consent_form: req.body.medication_management_consent_form || '',
    freedom_of_choice_form: req.body.freedom_of_choice_form || '',
    meal_benefit_application_form: req.body.meal_benefit_application_form || '',
    photo_video_release_form: req.body.photo_video_release_form || '',
    security_deposit_agreement_form: req.body.security_deposit_agreement_form || '',
    recreational_program_contract_form: req.body.recreational_program_contract_form || '',
    tb_form: req.body.tb_form || '',
    pre_screening_form: req.body.pre_screening_form || '',
    
    // Additional Information
    note: req.body.note || '',
    notes_for_driver: req.body.notes_for_driver || '',
    private_note: req.body.private_note || '',
    
    // Other fields
    password: req.body.password ? bcrypt.hashSync(req.body.password, 8) : '',
    avatar: req.body.avatar || '',
    parent_id: '5eee3552b02fac3d4acfd5ea',
    nickname: req.body.nickname || '',
    pin: req.body.pin || '',
    vehicle_no: req.body.vehicle_no || '',
    caller: req.body.caller || '',
    placement: req.body.placement || '',
    height: req.body.height || '',
    weight: req.body.weight || '',
    status: 'active',
    roles: req.body.roles || [],
    groups: req.body.groups || [],
    tags: req.body.tags || [],
    edit_by: req.body.edit_by || '',
    edit_date: new Date(),
    payment_due_date: req.body.payment_due_date || '',
    payment_status: req.body.payment_status || '',
    site
   });
  // Save Customer in the database
  customer
    .save(customer)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Customer."
      });
    });
};
// Retrieve all Customers from the database.
exports.getAllCustomers = (req, res) => {
  var condition = {};
  condition = splitSite.splitSiteGet(req, condition);
  Customer.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving customers."
      });
    });
};
// Retrieve all Active Customer from the database.
exports.getAllActiveCustomers = (req, res) => {
  var condition = { status: 'active' };
  condition = splitSite.splitSiteGet(req, condition);
  Customer.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Customers."
      });
    });
};
// Get One Customer by Id
exports.getCustomer = (req, res) => {
  const id = req.params.id;
  Customer.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Customer with id " + id });
      else res.send(data);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Customer with id=" + id });
    });
};
// Update a Customer by the id in the request
exports.updateCustomer = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;
  if (req.body.password) {
    req.body.password = bcrypt.hashSync(req.body.password, 8);
  }
  Customer.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update customer with id=${id}. Maybe Customer was not found!`
        });
      } else res.send({ success: true, message: "Customer was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Customer with id=" + id
      });
    });
};
// Soft Delete a Customer with the specified id in the request
exports.deactivateCustomer = (req, res) => {
  
};
// Delete a Customer by id
exports.deleteCustomer = (req, res) => {

};
// Get Customer with username or email 
exports.getCustomersWithNameOrEmail = (req, res) => {
  var params = req.query;
  var condition = {};
  const nameOrEmail = params?.nameOrEmail;
  if (nameOrEmail) {
    condition = { $or: [ 
      { email: nameOrEmail },
      { name: nameOrEmail }
    ]};
  }
  condition = splitSite.splitSiteGet(req, condition);
  Customer.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving customers."
      });
    });
};
