<?php 
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'None'
]);

session_start();
$domainName = $_REQUEST['DOMAIN'];
$refreshId = $_REQUEST['REFRESH_ID'];
/*$clientId = 'local.6805d354e66728.30940389';
$clientSecret = 'FqYfld1y0UgsdMiUK3AEepPmdAj1JXldgNbYPEcyguU2gORqm7';*/
$clientId = 'app.6814bcb5627763.66194477';
$clientSecret = 'RMsbzWZSuGq7t98LVA0WgrgoHnyXv1ZPsY3VYaYUOJ32nej2up';

require_once './src/Database.php';
$conn = Database::getInstance();

function getNewAccessToken($domainName, $clientId, $clientSecret, $refreshToken) {
    $url = "https://{$domainName}/oauth/token/"
         . "?grant_type=refresh_token"
         . "&client_id=" . urlencode($clientId)
         . "&client_secret=" . urlencode($clientSecret)
         . "&refresh_token=" . urlencode($refreshToken);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

function getBitrix24UsersByDomain($conn, $domainName) {
    $stmt = $conn->prepare("SELECT * FROM bitrix24_users WHERE domain_name = ?");
    $stmt->bind_param("s", $domainName);
    $stmt->execute();
    $result = $stmt->get_result();

    $users = [];
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }

    $stmt->close();
    return $users;
}

$firstForm = "";
$users = getBitrix24UsersByDomain($conn, $domainName);
if (isset($users[0]['domain_name'])) {
    $firstForm= $users[0]['first_user'];
    $responsible = $users[0]['responsible_id'];
    $projectId   = $users[0]['Project_id'];
    $folderId    = $users[0]['folder_id'];
    $bitrix24UserId = $users[0]['id'];

    $_SESSION['responsible_id'] = $responsible;
    $_SESSION['project_id']     = $projectId;
    $_SESSION['folder_id']      = $folderId;
    $_SESSION['bitrix_user_id'] = $bitrix24UserId;

} else {
    $response = getNewAccessToken($domainName, $clientId, $clientSecret, $refreshId);
    $tokenResponse = json_decode($response, true); 
    $accessToken = $tokenResponse['access_token'];
    $refreshToken = $tokenResponse['refresh_token'];
    $client_endpoint = $tokenResponse['client_endpoint'];
    $responsible = $tokenResponse['user_id'];

    // Insert only domain_name into bitrix24_users
    $sqlUser = "INSERT INTO bitrix24_users (domain_name) VALUES (?)";
    $stmtUser = $conn->prepare($sqlUser);
    $stmtUser->bind_param("s", $domainName);
    $stmtUser->execute();
    $bitrix24_user_id = $stmtUser->insert_id;

    // Insert token info as before
    $sqlToken = "INSERT INTO bitrix24_token (refresh_token, acsess_token, bitrix24_user_id, domain, client_endpoint, respo_id) 
                 VALUES (?, ?, ?, ?, ?, ?)";
    $stmtToken = $conn->prepare($sqlToken);
    $stmtToken->bind_param("ssisss", $refreshToken, $accessToken, $bitrix24_user_id, $domainName, $client_endpoint, $responsible);
    $stmtToken->execute();

    $stmtUser->close();
    $stmtToken->close();
    $conn->close();
}

if (!isset($_SESSION['bitrix_user_id'])) {
    header("Location: https://integrations.notamedia.co.in/helpdesk-core-php/consent.php");
    exit;
}

// At this point, session is set. Now check your condition:
if (!empty($firstForm)) {
    sleep(5); // Delay if $firstForm is not null

    // Redirect to dashboard after delay
    header("Location: https://integrations.notamedia.co.in/helpdesk-core-php/dashboard.php");
    exit;
} else {
     if(!$domainName){
          echo "❌ Access Denied: Only Bitrix24 is allowed to access this script.";
           exit();
     }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Helpdesk - Login</title>
  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="css/sb-admin.css" rel="stylesheet">
</head>
<body class="bg-light">
  <div class="container">
    <div class="card card-login mx-auto mt-5">
      <div class="card-header text-center font-weight-bold">For initial application setup</div>
      <div class="card-body">
        <form method="POST" action="form-data.php">
          <input type="hidden" name="domain" value="<?=$domainName?>">
          <div class="form-group">
            <label for="inputName">Name</label>
            <input type="text" name="name" class="form-control" autofocus>
          </div>
          <div class="form-group">
            <label for="inputEmail">Email address</label>
            <input type="text" name="email" class="form-control">
          </div>
          <div class="form-group">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control">
          </div>
          <div class="form-group">
            <label for="inputCompany">Company Name</label>
            <input type="text" name="company" class="form-control">
          </div>
          <div class="form-group">
            <label for="inputSupportEmail">Support Email</label>
            <input type="text" name="support-email" class="form-control">
          </div>
          <button type="submit" name="submit" class="btn btn-primary btn-block">Submit</button>
        </form>     
      </div>
    </div>
  </div>
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
</body>
</html>
<?php
}
?>
