<?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.'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources.'includes/specific_db_config.php';
//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';

try {
    $conn_rjllearning->beginTransaction();

    $institution_id = 2; // Replace with actual institution_id
    $workspace_id = 4;   // Replace with actual workspace_id
    
    $login_url = "https://rejoicelearning.in/login";
    $userid = '4';
    $role='superadmin';
    $specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
    if (!$specific_db_name) {
        errorreturn('Access denied.');
    } else {
        $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
    }

    // Fetch unsent records including branch_id
    $stmt = $conn_rjllearning->prepare("
        SELECT id, username, password, name, admission_no, userid, type, branch_id 
        FROM users_unencrypted_cred 
        WHERE status = 0
    ");
    $stmt->execute();
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($records as $row) {
        $username = $row['username'];
        $password = $row['password'];
        $name = $row['name'];
        $admission_no = $row['admission_no'];
        $user_id = $row['userid'];
        $type = $row['type'];
        $branch_id = $row['branch_id']; // ✅ Using branch_id

        $subject = 'Welcome to ' . $web_app_title;
        $message = "<h1>Welcome To <span class='web_app_title'>$web_app_title</span></h1>
            <p>Thank you for creating a user account on $web_app_title. You can now sign in at $login_url or <a href='$login_url'>Click Here</a>.</p>
            <p>
            Name : <b>$name</b><br>
            Amission number : <b>$admission_no</b><br>
            Password : <b>$password</b>
            Username : <b>$username</b><br>
            </p>";

        try {
            sendMailTemplate1(
                $conn_rjllearning,
                'Rejoice Learning <no-reply@rejoicelearning.in>',
                $email,
                $subject,
                $message,
                $workspace_id,
                $institution_id,
                $branch_id,
                null,
                null,
                'real_time'
            );

            // Mark as sent
            $update = $conn_rjllearning->prepare("UPDATE users_unencrypted_cred SET status = 1 WHERE id = ?");
            $update->execute([$row['id']]);
        } catch (Exception $e) {
            // Mark as failed
            $update = $conn_rjllearning->prepare("UPDATE users_unencrypted_cred SET status = -1 WHERE id = ?");
            $update->execute([$row['id']]);
        }
    }

    // Delete successful records
    $delete = $conn_rjllearning->prepare("DELETE FROM users_unencrypted_cred WHERE status = 1");
    $delete->execute();

    $conn_rjllearning->commit();

    echo json_encode([
        'status' => true,
        'message' => 'Emails sent and processed records deleted.'
    ]);

} catch (Exception $e) {
    $conn_rjllearning->rollBack();
    echo json_encode([
        'status' => false,
        'message' => 'Failed: ' . $e->getMessage()
    ]);
}
