<?php

function create_Salarydetails_table($dynamoDbClient, $dynamoDB_table_name)
{
    $tableName = $dynamoDB_table_name;

    try {
        // First check if table exists
        $existingTables = $dynamoDbClient->listTables();
        if (in_array($tableName, $existingTables['TableNames'])) {
            return ['status' => 'success', 'message' => 'Table already exists'];
        }

        $params = [
            'TableName' => $tableName,
            'KeySchema' => [
                [
                    'AttributeName' => 'id',
                    'KeyType' => 'HASH'  // Partition key
                ]
            ],
            'AttributeDefinitions' => [
                [
                    'AttributeName' => 'id',
                    'AttributeType' => 'N'
                ],
                [
                    'AttributeName' => 'workspace_id',
                    'AttributeType' => 'N'
                ],
                [
                    'AttributeName' => 'institution_id',
                    'AttributeType' => 'N'
                ],
                [
                    'AttributeName' => 'branch_id',
                    'AttributeType' => 'N'
                ]
                // Removed salary_data since it's not used in any key schema
            ],
            'GlobalSecondaryIndexes' => [
                [
                    'IndexName' => 'WorkspaceIndex',
                    'KeySchema' => [
                        [
                            'AttributeName' => 'workspace_id',
                            'KeyType' => 'HASH'
                        ]
                    ],
                    'Projection' => [
                        'ProjectionType' => 'ALL'
                    ],
                    'ProvisionedThroughput' => [
                        'ReadCapacityUnits' => 5,
                        'WriteCapacityUnits' => 5
                    ]
                ],
                [
                    'IndexName' => 'InstitutionBranchIndex',
                    'KeySchema' => [
                        [
                            'AttributeName' => 'institution_id',
                            'KeyType' => 'HASH'
                        ],
                        [
                            'AttributeName' => 'branch_id',
                            'KeyType' => 'RANGE'
                        ]
                    ],
                    'Projection' => [
                        'ProjectionType' => 'ALL'
                    ],
                    'ProvisionedThroughput' => [
                        'ReadCapacityUnits' => 5,
                        'WriteCapacityUnits' => 5
                    ]
                ]
            ],
            'ProvisionedThroughput' => [
                'ReadCapacityUnits' => 5,
                'WriteCapacityUnits' => 5
            ]
        ];

        $result = $dynamoDbClient->createTable($params);

        // Wait for table to be created with enhanced error handling
        try {
            $dynamoDbClient->waitUntil('TableExists', [
                'TableName' => $tableName,
                '@waiter' => [
                    'delay' => 5,
                    'maxAttempts' => 20
                ]
            ]);
        } catch (AwsException $waiterException) {
            return [
                'status' => 'error',
                'message' => 'Table creation succeeded but waiter failed: ' . $waiterException->getMessage()
            ];
        }

        return [
            'status' => 'success',
            'message' => 'Table created successfully with indexes',
            'details' => [
                'tableName' => $tableName,
                'indexes' => ['WorkspaceIndex', 'InstitutionBranchIndex'],
                'capacity' => [
                    'read' => 5,
                    'write' => 5
                ]
            ]
        ];
    } catch (AwsException $e) {
        return [
            'status' => 'error',
            'message' => $e->getMessage(),
            'errorCode' => $e->getAwsErrorCode()
        ];
    }
}

function insert_salary_Data_to_dynamoDB($dynamoDbClient, $salaryData, $institution_id, $branch_id, $workspace_id, $dynamoDB_table_name)
{
    $tableName = $dynamoDB_table_name;

    try {
        // Generate a unique ID for this batch
        $id = time() . rand(1000, 9999);
        
        $convertNumber = function($value) {
            if (is_string($value) && strpos($value, ',') !== false) {
                return (float)str_replace(',', '', $value);
            }
            return (float)$value;
        };

        // Prepare faculty records using foreach
        $facultyRecords = [];
        foreach ($salaryData as $salary) {
            $facultyRecords[] = [
                'faculty_id' => (int)$salary['faculty_id'],
                'name' => $salary['name'],
                'designation' => $salary['designation'],
                'role' => $salary['role'],
                'basic_salary' => $convertNumber($salary['basic_salary']),
                'per_day_salary' => $convertNumber($salary['per_day_salary']),
                'working_days' => (int)$salary['working_days'],
                'present_days' => (int)$salary['present_days'],
                'half_days' => (float)$salary['half_days'],
                'absent_days' => (int)$salary['absent_days'],
                'leave_days' => (int)$salary['leave_days'],
                'allowed_leaves' => (float)$salary['allowed_leaves'],
                'deduction_leaves' => (float)$salary['deduction_leaves'],
                'leave_deduction' => $convertNumber($salary['leave_deduction']),
                'absent_days_salary_cut' => $convertNumber($salary['absent_days_salary_cut']),
                'gross_salary' => $convertNumber($salary['gross_salary']),
                'total_deductions' => $convertNumber($salary['total_deductions']),
                'net_salary' => $convertNumber($salary['net_salary']),
                'salary_components' => array_map(function($val) use ($convertNumber) {
                    return $convertNumber($val);
                }, $salary['salary_components'])
            ];
        }

        // Create DynamoDB item
        $item = [
            'id' => ['N' => (string)$id],
            'workspace_id' => ['N' => (string)$workspace_id],
            'institution_id' => ['N' => (string)$institution_id],
            'branch_id' => ['N' => (string)$branch_id],
            'salary_data' => ['S' => json_encode([
                'faculty_records' => $facultyRecords
            ])],
        ];

        // Single put operation
        $dynamoDbClient->putItem([
            'TableName' => $tableName,
            'Item' => $item
        ]);

        return [
            'status' => 'success',
            'message' => 'Salary data stored successfully',
            'batch_id' => $id,
            'faculty_count' => count($facultyRecords)
        ];
    } catch (AwsException $e) {
        return [
            'status' => 'error',
            'message' => 'Failed to store payroll data',
            'error' => $e->getMessage(),
            'error_code' => $e->getAwsErrorCode()
        ];
    }
}

// function get_Salary_Data_dynamoDB($dynamoDbClient, $dynamoDB_table_name, $institution_id, $branch_id) {
//     try {
//         $params = [
//             'TableName' => $dynamoDB_table_name,
//             'IndexName' => 'InstitutionBranchIndex',
//             'KeyConditionExpression' => 'institution_id = :inst_id AND branch_id = :br_id',
//             'ExpressionAttributeValues' => [
//                 ':inst_id' => ['N' => (string)$institution_id],
//                 ':br_id' => ['N' => (string)$branch_id]
//             ],
//             // Now including workspace_id in the projection
//             'ProjectionExpression' => 'id, workspace_id, institution_id, branch_id, salary_data'
//         ];

//         $result = $dynamoDbClient->query($params);

//         // Process items to include workspace_id
//         $items = [];
//         foreach ($result['Items'] as $item) {
//             $items[] = [
//                 'id' => $item['id']['N'],
//                 'workspace_id' => $item['workspace_id']['N'], // Now included
//                 'institution_id' => $item['institution_id']['N'],
//                 'branch_id' => $item['branch_id']['N'],
//                 'salary_data' => json_decode($item['salary_data']['S'], true)
//             ];
//         }

//         return [
//             'status' => 'success',
//             'data' => $items,
//             'count' => count($items)
//         ];

//     } catch (AwsException $e) {
//         return [
//             'status' => 'error',
//             'message' => $e->getMessage(),
//             'errorCode' => $e->getAwsErrorCode()
//         ];
//     }
// }

function get_Salary_Data_dynamoDB(
    $dynamoDbClient, 
    $dynamoDB_table_name, 
    $institution_id, 
    $branch_id,
    $limit = 10
) {
    try {
        $params = [
            'TableName' => $dynamoDB_table_name,
            'IndexName' => 'InstitutionBranchIndex',
            'KeyConditionExpression' => 'institution_id = :inst_id AND branch_id = :br_id',
            'ExpressionAttributeValues' => [
                ':inst_id' => ['N' => (string)$institution_id],
                ':br_id' => ['N' => (string)$branch_id]
            ],
            'ProjectionExpression' => 'id, workspace_id, institution_id, branch_id, salary_data',
            'Limit' => $limit
        ];

        $result = $dynamoDbClient->query($params);
        
        if (empty($result['Items'])) {
            errorreturn("No record found");
        }

        $items = [];
        foreach ($result['Items'] as $item) {
            $items[] = [
                'id' => $item['id']['N'],
                'workspace_id' => $item['workspace_id']['N'],
                'institution_id' => $item['institution_id']['N'],
                'branch_id' => $item['branch_id']['N'],
                'salary_data' => json_decode($item['salary_data']['S'], true)
            ];
        }

        return [
            'total_rows' => count($items),
            'salary_data_info' => $items
        ];

    } catch (AwsException $e) {
        return [
            'status' => 'error',
            'message' => $e->getMessage(),
            'errorCode' => $e->getAwsErrorCode()
        ];
    }
}

function get_Salary_Data_ById($dynamoDbClient, $dynamoDB_table_name, $institution_id, $id) {
    try {
        $params = [
            'TableName' => $dynamoDB_table_name,
            'IndexName' => 'InstitutionIdIndex',
            'KeyConditionExpression' => 'id = :id AND institution_id = :inst_id',
            'ExpressionAttributeValues' => [
                ':inst_id' => ['N' => (string)$institution_id],
                ':id' => ['N' => (string)$id]
            ],
            'ProjectionExpression' => 'id, workspace_id, institution_id, branch_id, salary_data'
        ];

        $result = $dynamoDbClient->query($params);

        if (empty($result['Items'])) {
            errorreturn("No record found with the specified ID and institution");
        }

        $item = $result['Items'][0];
        $salaryData = json_decode($item['salary_data']['S'], true);
        
        if (isset($salaryData['faculty_records']) && is_array($salaryData['faculty_records'])) {
            foreach ($salaryData['faculty_records'] as &$record) {
                $floatFields = [
                    'basic_salary', 'per_day_salary', 'leave_deduction',
                    'absent_days_salary_cut', 'gross_salary', 'total_deductions', 'net_salary'
                ];
                
                foreach ($floatFields as $field) {
                    if (isset($record[$field])) {
                        $record[$field] = (float)number_format((float)$record[$field], 2, '.', '');
                    }
                }
                
                // Format salary components if they exist
                if (isset($record['salary_components']) && is_array($record['salary_components'])) {
                    foreach ($record['salary_components'] as &$value) {
                        $value = (float)number_format((float)$value, 2, '.', '');
                    }
                }
            }
        }
        
        $salaryRecord = [
            'id' => $item['id']['N'],
            'workspace_id' => $item['workspace_id']['N'],
            'institution_id' => $item['institution_id']['N'],
            'branch_id' => $item['branch_id']['N'],
            'salary_data' => $salaryData
        ];

        return $salaryRecord;

    } catch (AwsException $e) {
        return [
            'status' => 'error',
            'message' => $e->getMessage(),
            'errorCode' => $e->getAwsErrorCode()
        ];
    }
}

// function addInstitutionIdIndex($dynamoDbClient, $tableName)
// {
//     try {
//         $params = [
//             'TableName' => $tableName,
//             'AttributeDefinitions' => [
//                 [
//                     'AttributeName' => 'institution_id',
//                     'AttributeType' => 'N'
//                 ],
//                 [
//                     'AttributeName' => 'id',
//                     'AttributeType' => 'N'
//                 ]
//             ],
//             'GlobalSecondaryIndexUpdates' => [
//                 [
//                     'Create' => [
//                         'IndexName' => 'InstitutionIdIndex',
//                         'KeySchema' => [
//                             [
//                                 'AttributeName' => 'institution_id',
//                                 'KeyType' => 'HASH'
//                             ],
//                             [
//                                 'AttributeName' => 'id',
//                                 'KeyType' => 'RANGE'
//                             ]
//                         ],
//                         'Projection' => [
//                             'ProjectionType' => 'ALL'
//                         ],
//                         'ProvisionedThroughput' => [
//                             'ReadCapacityUnits' => 5,
//                             'WriteCapacityUnits' => 5
//                         ]
//                     ]
//                 ]
//             ]
//         ];

//         $result = $dynamoDbClient->updateTable($params);

//         // Wait until the index is active
//         $dynamoDbClient->waitUntil('TableExists', [
//             'TableName' => $tableName,
//             '@waiter' => [
//                 'delay' => 5,
//                 'maxAttempts' => 20
//             ]
//         ]);

//         return [
//             'status' => 'success',
//             'message' => 'InstitutionIdIndex created successfully'
//         ];
//     } catch (AwsException $e) {
//         return [
//             'status' => 'error',
//             'message' => $e->getMessage(),
//             'errorCode' => $e->getAwsErrorCode()
//         ];
//     }
// }



