<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);  

include './assets/functions.php';
include './settings/settings.php';
include './settings/config.php';
include_once './settings/translations/translations_US.php';
include_once './settings/systemfirmware.php';

$pdo = dbConnect($dbname);
$sql = 'SELECT * FROM contracts WHERE status = 1';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($messages as $message){
  //Calculate contract end date
  $end_date = date('Y-m-d', strtotime('+'.$message['duration'].' months', strtotime($message['start_date'])));

  //Validate if contract end date is in the past change contact status to closed and set users to not active
  if (date("Y-m-d") > $end_date){
    //Contract expired -> change status to closed (2)
    $sql = 'UPDATE contracts SET status = ? WHERE rowID = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([2,$message['rowID']]);
    
    //CHECK FOR ASSIGNED USER END SET SERVICE TO INACTIVE
    foreach (json_decode($message['assigned_users']) as $user_assigned){

      //CALL TO API FOR General information
      $clientsecret = createCommunicationToken($_SESSION['userkey']);
      $responses = ioApi('/v2/users/username='.$user_assigned,'',$clientsecret);

      if (!empty($responses)){
        $response = json_decode($responses,true);
        //If response is not null update the service flag of the user
        if (count($response) != 0){
          $id_exist_user = $response[0]['id'];
          $sql = 'UPDATE users SET service = ? WHERE id = ? ';
          $stmt = $pdo->prepare($sql);
          //Remove serviceflag from user when status is Closed
          $stmt->execute(['',$id_exist_user]);
        }
      }
    }
  }
} 