<?php

/**

 * Base AI Model Class

 * Handles core AI functionality, data processing, and model management

 */



class AIModel {

    protected $conn;

    protected $modelName;

    protected $modelVersion;

    protected $modelData;

    protected $isTrained = false;

    protected $accuracy = 0;

    protected $lastTrainingDate;

    

    public function __construct($modelName, $version = '1.0') {

        $this->conn = getDBConnection();

        $this->modelName = $modelName;

        $this->modelVersion = $version;

        $this->loadModel();

    }

    

    /**

     * Load existing model from file or database

     */

    protected function loadModel() {

        $modelFile = AI_MODELS_PATH . $this->modelName . '_v' . $this->modelVersion . '.json';

        

        if (file_exists($modelFile)) {

            $modelData = json_decode(file_get_contents($modelFile), true);

            $this->modelData = $modelData['weights'] ?? [];

            $this->accuracy = $modelData['accuracy'] ?? 0;

            $this->lastTrainingDate = $modelData['training_date'] ?? null;

            $this->isTrained = true;

        } else {

            // Try to load from database

            $query = "SELECT * FROM ai_models WHERE model_name = ? AND model_version = ?";

            $stmt = $this->conn->prepare($query);

            $stmt->bind_param("ss", $this->modelName, $this->modelVersion);

            $stmt->execute();

            $result = $stmt->get_result();

            

            if ($row = $result->fetch_assoc()) {

                $this->modelData = json_decode($row['model_data'], true);

                $this->accuracy = $row['accuracy'];

                $this->lastTrainingDate = $row['training_date'];

                $this->isTrained = true;

            }

            $stmt->close();

        }

    }

    

    /**

     * Save model to file and database

     */

    public function saveModel() {

        $modelData = [

            'weights' => $this->modelData,

            'accuracy' => $this->accuracy,

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

            'version' => $this->modelVersion

        ];

        

        // Save to file

        $modelFile = AI_MODELS_PATH . $this->modelName . '_v' . $this->modelVersion . '.json';

        file_put_contents($modelFile, json_encode($modelData, JSON_PRETTY_PRINT));

        

        // Save to database

        $query = "INSERT INTO ai_models (model_name, model_version, model_data, accuracy, training_date) 

                  VALUES (?, ?, ?, ?, NOW())

                  ON DUPLICATE KEY UPDATE 

                  model_data = VALUES(model_data),

                  accuracy = VALUES(accuracy),

                  training_date = VALUES(training_date)";

        

        $stmt = $this->conn->prepare($query);

        $modelDataJson = json_encode($this->modelData);

        $stmt->bind_param("sssd", $this->modelName, $this->modelVersion, $modelDataJson, $this->accuracy);

        $stmt->execute();

        $stmt->close();

    }

    

    /**

     * Normalize data for AI processing

     */

    protected function normalizeData($data, $min = null, $max = null) {

        if ($min === null) $min = min($data);

        if ($max === null) $max = max($data);

        

        if ($max == $min) return array_fill(0, count($data), 0.5);

        

        $normalized = [];

        foreach ($data as $value) {

            $normalized[] = ($value - $min) / ($max - $min);

        }

        return $normalized;

    }

    

    /**

     * Denormalize data back to original scale

     */

    protected function denormalizeValue($normalized, $min, $max) {

        return $normalized * ($max - $min) + $min;

    }

    

    /**

     * Calculate prediction accuracy

     */

    protected function calculateAccuracy($predictions, $actuals) {

        $correct = 0;

        $total = count($predictions);

        

        for ($i = 0; $i < $total; $i++) {

            if (abs($predictions[$i] - $actuals[$i]) < 0.1) {

                $correct++;

            }

        }

        

        return $total > 0 ? $correct / $total : 0;

    }

    

    /**

     * Get model performance metrics

     */

    public function getPerformanceMetrics() {

        return [

            'model_name' => $this->modelName,

            'version' => $this->modelVersion,

            'is_trained' => $this->isTrained,

            'accuracy' => $this->accuracy,

            'last_training' => $this->lastTrainingDate,

            'status' => $this->isTrained ? 'Active' : 'Not Trained'

        ];

    }

    

    /**

     * Clear model cache

     */

    public function clearCache() {

        $cacheFiles = glob(AI_PREDICTIONS_CACHE . $this->modelName . '_*.cache');

        foreach ($cacheFiles as $file) {

            unlink($file);

        }

    }

}