<?php
ini_set('display_errors', 1);

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'admin_api/institution_management/function/institution_function.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;

$postdata = $_POST;

if (!isset($postdata['institution_code']) or !checkIfIssetAndNotEmpty($postdata['institution_code']) or
    !isset($postdata['institution_name']) or !checkIfIssetAndNotEmpty($postdata['institution_name']) or
    !isset($postdata['address']) or !checkIfIssetAndNotEmpty($postdata['address']) or
    !isset($postdata['contact_number']) or !checkIfIssetAndNotEmpty($postdata['contact_number']) or
    !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature'])  or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['jwt_token']) or !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$created_by = $jwt_validate->data->username;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$userid = $jwt_validate->data->id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin']);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$company_id = (isset($postdata['company_id']) and !empty($postdata['company_id'])) ? ($postdata['company_id']) : null;
$institution_code = ucwords(strtolower(trim($postdata['institution_code'])));
$institution_code = strtoupper($institution_code);
$institution_name = ucwords(strtolower(trim($postdata['institution_name'])));
$address = trim($postdata['address']);
$contact_number = trim($postdata['contact_number']);
$email = trim($postdata['email']);
$website = (isset($postdata['website']) and !empty($postdata['website'])) ? trim($postdata['website']) : null;
$tagline = (isset($postdata['tagline']) && !empty($postdata['tagline']))
    ? (strtoupper($postdata['tagline']) === $postdata['tagline']
        ? trim($postdata['tagline'])
        : ucwords(strtolower(trim($postdata['tagline']))))
    : null;

// $tagline = strtolower($tagline);
$institution_name_abbreviation = (isset($postdata['institution_name_abbreviation']) and !empty($postdata['institution_name_abbreviation'])) ? trim($postdata['institution_name_abbreviation']) : null;

$date_added = date('Y-m-d');
$unique_institution_id = (isset($postdata['unique_institution_id']) and !empty($postdata['unique_institution_id'])) ? trim($postdata['unique_institution_id']) : null;
$logo = (isset($_FILES['logo']) and !empty($_FILES['logo'])) ? $_FILES['logo'] : null;

//white label
$white_label_url = (isset($postdata['white_label_url']) and !empty($postdata['white_label_url'])) ? trim($postdata['white_label_url']) : null;
$white_label_email = (isset($postdata['white_label_email']) and !empty($postdata['white_label_email'])) ? trim($postdata['white_label_email']) : null;
$white_label_message_header = (isset($postdata['white_label_message_header']) and !empty($postdata['white_label_message_header'])) ? trim($postdata['white_label_message_header']) : null;
$white_label_app_name = (isset($postdata['white_label_app_name']) and !empty($postdata['white_label_app_name'])) ? trim($postdata['white_label_app_name']) : null;


function capitalizeAddress($address)
{
    // Capitalize the first letter of each word in the address
    $address = ucwords($address);

    return $address;
}

$address = capitalizeAddress($address);

if (!CheckAddressValidation($address)) {
    //eg House Name, Street Name
    errorreturn('Invalid Address');
}

if (!CheckCode($institution_code)) {
    //eg House Name, Street Name
    errorreturn('Invalid Institution Code');
}


if (strlen($contact_number) != 13 or $contact_number <= 0) {
    errorreturn('Enter valid 12 digit mobile number ' . $contact_number);
}
if (!CheckEMailIsValidOrNot($email)) {
    errorreturn('Enter valid Email Id');
}

if ($website != null) {
    if (!checkWebsiteUrl($website)) {
        errorreturn('Invalid Website URL.');
    }
}
if (!CheckAddressValidation($address)) { // for english chars + numbers only
    //eg House Name, Street Name
    errorreturn('Invalid institutions address');
}

if ($postdata['function_type'] == "create_institute") {


    //validation for institution
    $res = $conn_rjllearning->prepare("SELECT institution_code FROM institutions WHERE institution_name = ? or institution_code= ? ");
    $res->execute(array($institution_name, $institution_code));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("This Institution name or Code already exists.");
    }



    if ($logo == null) {

        $logo = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');
        $directoryPathMain =  "user_uploads/" . $workspace_id .  "/institutions_attachments/" . $currentYear . "/" . $currentMonth . "/";
        $file_name = $_FILES['logo']['name'];
        $fileTmpName = $_FILES['logo']["tmp_name"];
        $fileSize = $_FILES['logo']["size"];
        $fileType = $_FILES['logo']["type"];
        $fileError = $_FILES['logo']["error"];
        $file_extension = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }


    try {

        $sql = "INSERT INTO institutions(workspace_id,institution_code,company_id,institution_name,address,contact_number,email,website,tagline,institution_name_abbreviation,unique_institution_id,date_added,added_by,time_created,logo,white_label_url,white_label_email,white_label_message_header,white_label_app_name,status)
            VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning->prepare($sql);
        $stmt->execute(array($workspace_id, $institution_code, $company_id, $institution_name, $address, $contact_number, $email, $website, $tagline, $institution_name_abbreviation, $unique_institution_id, $date_added, $created_by, time(), null,$white_label_url,$white_label_email,$white_label_message_header,$white_label_app_name, '1'));
        $institution_id = $conn_rjllearning->lastInsertId();

        // Creating Transport Ledger Group
        createTransportEntry($conn_rjllearning_specific, $institution_id, $created_by);

        // Creating Other Expenses Ledger Group
        createOtherExpense($conn_rjllearning_specific, $institution_id, $created_by);
        
        createStudentRegistrationExpense($conn_rjllearning_specific, $institution_id, $created_by);

        if ($logo !=  null) {
            $image_name = "logo_" . $institution_id . "." . $file_extension; // Define the image name dynamically
            $logo_path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $logo, $logo_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $result = $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $image_name,
                'SourceFile' => $fileTmpName,
                'ACL' => 'public-read' // Make the file publicly accessible
            ]);

            // Get the public URL of the uploaded logo
            $publicUrl = $result['ObjectURL'];

            // Store the file path and original name as JSON data
            $institution_logo = json_encode(array("filepath" => $logo_path, "original_name" => $file_name, "path" => $publicUrl));
            $sql_logo = "UPDATE institutions SET logo = ? WHERE id= ? and workspace_id = ?";
            $conn_rjllearning->prepare($sql_logo)->execute(array($institution_logo, $institution_id, $workspace_id));
        }
        successreturn(array('institute_id' => $institution_id, 'successmsg' => 'Successfully institution added.'));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else if ($postdata['function_type'] == "alter_institution") {
    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
        errorreturn('Error in updating the institution.');
    } else {
        $id = $postdata['institution_id'];
    }


    $remove_bool  = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0; //if logo_remove is 1 then user can delete logo

    $sql_institutions = $conn_rjllearning->prepare("SELECT logo FROM institutions WHERE id = ?");
    $sql_institutions->execute(array($id));
    $result = $sql_institutions->fetchAll();
    if (count($result) == 1) {

        $existing_logo = $result[0]['logo'];
    } else {

        errorreturn("Institute Not Found.");
    }
    // validate from branch if existing super admins 
    $res = $conn_rjllearning->prepare("SELECT id FROM institutions WHERE id != ? and  institution_name=?");
    $res->execute(array($id, $institution_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Institution Name or code already exists");
    }


    if (($remove_bool == 1 or $logo != null) and $existing_logo != null) {
        // $sql_image = $conn_rjllearning->prepare("SELECT logo FROM  institutions  where id = ? and workspace_id = ?");
        // $sql_image->execute(array($id, $workspace_id));
        // $result_image = $sql_image->fetchAll();

        // if (count($result_image) == 1) {

        //     $existing_logo = $result_image[0]['logo'];
            $data_attachment = json_decode($existing_logo, true);

            $filePath = $data_attachment['filepath'];
            

            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning, $id, $filePath, null, null);
            $sql = "UPDATE institutions SET logo = ? WHERE id = ? and workspace_id = ?";
            $conn_rjllearning->prepare($sql)->execute(array(null, $id, $workspace_id));
        // 
    }
   

    if ($remove_bool == 1 and $logo !=  null) {

        if ($existing_logo === null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryPathMain =  "user_uploads/" . $workspace_id .  "/institutions_attachments/" . $currentYear . "/" . $currentMonth . "/";
        } else {
            $directoryPathMain = substr($filePath, 0, strrpos($filePath, '/') + 1);
        }
        $file_name = $_FILES['logo']['name'];
        $fileTmpName = $_FILES['logo']["tmp_name"];
        $fileSize = $_FILES['logo']["size"];
        $fileType = $_FILES['logo']["type"];
        $fileError = $_FILES['logo']["error"];
        $file_extension = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    $sql = "UPDATE institutions SET company_id=?,institution_name=?,address=?,contact_number=?,email=?,website=?,tagline=?,institution_name_abbreviation=?,unique_institution_id= ?,white_label_url = ?,white_label_email =?,white_label_message_header =?,white_label_app_name =? WHERE id=? and workspace_id= ? ";
    $conn_rjllearning->prepare($sql)->execute(array(
        $company_id,
        $institution_name,
        $address,
        $contact_number,
        $email,
        $website,
        $tagline,
        $institution_name_abbreviation,
        $unique_institution_id,
        $white_label_url,
        $white_label_email,
        $white_label_message_header,
        $white_label_app_name,
        $id,
        $workspace_id
    ));

    if ($remove_bool == 1 and $logo !=  null) {

        $image_name = "logo_" . $id . "." . $file_extension; // Define the image name dynamically
        $logo_path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $logo, $logo_path, $multiple_files_bool = false, $multiple_file_index = 0);
        $result = $s3_learning_bucket->putObject([
            'Bucket' => $learning_bucketName,
            'Key' => $image_name,
            'SourceFile' => $fileTmpName,
            'ACL' => 'public-read' // Make the file publicly accessible
   
        ]);

        // Get the public URL of the uploaded logo
        $publicUrl = $result['ObjectURL'];
        // errorreturn($publicUrl);

        // Store the file path and original name as JSON data
        $institution_logo = json_encode(array("filepath" => $logo_path, "original_name" => $file_name, "path" => $publicUrl));

        $sql_logo = "UPDATE institutions SET logo = ? WHERE id= ? and workspace_id = ?";
        $conn_rjllearning->prepare($sql_logo)->execute(array($institution_logo, $id, $workspace_id));
        
        // if (!empty($cloudFrontDomain)) {
        // $success=invalidateCloudFrontCache($cloudFrontDomain, $image_name, $learning_region, $learning_aws_access, $learning_aws_secret_accesskey, $id);
       
        // }
    }

    successreturn("Updated institution Successfully");
}
