import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:unit2/model/passo/bldg_loc.dart';
import 'package:unit2/model/passo/city.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/model/passo/land_property_assessment.dart';
import 'package:unit2/model/passo/land_property_boundaries.dart';
import 'package:unit2/model/passo/land_ref.dart';
import 'package:unit2/model/passo/other_improvements.dart';
import 'package:unit2/model/passo/signatories.dart';
import 'package:unit2/model/passo/structural_materials_ii.dart';
import 'package:unit2/model/passo/type_of_road.dart';
import 'package:unit2/model/passo/unit_construct.dart';
import 'package:unit2/utils/request.dart';
import 'package:unit2/utils/urls.dart';
import 'package:http/http.dart' as http;

import '../../../../../model/passo/additional_items.dart';
import '../../../../../model/passo/barangay.dart';
import '../../../../../model/passo/building_and_structure.dart';
import '../../../../../model/passo/class_components _offline.dart';
import '../../../../../model/passo/floor_sketch.dart';
import '../../../../../model/passo/general_description.dart';
import '../../../../../model/passo/land_appr.dart';
import '../../../../../model/passo/land_classification.dart';
import '../../../../../model/passo/land_ext.dart';
import '../../../../../model/passo/land_property_loc.dart';
import '../../../../../model/passo/land_property_owner.dart';
import '../../../../../model/passo/land_subclassification.dart';
import '../../../../../model/passo/land_value_adjustment.dart';
import '../../../../../model/passo/memoranda.dart';
import '../../../../../model/passo/property_appraisal.dart';
import '../../../../../model/passo/property_assessment.dart';
import '../../../../../model/passo/property_info.dart';
import '../../../../../model/passo/structureMaterial.dart';
import '../../../../../model/passo/trees_improvements.dart';
import '../../../../../model/passo/type_of_location.dart';

class SQLServices {
  static final SQLServices instance = SQLServices._init();
  static Database? _database;
  SQLServices._init();

  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await _initDB('passo.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE municipalities (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        cityCode TEXT NOT NULL,
        cityDescription TEXT NOT NULL,
        gen_code TEXT
      )
      ''');
    await db.execute('''
      CREATE TABLE barangay (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        barangayId INTEGER NOT NULL,
        barangayCode TEXT NOT NULL,
        cityCode TEXT NOT NULL,
        barangayDescription TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE class_components (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        componentName TEXT NOT NULL,
        minBaseUnitvalPercent TEXT NOT NULL,
        maxBaseUnitvalPercent TEXT NOT NULL,
        minUnitvalSqrmtr TEXT NOT NULL,
        maxUnitvalSqrmtr TEXT NOT NULL,
        minAddBaseunitval TEXT NOT NULL,
        maxAddBaseunitval TEXT NOT NULL,
        minDeductBaserate TEXT NOT NULL,
        maxDeductBaserate TEXT NOT NULL,
        minLinearMeter TEXT NOT NULL,
        maxLinearMeter TEXT NOT NULL,
        minSpacing TEXT NOT NULL,
        maxSpacing TEXT NOT NULL,
        roughFinish TEXT NOT NULL,
        highFinish TEXT NOT NULL,
        withoutBucc INTEGER NOT NULL
      )
      ''');

    await db.execute('''
      CREATE TABLE unit_construction (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgType TEXT NOT NULL,
        building TEXT NOT NULL,
        unitValue TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE signatories (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        signatoryId INTEGER NOT NULL,
        firstname TEXT NOT NULL,
        middlename TEXT NOT NULL,
        lastname TEXT NOT NULL,
        designation TEXT NOT NULL
      )
      ''');

    await db.execute('''
      CREATE TABLE memoranda (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        code TEXT NOT NULL,
        memoranda TEXT NOT NULL
      )
      ''');

    await db.execute('''
      CREATE TABLE land_classification (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        classificationCode TEXT NOT NULL,
        description TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE land_subclassification (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        classificationId INTEGER NOT NULL,
        cityCode TEXT NOT NULL,
        subclassCode TEXT NOT NULL,
        subclassDescription TEXT NOT NULL,
        baseUnitMarketval TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE trees_improvement (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        improvement TEXT NOT NULL,
        pricePerTree TEXT NOT NULL,
        subclassCode TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE type_of_location (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        distanceKm TEXT NOT NULL,
        allRoadTypes TEXT NOT NULL,
        localTradingCenter TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE type_of_road (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        roadType TEXT NOT NULL,
        deduction TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldg_floor_sketch (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgappr_details_id INTEGER NOT NULL,
        date_created TEXT NOT NULL,
        floor_sketch TEXT NOT NULL,
        gen_code TEXT NOT NULL
      )
      ''');

    await db.execute('''
      CREATE TABLE value_adjustments (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId INTEGER NOT NULL,
        baseMarketval TEXT NOT NULL,
        adjustmentFactors TEXT NOT NULL,
        adjustment TEXT NOT NULL,
        valueAdjustment TEXT NOT NULL,
        marketValue TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldg_owner (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        transCode TEXT NOT NULL,
        tdn TEXT NOT NULL,
        pin TEXT NOT NULL,
        fname TEXT NOT NULL,
        mname TEXT NOT NULL,
        lname TEXT NOT NULL,
        bday TEXT NOT NULL,
        address TEXT NOT NULL,
        telno TEXT NOT NULL,
        tin TEXT NOT NULL,
        adminUser TEXT NOT NULL,
        adminAddress TEXT NOT NULL,
        adminTelno TEXT NOT NULL,
        adminTin TEXT NOT NULL,
        faasType TEXT NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        gen_code TEXT,
        dateSynced TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE landref (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        owner TEXT NOT NULL,
        cloaNo TEXT NOT NULL,
        lotNo TEXT NOT NULL,
        tdn TEXT NOT NULL,
        area TEXT NOT NULL,
        surveyNo TEXT NOT NULL,
        blkNo TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldgloc (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        street TEXT NOT NULL,
        barangay TEXT NOT NULL,
        municipality TEXT NOT NULL,
        province TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE gendesc (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        bldgKind TEXT NOT NULL,
        strucType TEXT NOT NULL,
        bldgPermit TEXT NOT NULL,
        dateIssued TEXT NOT NULL,
        cct TEXT NOT NULL,
        certCompletionIssued TEXT NOT NULL,
        certOccupancyIssued TEXT NOT NULL,
        dateCompleted TEXT NOT NULL,
        dateOccupied TEXT NOT NULL,
        bldgAge TEXT NOT NULL,
        noStoreys TEXT NOT NULL,
        area1Stfloor TEXT NOT NULL,
        area2Ndfloor TEXT NOT NULL,
        area3Rdfloor TEXT NOT NULL,
        area4Thfloor TEXT NOT NULL,
        totalFloorArea TEXT NOT NULL,
        floorSketch TEXT NOT NULL,
        actualUse TEXT NOT NULL,
        unitValue TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldg_and_structure (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        bldgType TEXT NOT NULL,
        strucType TEXT NOT NULL,
        description TEXT NOT NULL,
        actualUse TEXT NOT NULL,
        floorCount TEXT NOT NULL,
        bldgArea TEXT NOT NULL,
        unitValue TEXT NOT NULL,
        buccPercentage TEXT NOT NULL,
        depRate TEXT NOT NULL,
        marketValue TEXT NOT NULL,
        depAmount TEXT NOT NULL,
        adjustedMarketValue TEXT NOT NULL,
        gen_code TEXT,
        dateSync TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE structural_materials (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        foundation TEXT NOT NULL,
        columns TEXT NOT NULL,
        beams TEXT NOT NULL,
        trussFraming TEXT NOT NULL,
        roof TEXT NOT NULL,
        flooring TEXT NOT NULL,
        walls TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldg_appraisal (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        unitconstructCost TEXT NOT NULL,
        buildingCore TEXT NOT NULL,
        unitconstructSubtotal TEXT NOT NULL,
        depreciationRate TEXT NOT NULL,
        depreciationCost TEXT NOT NULL,
        costAddItems TEXT NOT NULL,
        addItemsSubtotal TEXT NOT NULL,
        totalpercentDepreciation TEXT NOT NULL,
        marketValue TEXT NOT NULL,
        totalArea TEXT NOT NULL,
        actualUse TEXT NOT NULL,
        gen_code TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE bldg_assessment (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        bldgapprDetailsId INTEGER NOT NULL, 
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        actualUse TEXT NOT NULL, 
        marketValue TEXT NOT NULL,
        assessmentLevel TEXT NOT NULL, 
        assessedValue TEXT NOT NULL, 
        taxable TEXT NOT NULL, 
        exempt TEXT NOT NULL, 
        qtr TEXT NOT NULL, 
        yr TEXT NOT NULL, 
        appraisedbyName TEXT NOT NULL, 
        appraisedbyDate TEXT NOT NULL,
        appraisedby_designation TEXT,
        recommendapprName TEXT NOT NULL, 
        recommendapprDate TEXT NOT NULL, 
        recommendappr_designation TEXT,
        approvedbyName TEXT NOT NULL, 
        approvedby_designation TEXT,
        approvedbyDate  TEXT,
        memoranda TEXT NOT NULL, 
        swornstatementNo TEXT NOT NULL, 
        dateReceived TEXT NOT NULL, 
        entryDateAssessment TEXT NOT NULL, 
        entryDateBy TEXT NOT NULL,
        gen_code TEXT,
        note TEXT
      )
      ''');

    await db.execute('''
      CREATE TABLE additionalitems (
         id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
         bldgapprDetailsId INTEGER NOT NULL,
         classId INTEGER NOT NULL,
         className TEXT NOT NULL,
         structType TEXT NOT NULL,
         unitValue TEXT NOT NULL,
         baseUnitValue TEXT NOT NULL,
         area TEXT NOT NULL,
         marketValue TEXT NOT NULL,
         depreciationRate TEXT NOT NULL,
         adjustedMarketVal TEXT NOT NULL,
         amtDepreciation TEXT NOT NULL,
         painted TEXT NOT NULL,
         secondhand TEXT NOT NULL,
         paintedUnitval TEXT NOT NULL,
         secondhandUnitval TEXT NOT NULL,
         actualUse TEXT NOT NULL,
         gen_code TEXT,
         dateSync TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_owner (
         id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
         assessedById TEXT NOT NULL,
         assessedByName TEXT NOT NULL,
         dateCreated TEXT NOT NULL,
         dateModified TEXT NOT NULL,
         transCode TEXT NOT NULL,
         tdn TEXT NOT NULL,
         pin TEXT NOT NULL,
         cloaNo TEXT NOT NULL,
         dated TEXT NOT NULL,
         surveyNo TEXT NOT NULL,
         lotNo TEXT NOT NULL,
         blkNo TEXT NOT NULL,
         owner TEXT NOT NULL,
         address  TEXT NOT NULL,
         telno TEXT NOT NULL,
         tin TEXT NOT NULL,
         adminUser TEXT NOT NULL,
         adminTelno  TEXT NOT NULL,
         adminAddress TEXT NOT NULL, 
         adminTin TEXT NOT NULL,
         faasType TEXT NOT NULL,
         gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_location (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        street TEXT NOT NULL,
        municipality TEXT NOT NULL,
        barangay TEXT NOT NULL,
        province TEXT NOT NULL,
        gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_boundaries (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId INTEGER NOT NULL,
        assessedById TEXT NOT NULL,
        assessedByName TEXT NOT NULL,
        dateCreated TEXT NOT NULL,
        dateModified TEXT NOT NULL,
        north  TEXT NOT NULL,
        east  TEXT NOT NULL,
        south  TEXT NOT NULL,
        west  TEXT NOT NULL,
        sketch  TEXT NOT NULL,
        gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_appr (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId INTEGER NOT NULL,
        classification TEXT NOT NULL,
        subClass TEXT NOT NULL,
        area TEXT NOT NULL,
        unitValue TEXT NOT NULL,
        baseMarketval  TEXT NOT NULL,
        gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_other_improvements (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId  INTEGER NOT NULL,
        kindsOfTrees  TEXT NOT NULL,
        subclassAge  TEXT NOT NULL,
        quantity  INTEGER NOT NULL,
        unitValue  TEXT NOT NULL,
        baseMarketval  TEXT NOT NULL,
        noOfProductive  INTEGER NOT NULL,
        noOfNonproductive  INTEGER NOT NULL,
        fruitBearing  TEXT NOT NULL,
        gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_assessment (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId  INTEGER NOT NULL,
        actualUse  TEXT NOT NULL,
        marketval  TEXT NOT NULL,
        assessmentLevel  TEXT NOT NULL,
        assessedValue  TEXT NOT NULL,
        totalMarketval  TEXT NOT NULL,
        totalAssessedval  TEXT NOT NULL,
        gen_code TEXT
      )
    ''');

    await db.execute('''
      CREATE TABLE land_property_ext (
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        landapprDetailsId  INTEGER NOT NULL,
        assessedById   TEXT NOT NULL,
        assessedByName   TEXT NOT NULL,
        dateCreated   TEXT NOT NULL,
        dateModified   TEXT NOT NULL,
        taxable   TEXT NOT NULL,
        exempt   TEXT NOT NULL,
        qtr   TEXT NOT NULL,
        yr   TEXT NOT NULL,
        appraisedbyName   TEXT NOT NULL,
        appraisedbyDate   TEXT NOT NULL,
        recommendapprName   TEXT NOT NULL,
        recommendapprDate   TEXT NOT NULL,
        approvedbyName   TEXT NOT NULL,
        approvedbyDate   TEXT NOT NULL,
        memoranda   TEXT NOT NULL,
        swornstatementNo   TEXT NOT NULL,
        dateReceived   TEXT NOT NULL,
        entryDateAssessment   TEXT NOT NULL,
        entryDateBy   TEXT NOT NULL,
        gen_code TEXT
      )
    ''');
  }

  //Municipalities

  Future<City> createMunicipalities(City city) async {
    final db = await instance.database;

    final data = {
      "id": city.id,
      "cityCode": city.cityCode,
      "cityDescription": city.cityDescription,
    };
    final id = await db.insert('municipalities', data);
    return city.copy(id: id);
  }

  Future<List<City>> readAllMunicipalities() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('municipalities', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => City.fromJson2(json)).toList();
  }

  //Barangay

  Future<Brgy> createBarangay(Brgy brgy) async {
    final db = await instance.database;

    final data = {
      "barangayId": brgy.barangayId,
      "barangayCode": brgy.barangayCode,
      "cityCode": brgy.cityCode,
      "barangayDescription": brgy.barangayDescription
    };
    final id = await db.insert('barangay', data);
    return brgy.copy(id: id);
  }

  Future<List<Brgy>> readBrgyInSelectedMunicipality(cityCode) async {
    final db = await instance.database;
    const orderBy = 'id';
    // Use a placeholder for the WHERE clause and provide the value separately.
    final params = [cityCode]; // List of values to substitute

    final result = await db.query('barangay',
        orderBy: orderBy, where: 'cityCode = ?', whereArgs: params);
    print('result');
    print(cityCode);
    print(result.toString());

    return result.map((json) => Brgy.fromJson2(json)).toList();
  }

  Future<List<Brgy>> readAllBarangay() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('barangay', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => Brgy.fromJson2(json)).toList();
  }

  //Class components

  Future<ClassComponentsOffline> createClassComponents(
      ClassComponentsOffline classes) async {
    final db = await instance.database;

    final data = {
      "componentName": classes.componentName,
      "minBaseUnitvalPercent": classes.minBaseUnitvalPercent,
      "maxBaseUnitvalPercent": classes.maxBaseUnitvalPercent,
      "minUnitvalSqrmtr": classes.minUnitvalSqrmtr,
      "maxUnitvalSqrmtr": classes.maxUnitvalSqrmtr,
      "minAddBaseunitval": classes.minAddBaseunitval,
      "maxAddBaseunitval": classes.maxAddBaseunitval,
      "minDeductBaserate": classes.minDeductBaserate,
      "maxDeductBaserate": classes.maxDeductBaserate,
      "minLinearMeter": classes.minLinearMeter,
      "maxLinearMeter": classes.maxLinearMeter,
      "minSpacing": classes.minSpacing,
      "maxSpacing": classes.maxSpacing,
      "roughFinish": classes.roughFinish,
      "highFinish": classes.highFinish,
      "withoutBucc": classes.withoutBucc
    };
    final id = await db.insert('class_components', data);
    return classes.copy(id: id);
  }

  Future<List<ClassComponentsOffline>> readAllClassComponents() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('class_components', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result
        .map((json) => ClassComponentsOffline.fromJson2(json))
        .toList();
  }

  //Unit construction

  Future<UnitConstruct> createUnitConstruction(UnitConstruct unit) async {
    final db = await instance.database;

    final data = {
      "bldgType": unit.bldgType,
      "building": unit.building,
      "unitValue": unit.unitValue,
      "gen_code": unit.genCode
    };
    final id = await db.insert('unit_construction', data);
    return unit.copy(id: id);
  }

  Future<List<UnitConstruct>> readAllUnitConstruct() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('unit_construction', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => UnitConstruct.fromJson2(json)).toList();
  }

  //Signatories

  Future<Signatories> createSignatories(Signatories signatories) async {
    final db = await instance.database;

    final data = {
      "signatoryId": signatories.signatoryId,
      "firstname": signatories.firstname,
      "middlename": signatories.middlename,
      "lastname": signatories.lastname,
      "designation": signatories.designation,
    };
    final id = await db.insert('signatories', data);
    return signatories.copy(id: id);
  }

  Future<List<Signatories>> readAllSignatories() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('signatories', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => Signatories.fromJson2(json)).toList();
  }

  // Memoranda

  Future<Memoranda> createMemoranda(Memoranda memo) async {
    final db = await instance.database;

    final data = {
      "id": memo.id,
      "code": memo.code,
      "memoranda": memo.memoranda
    };
    final id = await db.insert('memoranda', data);
    return memo.copy(id: id);
  }

  Future<List<Memoranda>> readAllMemoranda() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('memoranda', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => Memoranda.fromJson2(json)).toList();
  }

  // Land Classification

  Future<LandClassification> createLandClassification(
      LandClassification landClass) async {
    final db = await instance.database;

    final data = {
      // "id": landClass.id,
      "classificationCode": landClass.classificationCode,
      "description": landClass.description
    };
    final id = await db.insert('land_classification', data);
    return landClass.copy(id: id);
  }

  Future<List<LandClassification>> readAllLandClassification() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('land_classification', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => LandClassification.fromJson2(json)).toList();
  }

  //Land SubClassification

  Future<LandSubClassification> createLandSubClassification(
      LandSubClassification landSubClass) async {
    final db = await instance.database;

    final data = {
      "id": landSubClass.id,
      "classificationId": landSubClass.classificationId,
      "cityCode": landSubClass.cityCode,
      "subclassCode": landSubClass.subclassCode,
      "subclassDescription": landSubClass.subclassDescription,
      "baseUnitMarketval": landSubClass.baseUnitMarketval
    };
    final id = await db.insert('land_subclassification', data);
    return landSubClass.copy(id: id);
  }

  Future<List<LandSubClassification>> readAllLandSubClassification() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('land_subclassification', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => LandSubClassification.fromJson2(json)).toList();
  }

  Future<List<LandSubClassification>> readSpecificLandSubClassification(
      cityCode, classificationId) async {
    final db = await instance.database;
    const orderBy = 'id';

    // Use placeholders for the WHERE clause and provide the values separately.
    final params = [cityCode, classificationId]; // List of values to substitute

    final result = await db.query('land_subclassification',
        orderBy: orderBy,
        where: 'cityCode = ? AND classificationId = ?',
        whereArgs: params);

    print('result');
    print(cityCode);
    print(classificationId);
    print(result.toString());

    return result.map((json) => LandSubClassification.fromJson2(json)).toList();
  }

  //Trees Improvements

  Future<TreesImprovements> createTreesImprovements(
      TreesImprovements treesImprovements) async {
    final db = await instance.database;

    final data = {
      // "id": treesImprovements.id,
      "improvement": treesImprovements.improvement,
      "pricePerTree": treesImprovements.pricePerTree,
      "subclassCode": treesImprovements.subclassCode
    };
    final id = await db.insert('trees_improvement', data);
    return treesImprovements.copy(id: id);
  }

  Future<List<TreesImprovements>> readAllTreesImprovements() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('trees_improvement', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => TreesImprovements.fromJson2(json)).toList();
  }

  //Type of Location

  Future<TypeOfLocation> createTypeOfLocation(
      TypeOfLocation typeOfLocation) async {
    final db = await instance.database;

    final data = {
      "id": typeOfLocation.id,
      "distanceKm": typeOfLocation.distanceKm,
      "allRoadTypes": typeOfLocation.allRoadTypes,
      "localTradingCenter": typeOfLocation.localTradingCenter
    };
    final id = await db.insert('type_of_location', data);
    return typeOfLocation.copy(id: id);
  }

  Future<List<TypeOfLocation>> readAllTypeOfLocation() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('type_of_location', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => TypeOfLocation.fromJson2(json)).toList();
  }

  //Type of Road

  Future<TypeOfRoad> createTypeOfRoad(TypeOfRoad typeOfRoad) async {
    final db = await instance.database;

    final data = {
      "id": typeOfRoad.id,
      "roadType": typeOfRoad.roadType,
      "deduction": typeOfRoad.deduction,
    };
    final id = await db.insert('type_of_road', data);
    return typeOfRoad.copy(id: id);
  }

  Future<List<TypeOfRoad>> readAllTypeOfRoad() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('type_of_road', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => TypeOfRoad.fromJson2(json)).toList();
  }

  //BLDG Owner

  Future<PropertyInfo> createBldgOwner(PropertyInfo propertyInfo) async {
    final db = await instance.database;

    final data = {
      "id": propertyInfo.id,
      "transCode": propertyInfo.transCode,
      "tdn": propertyInfo.tdn,
      "pin": propertyInfo.pin,
      "lname": propertyInfo.lname,
      "mname": propertyInfo.mname,
      "fname": propertyInfo.fname,
      "bday": propertyInfo.bday,
      "address": propertyInfo.address,
      "telno": propertyInfo.telno,
      "tin": propertyInfo.tin,
      "adminUser": propertyInfo.adminUser,
      "adminAddress": propertyInfo.adminAddress,
      "adminTelno": propertyInfo.adminTelno,
      "adminTin": propertyInfo.adminTin,
      "faasType": propertyInfo.faasType,
      "assessedById": propertyInfo.assessedById,
      "assessedByName": propertyInfo.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
    };
    final id = await db.insert('bldg_owner', data);
    final tempID = await SharedPreferences.getInstance();
    print(propertyInfo.copy(id: id).toJson());
    await tempID.setInt('tempid', id);
    return propertyInfo.copy(id: id);
  }

  Future<List<PropertyInfo>> readAllBldgOwner() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('bldg_owner', orderBy: orderBy);

    return result.map((json) => PropertyInfo.fromJson2(json)).toList();
  }

  Future<int> updateBldgOwner(id, PropertyInfo propertyInfo) async {
    final db = await instance.database;
    final data = {
      "transCode": propertyInfo.transCode,
      "tdn": propertyInfo.tdn,
      "pin": propertyInfo.pin,
      "bday": propertyInfo.bday,
      "fname": propertyInfo.fname,
      "mname": propertyInfo.mname,
      "lname": propertyInfo.lname,
      "address": propertyInfo.address,
      "telno": propertyInfo.telno,
      "tin": propertyInfo.tin,
      "adminUser": propertyInfo.adminUser,
      "adminAddress": propertyInfo.adminAddress,
      "adminTelno": propertyInfo.adminTelno,
      "adminTin": propertyInfo.adminTin,
      "faasType": propertyInfo.faasType,
      "assessedById": propertyInfo.assessedById,
      "assessedByName": propertyInfo.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
      "dateSynced": propertyInfo.dateSynced
    };

    final result =
        await db.update('bldg_owner', data, where: "id = ?", whereArgs: [id]);

    if (result > 0) {
      print('Bldg Owner Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  Future<int> deleteBldgOwner({required int id}) async {
    final db = await instance.database;

    return await db.delete(
      'bldg_owner',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  //Bldg Land Ref
  Future<LandRef> createBldgLandRef(LandRef landref) async {
    final db = await instance.database;

    final data = {
      "bldgapprDetailsId": landref.bldgapprDetailsId,
      "assessedById": landref.assessedById,
      "assessedByName": landref.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
      "owner": landref.owner,
      "cloaNo": landref.cloaNo,
      "lotNo": landref.lotNo,
      "tdn": landref.tdn,
      "area": landref.area,
      "surveyNo": landref.surveyNo,
      "blkNo": landref.blkNo
    };
    final id = await db.insert('landref', data);
    print(landref.copy(id: id).toJson());
    return landref.copy(id: id);
  }

  Future<int> updateLandRef(id, LandRef landref) async {
    final db = await instance.database;
    final data = {
      "bldgapprDetailsId": landref.bldgapprDetailsId,
      "assessedById": landref.assessedById,
      "assessedByName": landref.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
      "owner": landref.owner,
      "cloaNo": landref.cloaNo,
      "lotNo": landref.lotNo,
      "tdn": landref.tdn,
      "area": landref.area,
      "surveyNo": landref.surveyNo,
      "blkNo": landref.blkNo
    };

    final result = await db.update('landref', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('LanRef Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  Future<List<Map<String, dynamic>>> getLandRef(id) async {
    final db = await instance.database;
    int ids = id;
    print('id');
    print(id);
    final result = await db
        .query('landref', where: 'bldgapprDetailsId = ?', whereArgs: [ids]);

    print('landref test result');

    if (result.isNotEmpty) {
      final firstRow = result[0];
      print(firstRow);
    } else {
      print('No data found.');
    }

    return result;
  }

  Future<List<LandRef>> getAllLandRef() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('landref', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => LandRef.fromJson2(json)).toList();
  }

  //Bldg Location
  Future<BldgLoc> createBldglocation(BldgLoc bldgloc) async {
    final db = await instance.database;

    final data = {
      "bldgapprDetailsId": bldgloc.bldgapprDetailsId,
      "assessedById": bldgloc.assessedById,
      "assessedByName": bldgloc.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
      "street": bldgloc.street,
      "barangay": bldgloc.barangay,
      "municipality": bldgloc.municipality,
      "province": bldgloc.province
    };
    final id = await db.insert('bldgloc', data);

    print(id);

    return bldgloc.copy(id: id);
  }

  Future<int> updateLocation(id, BldgLoc bldgloc) async {
    final db = await instance.database;
    final data = {
      "bldgapprDetailsId": bldgloc.bldgapprDetailsId,
      "assessedById": bldgloc.assessedById,
      "assessedByName": bldgloc.assessedByName,
      "dateCreated": "000",
      "dateModified": "000",
      "street": bldgloc.street,
      "barangay": bldgloc.barangay,
      "municipality": bldgloc.municipality,
      "province": bldgloc.province
    };

    final result = await db.update('bldgloc', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('Location Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  Future<List<Map<String, dynamic>>> getLocation(id) async {
    final db = await instance.database;
    final results = await db.query('bldgloc',
        where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1);
    print('loc test result');
    print(results);

    return results;
  }

  //Bldg General Description

  Future<GeneralDesc> createBldgGeneralDescription(GeneralDesc gendesc) async {
    final db = await instance.database;

    final data = {
      "bldgapprDetailsId": gendesc.bldgapprDetailsId,
      "assessedById": gendesc.assessedById,
      "assessedByName": gendesc.assessedByName,
      "dateCreated": 'None',
      "dateModified": 'None',
      "bldgKind": gendesc.bldgKind,
      "strucType": gendesc.strucType,
      "bldgPermit": gendesc.bldgPermit,
      "dateIssued": gendesc.dateIssued,
      "cct": gendesc.cct,
      "certCompletionIssued": gendesc.certCompletionIssued,
      "certOccupancyIssued": gendesc.certOccupancyIssued,
      "dateCompleted": gendesc.dateCompleted,
      "dateOccupied": gendesc.dateOccupied,
      "bldgAge": gendesc.bldgAge,
      "noStoreys": gendesc.noStoreys,
      "area1Stfloor": gendesc.area1Stfloor,
      "area2Ndfloor": gendesc.area2Ndfloor,
      "area3Rdfloor": gendesc.area3Rdfloor,
      "area4Thfloor": gendesc.area4Thfloor,
      "totalFloorArea": gendesc.totalFloorArea,
      "floorSketch": 'None',
      "actualUse": gendesc.actualUse,
      "unitValue": gendesc.unitValue
    };
    final id = await db.insert('gendesc', data);
    print(gendesc.copy(id: id));
    return gendesc.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getGeneralDescription(id) async {
    final db = await instance.database;
    final results = await db.query('gendesc',
        where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1);
    print('gendesc test result');
    print(results);

    return results;
  }

  Future<int> updateGeneralDescription(id, GeneralDesc gendesc) async {
    final db = await instance.database;
    final data = {
      "bldgapprDetailsId": gendesc.bldgapprDetailsId,
      "assessedById": gendesc.assessedById,
      "assessedByName": gendesc.assessedByName,
      "dateCreated": 'None',
      "dateModified": 'None',
      "bldgKind": gendesc.bldgKind,
      "strucType": gendesc.strucType,
      "bldgPermit": gendesc.bldgPermit,
      "dateIssued": gendesc.dateIssued,
      "cct": gendesc.cct,
      "certCompletionIssued": gendesc.certCompletionIssued,
      "certOccupancyIssued": gendesc.certOccupancyIssued,
      "dateCompleted": gendesc.dateCompleted,
      "dateOccupied": gendesc.dateOccupied,
      "bldgAge": gendesc.bldgAge,
      "noStoreys": gendesc.noStoreys,
      "area1Stfloor": gendesc.area1Stfloor,
      "area2Ndfloor": gendesc.area2Ndfloor,
      "area3Rdfloor": gendesc.area3Rdfloor,
      "area4Thfloor": gendesc.area4Thfloor,
      "totalFloorArea": gendesc.totalFloorArea,
      "floorSketch": 'None',
      "actualUse": gendesc.actualUse,
      "unitValue": gendesc.unitValue
    };

    final result = await db.update('gendesc', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('GenDesc Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  // Floor Sketch

  Future<FloorSketch> createFloorSketch(FloorSketch floorSketch) async {
    final db = await instance.database;

    final data = {
      // "id": treesImprovements.id,
      "bldgappr_details_id": floorSketch.bldgapprDetailsId,
      "date_created": floorSketch.dateCreated,
      "floor_sketch": floorSketch.floorSketch,
      "gen_code": "5TH"
    };
    final id = await db.insert('bldg_floor_sketch', data);
    return floorSketch.copy(bldgapprDetailsId: id);
  }

  Future<List<Map<String, dynamic>>> getFloorSketch(id) async {
    final db = await instance.database;
    final results = await db.query('bldg_floor_sketch',
        where: "bldgappr_details_id = ?", whereArgs: [id], limit: 1);
    print('floor sketch test result');
    print(results);

    return results;
  }

  //Structural Materials

  Future<StructureMaterialsII> createStructuralMaterials(
      StructureMaterialsII materials) async {
    final db = await instance.database;

    final data = {
      // "id": materials.id,
      "bldgapprDetailsId": materials.bldgapprDetailsId,
      "foundation": materials.foundation!.join(', ').splitMapJoin(', '),
      "columns": materials.columns!.join(', ').splitMapJoin(', '),
      "beams": materials.beams!.join(', ').splitMapJoin(', '),
      "trussFraming": materials.trussFraming!.join(', ').splitMapJoin(', '),
      "roof": materials.roof!.join(', ').splitMapJoin(', '),
      "flooring": materials.flooring!.join(', ').splitMapJoin(', '),
      "walls": materials.walls!.join(', ').splitMapJoin(', '),
      "assessedById": materials.assessedById,
      "assessedByName": materials.assessedByName,
      "dateCreated": materials.dateCreated,
      "dateModified": materials.dateModified,
      "gen_code": materials.genCode
    };
    final id = await db.insert('structural_materials', data);
    print('strct Mat test idcopy');
    print(id);
    return materials.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getStructuralMaterials(id) async {
    final db = await instance.database;
    final results = await db.query('structural_materials',
        where: "bldgapprDetailsId = ?", whereArgs: [id], limit: 1);
    print('strucmat test result');
    print(results);

    return results;
  }

  Future<int> updateStructuralMaterial(
      id, StructureMaterialsII materials) async {
    final db = await instance.database;
    final data = {
      "foundation": materials.foundation?.join(', ').splitMapJoin(', '),
      "columns": materials.columns!.join(', ').splitMapJoin(', '),
      "beams": materials.beams!.join(', ').splitMapJoin(', '),
      "trussFraming": materials.trussFraming!.join(', ').splitMapJoin(', '),
      "roof": materials.roof!.join(', ').splitMapJoin(', '),
      "flooring": materials.flooring!.join(', ').splitMapJoin(', '),
      "walls": materials.walls!.join(', ').splitMapJoin(', '),
    };

    final result = await db.update('structural_materials', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('Structural Materials Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  //Additional Items

  Future<AdditionalItems> createAdditionalItems(
      AdditionalItems addItems) async {
    final db = await instance.database;

    final data = {
      // "id": addItems.id,
      "bldgapprDetailsId": addItems.bldgapprDetailsId,
      "classId": addItems.classId,
      "className": addItems.className,
      "structType": addItems.structType,
      "unitValue": addItems.unitValue,
      "baseUnitValue": addItems.baseUnitValue,
      "area": addItems.area,
      "marketValue": addItems.marketValue,
      "depreciationRate": addItems.depreciationRate,
      "adjustedMarketVal": addItems.adjustedMarketVal,
      "amtDepreciation": addItems.amtDepreciation,
      "painted": addItems.painted == true ? '1' : 0,
      "secondhand": addItems.secondhand == true ? '1' : 0,
      "paintedUnitval": addItems.paintedUnitval,
      "secondhandUnitval": addItems.secondhandUnitval,
      "actualUse": addItems.actualUse,
      "gen_code": addItems.genCode
    };
    final id = await db.insert('additionalitems', data);
    return addItems.copy(id: id);
  }

  Future<List<AdditionalItems>> readAdditionalItems() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('additionalitems', orderBy: orderBy);

    return result.map((json) => AdditionalItems.fromJson(json)).toList();
  }

  Future<List<Map<String, dynamic>>> getAdditionalItems(id) async {
    final db = await instance.database;
    final results = await db.query('additionalitems',
        where: "bldgapprDetailsId = ?", whereArgs: [id]);
    print('add edit test result');
    print(results);

    return results;
  }

  Future<int> deleteAdditionalItems({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'additionalitems',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // Building and Structure

  Future<BldgAndStructure> createBuildingAndStructure(
      BldgAndStructure bldgAndStructure) async {
    final db = await instance.database;

    final data = {
      // "id": bldgAndStructure.id,
      "bldgapprDetailsId": bldgAndStructure.bldgapprDetailsId,
      "assessedById": 'none',
      "assessedByName": 'none',
      "dateCreated": 'none',
      "dateModified": 'none',
      "bldgType": bldgAndStructure.bldgType,
      "strucType": bldgAndStructure.structType,
      "description": bldgAndStructure.description,
      "actualUse": bldgAndStructure.actualUse,
      "floorCount": bldgAndStructure.floorCount,
      "bldgArea": bldgAndStructure.bldgArea,
      "unitValue": bldgAndStructure.unitValue,
      "depRate": bldgAndStructure.depRate,
      "marketValue": bldgAndStructure.marketValue,
      "depAmount": bldgAndStructure.depAmount,
      "adjustedMarketValue": bldgAndStructure.adjustedMarketValue,
      "buccPercentage": bldgAndStructure.buccPercentage,
    };
    final id = await db.insert('bldg_and_structure', data);
    return bldgAndStructure.copy(id: id);
  }

  Future<List<BldgAndStructure>> readBuildingAndStructure() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('bldg_and_structure', orderBy: orderBy);

    return result.map((json) => BldgAndStructure.fromJson(json)).toList();
  }

  Future<List<Map<String, dynamic>>> getBuildingAndStructure(id) async {
    final db = await instance.database;
    final results = await db.query('bldg_and_structure',
        where: "bldgapprDetailsId = ?", whereArgs: [id]);
    print('add edit test result');
    print(results);

    return results;
  }

  Future<int> deleteBuildingAndStructure({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'bldg_and_structure',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  //Bldg Appraisal

  Future<PropertyAppraisal> createBldgAppraisal(
      PropertyAppraisal appraisal) async {
    final db = await instance.database;

    final data = {
      // "id": appraisal.id,
      "bldgapprDetailsId": appraisal.bldgapprDetailsId,
      "assessedById": appraisal.assessedById,
      "assessedByName": appraisal.assessedByName,
      "dateCreated": appraisal.dateCreated,
      "dateModified": appraisal.dateModified,
      "unitconstructCost": appraisal.unitconstructCost,
      "buildingCore": appraisal.buildingCore,
      "unitconstructSubtotal": appraisal.unitconstructSubtotal,
      "depreciationRate": appraisal.depreciationRate,
      "depreciationCost": appraisal.depreciationCost,
      "costAddItems": appraisal.costAddItems,
      "addItemsSubtotal": appraisal.addItemsSubtotal,
      "totalpercentDepreciation": appraisal.totalpercentDepreciation,
      "marketValue": appraisal.marketValue,
      "totalArea": appraisal.totalArea,
      "actualUse": appraisal.actualUse
    };
    final id = await db.insert('bldg_appraisal', data);
    return appraisal.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getBldgAppraisal(id) async {
    final db = await instance.database;
    final results = await db.query('bldg_appraisal',
        where: "bldgapprDetailsId = ?", whereArgs: [id]);
    print('appraisal edit test result');
    print(results);

    return results;
  }

  Future<int> updateAppraisal(id, PropertyAppraisal appraisal) async {
    final db = await instance.database;
    final data = {
      "bldgapprDetailsId": appraisal.bldgapprDetailsId,
      "assessedById": appraisal.assessedById,
      "assessedByName": appraisal.assessedByName,
      "dateCreated": appraisal.dateCreated,
      "dateModified": appraisal.dateModified,
      "unitconstructCost": appraisal.unitconstructCost,
      "buildingCore": appraisal.buildingCore,
      "unitconstructSubtotal": appraisal.unitconstructSubtotal,
      "depreciationRate": appraisal.depreciationRate,
      "depreciationCost": appraisal.depreciationCost,
      "costAddItems": appraisal.costAddItems,
      "addItemsSubtotal": appraisal.addItemsSubtotal,
      "totalpercentDepreciation": appraisal.totalpercentDepreciation,
      "marketValue": appraisal.marketValue,
      "totalArea": appraisal.totalArea,
      "actualUse": appraisal.actualUse
    };

    final result = await db.update('bldg_appraisal', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('Appraisal Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  //Bldg Assessment
  Future<PropertyAssessment> createBldgAssessment(
      PropertyAssessment assessment) async {
    final db = await instance.database;
    print('assesss');
    print(assessment.toJson());

    final data = {
      // "id": assessment.id,
      "bldgapprDetailsId": assessment.bldgapprDetailsId,
      "assessedById": assessment.assessedById,
      "assessedByName": assessment.assessedByName,
      "dateCreated": assessment.dateCreated,
      "dateModified": assessment.dateModified,
      "actualUse": assessment.actualUse,
      "marketValue": assessment.marketValue,
      "assessmentLevel": assessment.assessmentLevel,
      "assessedValue": assessment.assessedValue,
      "taxable": assessment.taxable,
      "exempt": assessment.exempt,
      "qtr": assessment.qtr,
      "yr": assessment.yr,
      "appraisedbyName": assessment.appraisedbyName,
      "appraisedbyDate": assessment.appraisedbyDate,
      "recommendapprName": assessment.recommendapprName,
      "recommendapprDate": assessment.recommendapprDate,
      "approvedbyName": assessment.approvedbyName,
      "approvedbyDate": assessment.approvedbyDate,
      "memoranda": assessment.memoranda,
      "swornstatementNo": assessment.swornstatementNo,
      "dateReceived": assessment.dateReceived,
      "entryDateAssessment": assessment.entryDateAssessment,
      "entryDateBy": assessment.entryDateBy,
      "gen_code": assessment.genCode,
      "note": assessment.note,
      "appraisedby_designation": assessment.appraisedbyDesignation,
      "recommendappr_designation": assessment.recommendapprDesignation,
      "approvedby_designation": assessment.approvedbyDesignation
    };
    final id = await db.insert('bldg_assessment', data);
    return assessment.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getBldgAssessment(id) async {
    final db = await instance.database;
    final results = await db.query('bldg_assessment',
        where: "bldgapprDetailsId = ?", whereArgs: [id]);
    print('assessment edit test result');
    print(results);

    return results;
  }

  Future<int> updateAssessment(id, PropertyAssessment assessment) async {
    final db = await instance.database;
    final data = {
      "bldgapprDetailsId": assessment.bldgapprDetailsId,
      "actualUse": assessment.actualUse,
      "marketValue": assessment.marketValue,
      "assessmentLevel": assessment.assessmentLevel,
      "assessedValue": assessment.assessedValue,
      "taxable": assessment.taxable,
      "exempt": assessment.exempt,
      "qtr": assessment.qtr,
      "yr": assessment.yr,
      "appraisedbyName": assessment.appraisedbyName,
      "appraisedbyDate": assessment.appraisedbyDate,
      "recommendapprName": assessment.recommendapprName,
      "recommendapprDate": assessment.recommendapprDate,
      "approvedbyName": assessment.approvedbyName,
      "memoranda": assessment.memoranda,
      "swornstatementNo": assessment.swornstatementNo,
      "dateReceived": assessment.dateReceived,
      "entryDateAssessment": assessment.entryDateAssessment,
      "entryDateBy": assessment.entryDateBy,
      "appraisedby_designation": assessment.appraisedbyDesignation,
      "recommendappr_designation": assessment.recommendapprDesignation,
      "approvedby_designation": assessment.approvedbyDesignation
    };

    final result = await db.update('bldg_assessment', data,
        where: "bldgapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('Assessment Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

//Land Property Owner

  Future<LandPropertyOwner> createLandOwner(
      LandPropertyOwner landPropertyOwner) async {
    final db = await instance.database;

    final data = {
      // "id": landPropertyOwner.id,
      "assessedById": landPropertyOwner.assessedById,
      "assessedByName": landPropertyOwner.assessedByName,
      "dateCreated": landPropertyOwner.dateCreated,
      "dateModified": landPropertyOwner.dateModified,
      "transCode": landPropertyOwner.transCode,
      "tdn": landPropertyOwner.tdn,
      "pin": landPropertyOwner.pin,
      "cloaNo": landPropertyOwner.cloaNo,
      "dated": landPropertyOwner.dated,
      "surveyNo": landPropertyOwner.surveyNo,
      "lotNo": landPropertyOwner.lotNo,
      "blkNo": landPropertyOwner.blkNo,
      "owner": landPropertyOwner.owner,
      "address": landPropertyOwner.address,
      "telno": landPropertyOwner.telno,
      "tin": landPropertyOwner.tin,
      "adminUser": landPropertyOwner.adminUser,
      "adminTelno": landPropertyOwner.adminTelno,
      "adminAddress": landPropertyOwner.adminAddress,
      "adminTin": landPropertyOwner.adminTin,
      "faasType": landPropertyOwner.faasType
    };
    final id = await db.insert('land_property_owner', data);
    final tempID = await SharedPreferences.getInstance();
    print(landPropertyOwner.copy(id: id).toJson());
    await tempID.setInt('landid', id);
    return landPropertyOwner.copy(id: id);
  }

  Future<List<LandPropertyOwner>> getLandPropertyOwner() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('land_property_owner', orderBy: orderBy);

    return result.map((json) => LandPropertyOwner.fromJson2(json)).toList();
  }

  Future<int> updateLandPropertyOwner(
      id, LandPropertyOwner landPropertyOwner) async {
    final db = await instance.database;
    final data = {
      // "id": landPropertyOwner.id,
      "assessedById": landPropertyOwner.assessedById,
      "assessedByName": landPropertyOwner.assessedByName,
      "dateCreated": landPropertyOwner.dateCreated,
      "dateModified": landPropertyOwner.dateModified,
      "transCode": landPropertyOwner.transCode,
      "tdn": landPropertyOwner.tdn,
      "pin": landPropertyOwner.pin,
      "cloaNo": landPropertyOwner.cloaNo,
      "dated": landPropertyOwner.dated,
      "surveyNo": landPropertyOwner.surveyNo,
      "lotNo": landPropertyOwner.lotNo,
      "blkNo": landPropertyOwner.blkNo,
      "owner": landPropertyOwner.owner,
      "address": landPropertyOwner.address,
      "telno": landPropertyOwner.telno,
      "tin": landPropertyOwner.tin,
      "adminUser": landPropertyOwner.adminUser,
      "adminTelno": landPropertyOwner.adminTelno,
      "adminAddress": landPropertyOwner.adminAddress,
      "adminTin": landPropertyOwner.adminTin,
      "faasType": landPropertyOwner.faasType
    };

    final result = await db
        .update('land_property_owner', data, where: "id = ?", whereArgs: [id]);

    if (result > 0) {
      print('Bldg Owner Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  Future<int> deleteLandPropertyOwner({required int id}) async {
    final db = await instance.database;

    return await db.delete(
      'land_property_owner',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  //Land Location

  Future<LandPropertyLoc> createLandLocation(
      LandPropertyLoc landPropertyLoc) async {
    final db = await instance.database;

    final data = {
      "id": landPropertyLoc.id,
      "landapprDetailsId": landPropertyLoc.landapprDetailsId,
      "assessedById": landPropertyLoc.assessedById,
      "assessedByName": landPropertyLoc.assessedByName,
      "dateCreated": landPropertyLoc.dateCreated,
      "dateModified": landPropertyLoc.dateModified,
      "street": landPropertyLoc.street,
      "municipality": landPropertyLoc.municipality,
      "barangay": landPropertyLoc.barangay,
      "province": landPropertyLoc.province
    };
    print('loc test');
    print(data);
    final id = await db.insert('land_property_location', data);
    final tempID = await SharedPreferences.getInstance();

    await tempID.setInt('landid', id);
    return landPropertyLoc.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getLandPropertyLocation(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_location',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('land_property_location test result');
    print(results);

    return results;
  }

  Future<int> updateLandPropertyLocation(
      id, LandPropertyLoc landPropertyLoc) async {
    final db = await instance.database;
    final data = {
      "id": landPropertyLoc.id,
      "landapprDetailsId": landPropertyLoc.landapprDetailsId,
      "assessedById": landPropertyLoc.assessedById,
      "assessedByName": landPropertyLoc.assessedByName,
      "dateCreated": landPropertyLoc.dateCreated,
      "dateModified": landPropertyLoc.dateModified,
      "street": landPropertyLoc.street,
      "municipality": landPropertyLoc.municipality,
      "barangay": landPropertyLoc.barangay,
      "province": landPropertyLoc.province
    };

    final result = await db.update('land_property_location', data,
        where: "landapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('land_property_location Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  // Land Boundaries

  Future<LandPropertyBoundaries> createLandPropertyBoundaries(
      LandPropertyBoundaries landPropertyBoundaries) async {
    final db = await instance.database;

    final data = {
      "id": landPropertyBoundaries.id,
      "landapprDetailsId": landPropertyBoundaries.landapprDetailsId,
      "assessedById": landPropertyBoundaries.assessedById,
      "assessedByName": landPropertyBoundaries.assessedByName,
      "dateCreated": landPropertyBoundaries.dateCreated,
      "dateModified": landPropertyBoundaries.dateModified,
      "north": landPropertyBoundaries.north,
      "east": landPropertyBoundaries.east,
      "south": landPropertyBoundaries.south,
      "west": landPropertyBoundaries.west,
      "sketch": landPropertyBoundaries.sketch,
    };
    final id = await db.insert('land_property_boundaries', data);
    final tempID = await SharedPreferences.getInstance();
    print(landPropertyBoundaries.copy(id: id).toJson());
    await tempID.setInt('tempid', id);
    return landPropertyBoundaries.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getLandPropertyBoundaries(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_boundaries',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('get land boundary test result');
    print(results);

    return results;
  }

  Future<int> updateLandPropertyBoundaries(
      id, LandPropertyBoundaries landPropertyBoundaries) async {
    final db = await instance.database;
    final data = {
      "id": landPropertyBoundaries.id,
      "landapprDetailsId": landPropertyBoundaries.landapprDetailsId,
      "assessedById": landPropertyBoundaries.assessedById,
      "assessedByName": landPropertyBoundaries.assessedByName,
      "dateCreated": landPropertyBoundaries.dateCreated,
      "dateModified": landPropertyBoundaries.dateModified,
      "north": landPropertyBoundaries.north,
      "east": landPropertyBoundaries.east,
      "south": landPropertyBoundaries.south,
      "west": landPropertyBoundaries.west,
      "sketch": landPropertyBoundaries.sketch,
    };

    final result = await db.update('land_property_boundaries', data,
        where: "landapprDetailsId = ?", whereArgs: [id]);

    if (result > 0) {
      print('land_property_boundaries Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }

  //Land Appraisal

  Future<LandAppr> createLandAppraisal(LandAppr landPropertyAppr) async {
    final db = await instance.database;

    final data = {
      "landapprDetailsId": landPropertyAppr.landapprDetailsId,
      "classification": landPropertyAppr.classification,
      "subClass": landPropertyAppr.subClass,
      "area": landPropertyAppr.area,
      "unitValue": landPropertyAppr.unitValue,
      "baseMarketval": landPropertyAppr.baseMarketval
    };

    print('data');
    print(data);

    final id = await db.insert('land_property_appr', data);
    print(id);

    return landPropertyAppr.copy(id: id);
  }

  Future<List<LandAppr>> readLandPropertyAppraisal() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('land_property_appr', orderBy: orderBy);

    return result.map((json) => LandAppr.fromJson(json)).toList();
  }

  Future<List<Map<String, dynamic>>> getLandPropertyAppraisal(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_appr',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('add edit test result');
    print(results);

    return results;
  }

  Future<int> deleteLandPropertyAppraisal({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'land_property_appr',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  //Land Adjustments

  Future<ValueAdjustments> createValueAdjustments(
      ValueAdjustments adjustments) async {
    final db = await instance.database;

    final data = {
      // "id": adjustments.id,
      "landapprDetailsId": adjustments.landapprDetailsId,
      "baseMarketval": adjustments.baseMarketval,
      "adjustmentFactors": adjustments.adjustmentFactors,
      "adjustment": adjustments.adjustment,
      "valueAdjustment": adjustments.valueAdjustment,
      "marketValue": adjustments.marketValue
    };
    final id = await db.insert('value_adjustments', data);
    return adjustments.copy(id: id);
  }

  Future<List<ValueAdjustments>> readAllValueAdjustments() async {
    final db = await instance.database;
    const orderBy = 'id';
    final result = await db.query('value_adjustments', orderBy: orderBy);
    print('result');
    print(result.toString());

    return result.map((json) => ValueAdjustments.fromJson2(json)).toList();
  }

  Future<List<Map<String, dynamic>>> getValueAdjustments(id) async {
    final db = await instance.database;
    final results = await db.query('value_adjustments',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('land value Adjustments test result');
    print(results);

    return results;
  }

  Future<int> deleteValueAdjustment({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'value_adjustments',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // Land Other Improvements

  Future<OtherImprovements> createOtherImprovements(
      OtherImprovements otherImprovements) async {
    final db = await instance.database;

    final data = {
      "landapprDetailsId": otherImprovements.landapprDetailsId,
      "kindsOfTrees": otherImprovements.kindsOfTrees,
      "subclassAge": otherImprovements.subclassAge,
      "quantity": otherImprovements.quantity,
      "unitValue": otherImprovements.unitValue,
      "baseMarketval": otherImprovements.baseMarketval,
      "noOfProductive": otherImprovements.noOfProductive,
      "noOfNonproductive": otherImprovements.noOfNonproductive,
      "fruitBearing": otherImprovements.fruitBearing
    };
    final id = await db.insert('land_property_other_improvements', data);
    return otherImprovements.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getOtherImprovements(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_other_improvements',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('land other improvement test result');
    print(results);

    return results;
  }

  Future<int> deleteOtherImprovements({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'land_property_other_improvements',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  //Land Property Assessment

  Future<LandPropertyAssessment> createLandPropertyAssessment(
      LandPropertyAssessment assessment) async {
    final db = await instance.database;

    final data = {
      // "id": adjustments.id,
      "landapprDetailsId": assessment.landapprDetailsId,
      "actualUse": assessment.actualUse,
      "marketval": assessment.marketval,
      "assessmentLevel": assessment.assessmentLevel,
      "assessedValue": assessment.assessedValue,
      "totalMarketval": assessment.totalMarketval,
      "totalAssessedval": assessment.totalAssessedval
    };
    final id = await db.insert('land_property_assessment', data);
    return assessment.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getLandPropertyAssessment(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_assessment',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('land_property_assessment test result');
    print(results);

    return results;
  }

  Future<int> deleteLandPropertyAssessment({required int id}) async {
    final db = await instance.database;
    print(id);

    return await db.delete(
      'land_property_assessment',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

// Land Property Sgnatories

  Future<LandExt> createLandPropertySignatories(LandExt landExt) async {
    final db = await instance.database;

    final data = {
      // "id": landExt.id,
      "landapprDetailsId": landExt.landapprDetailsId,
      "assessedById": landExt.assessedById,
      "assessedByName": landExt.assessedByName,
      "dateCreated": landExt.dateCreated,
      "dateModified": landExt.dateModified,
      "taxable": landExt.taxable,
      "exempt": landExt.exempt,
      "qtr": landExt.qtr,
      "yr": landExt.yr,
      "appraisedbyName": landExt.appraisedbyName,
      "appraisedbyDate": landExt.appraisedbyDate,
      "appraisedbyDesignation": landExt.appraisedbyDesignation,
      "recommendapprName": landExt.recommendapprName,
      "recommendapprDate": landExt.recommendapprDate,
      "recommendapprDesignation": landExt.recommendapprDesignation,
      "approvedbyName": landExt.approvedbyName,
      "approvedbyDate": landExt.approvedbyDate,
      "approvedbyDesignation": landExt.approvedbyDesignation,
      "memoranda": landExt.memoranda,
      "swornstatementNo": landExt.swornstatementNo,
      "dateReceived": landExt.dateReceived,
      "entryDateAssessment": landExt.entryDateAssessment,
      "entryDateBy": landExt.entryDateBy,
    };
    final id = await db.insert('land_property_ext', data);
    final tempID = await SharedPreferences.getInstance();
    print(landExt.copy(id: id).toJson());
    await tempID.setInt('tempid', id);
    return landExt.copy(id: id);
  }

  Future<List<Map<String, dynamic>>> getLandPropertySignature(id) async {
    final db = await instance.database;
    final results = await db.query('land_property_ext',
        where: "landapprDetailsId = ?", whereArgs: [id]);
    print('land_property_ext test result');
    print(results);

    return results;
  }

  Future<int> updateLandPropertySignature(id, LandExt landExt) async {
    final db = await instance.database;
    final data = {
      // "id": landPropertyOwner.id,
      "landapprDetailsId": landExt.landapprDetailsId,
      "assessedById": landExt.assessedById,
      "assessedByName": landExt.assessedByName,
      "dateCreated": landExt.dateCreated,
      "dateModified": landExt.dateModified,
      "taxable": landExt.taxable,
      "exempt": landExt.exempt,
      "qtr": landExt.qtr,
      "yr": landExt.yr,
      "appraisedbyName": landExt.appraisedbyName,
      "appraisedbyDate": landExt.appraisedbyDate,
      "recommendapprName": landExt.recommendapprName,
      "recommendapprDate": landExt.recommendapprDate,
      "approvedbyName": landExt.approvedbyName,
      "approvedbyDate": landExt.approvedbyDate,
      "memoranda": landExt.memoranda,
      "swornstatementNo": landExt.swornstatementNo,
      "dateReceived": landExt.dateReceived,
      "entryDateAssessment": landExt.entryDateAssessment,
      "entryDateBy": landExt.entryDateBy,
    };

    final result = await db
        .update('land_property_ext', data, where: "id = ?", whereArgs: [id]);

    if (result > 0) {
      print('Land Signatory Updated Successfully');
    } else {
      throw Exception('Failed to update the Journal.');
    }
    return result;
  }
}
