<?php

/**

 * Import Queue Manager

 * Manages background import jobs

 */



class ImportQueue {

    private $jobsDir;

    

    public function __construct() {

        $this->jobsDir = __DIR__ . '/';

    }

    

    public function addJob($filePath, $type, $source) {

        // Count total records

        $total = $this->countRecords($filePath);

        

        $jobId = uniqid('import_', true);

        $job = [

            'id' => $jobId,

            'file_path' => $filePath,

            'type' => $type,

            'source' => $source,

            'total' => $total,

            'status' => 'pending',

            'created_at' => date('Y-m-d H:i:s'),

            'processed' => 0,

            'successful' => 0,

            'failed' => 0,

            'progress' => 0

        ];

        

        file_put_contents($this->jobsDir . $jobId . '.json', json_encode($job));

        

        // Trigger background process (optional)

        $this->triggerBackgroundProcess($jobId);

        

        return $jobId;

    }

    

    public function getJobStatus($jobId) {

        $jobFile = $this->jobsDir . $jobId . '.json';

        if (file_exists($jobFile)) {

            return json_decode(file_get_contents($jobFile), true);

        }

        return null;

    }

    

    public function getQueueStatus() {

        $jobs = glob($this->jobsDir . 'import_*.json');

        $queue = [];

        

        foreach ($jobs as $jobFile) {

            $job = json_decode(file_get_contents($jobFile), true);

            $queue[] = [

                'id' => $job['id'],

                'type' => $job['type'],

                'status' => $job['status'],

                'progress' => $job['progress'],

                'created_at' => $job['created_at']

            ];

        }

        

        return $queue;

    }

    

    public function cancelJob($jobId) {

        $jobFile = $this->jobsDir . $jobId . '.json';

        if (file_exists($jobFile)) {

            $job = json_decode(file_get_contents($jobFile), true);

            $job['status'] = 'cancelled';

            file_put_contents($jobFile, json_encode($job));

            return true;

        }

        return false;

    }

    

    private function countRecords($filePath) {

        $count = 0;

        if (($handle = fopen($filePath, 'r')) !== FALSE) {

            fgetcsv($handle); // Skip header

            while (fgetcsv($handle) !== FALSE) {

                $count++;

            }

            fclose($handle);

        }

        return $count;

    }

    

    private function triggerBackgroundProcess($jobId) {

        // For Linux servers, use exec to run in background

        if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {

            $cmd = "php " . __DIR__ . "/process_import.php $jobId > /dev/null 2>&1 &";

            exec($cmd);

        }

    }

}

?>