<?php

error_Reporting(E_ALL);
ini_set('display_errors', 1);

//header('Content-Type: text/html; charset=utf-8');
include_once "../../config.php";
include_once "../../database1.php";


//date_default_timezone_set('UTC');

class upload extends database{
 

	public function sceduleCron($data)
	{
      return $this->insert('tb_cron', $data);
	}
}

if(!isset($_FILES["file"]["name"]))
{
	http_response_code(404);
	echo json_encode(array('error_text' => 'File Not Found'));
	exit;
}

$target_dir = "../../uploads/cron/";
$newName = rand(100000,999999) . '_' . date('dmyHis') . '_' . basename($_FILES["file"]["name"]);
$target_file = $target_dir . $newName;
$message = '';
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    $message.="Sorry, file already exists.";
}
// Check file size
if ($_FILES["file"]["size"] > 500000000) {
    $message.="Sorry, your file is too large.";
}
// Allow certain file formats
if($imageFileType != "csv") {
    $message.="Sorry, only CSV files are allowed.";
}
// Check if $uploadOk is set to 0 by an error
if (trim($message) != '') {
    http_response_code(400);
    echo json_encode(['error_text' => $message]);
    exit;
// if everything is ok, try to upload file
} else {
	
	$fileError = '';
	$count = 0;
  $tmpName = $_FILES['file']['tmp_name'];
  
  if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {

      $obj = new upload();
      $data['cl_type'] = 'Update Stock and Price in Bulk';
      $data['cl_scheduled'] = date("Y-m-d H:i:s", strtotime('+2 minutes'));
      $data['cl_file'] = DOMAIN . '/uploads/cron/' . $newName;
      $data['cl_original_file_name'] = $_FILES["file"]["name"];

      $cronID = $obj->sceduleCron($data);
    //  $output = shell_exec('crontab -l');
      exec('/usr/bin/crontab -l 2>/dev/null', $current);
      
      
      $newJob = date('i', strtotime($data['cl_scheduled'])) . ' ' .
          date('H', strtotime($data['cl_scheduled'])) . ' ' .
          date('d', strtotime($data['cl_scheduled'])) . ' ' .
          date('m', strtotime($data['cl_scheduled'])) . ' * curl ' .
          DOMAIN . '/ajax/cron/execute/execute_update_stock_bulk_csv?id=' . $cronID;

// Step 3: Avoid duplicates (optional but recommended)
if (!in_array($newJob, $current)) {
    $current[] = $newJob;
}

      
      

    //  echo $output . date('i', strtotime($data['cl_scheduled'])) . ' ' . date('H', strtotime($data['cl_scheduled'])) . ' ' . date('d', strtotime($data['cl_scheduled'])) . ' ' . date('m', strtotime($data['cl_scheduled'])) . ' * curl ' . DOMAIN . '/ajax/cron/execute/execute_update_stock_bulk_csv?id=' . $cronID . PHP_EOL;
   
     /* file_put_contents('/tmp/crontab.txt', $output . date('i', strtotime($data['cl_scheduled'])) . ' ' . date('H', strtotime($data['cl_scheduled'])) . ' ' . date('d', strtotime($data['cl_scheduled'])) . ' ' . date('m', strtotime($data['cl_scheduled'])) . ' * curl ' . DOMAIN . '/ajax/cron/execute/execute_update_stock_bulk_csv?id=' . $cronID . PHP_EOL);*/
     
     
     
     file_put_contents('/tmp/crontab_user.txt', implode(PHP_EOL, $current) . PHP_EOL);
     
     exec('/usr/bin/crontab /tmp/crontab_user.txt');

     // echo exec('crontab /tmp/crontab.txt', $output, $return);
      
      
//exec('/usr/bin/crontab -l 2>&1', $output, $return);

//var_dump($return);
//var_dump($output);
    

        http_response_code(200);
        echo json_encode(['message' => 'Update Stock and Price in Bulk is sceduled on ' . $data['cl_scheduled'], 'link' => '/uploads/cron/' . $newName]);
        exit;
    } else {
        http_response_code(500);
        echo json_encode(['error_text' => 'Error while uploading file']);
        exit;
    }
 
}
