<?php
namespace App\Modules\Behavior\Controllers;

class BehaviorController extends \Core\Controller {
    private $behaviorModel;
    private $intelligenceService;

    public function __construct() {
        parent::__construct();
        $this->behaviorModel = $this->model('Behavior/Models/BehaviorModel');
        require_once __DIR__ . '/../../../../core/Services/BehaviorIntelligenceService.php';
        $this->intelligenceService = new \Core\Services\BehaviorIntelligenceService();
    }

    /**
     * Standalone Page for Behavioral Control
     */
    public function index() {
        $dailyBehaviors = $this->behaviorModel->getDailyBehaviors($this->userId, date('Y-m-d'));
        $heatmapData = $this->behaviorModel->getHeatmapData($this->userId);
        
        $score = $this->intelligenceService->getUnifiedDisciplineScore($this->userId);
        $intelligence = [
            'score' => $score,
            'identity' => $this->intelligenceService->getIdentityNarrative($score)
        ];
        
        $warnings = $this->intelligenceService->detectPreFailure($this->userId);
        $recovery = $this->intelligenceService->suggestRecovery($this->userId);
        $triggerInsights = $this->intelligenceService->autoDetectTriggerIntelligence($this->userId);
        
        // Merge insights
        $behaviorInsights = array_merge($triggerInsights, $recovery);

        $this->view('Behavior/Views/dashboard', [
            'title' => 'محرك الهوية والانضباط | OTIS',
            'dailyBehaviors' => $dailyBehaviors,
            'heatmapData' => $heatmapData,
            'intelligence' => $intelligence,
            'warnings' => $warnings,
            'behaviorInsights' => $behaviorInsights
        ]);
    }

    /**
     * AJAX endpoint to toggle logging a behavior today.
     */
    public function toggleLog() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $habitId = $data['habit_id'] ?? null;
            $status = isset($data['status']) ? (int)$data['status'] : null;
            $triggerReason = $data['trigger_reason'] ?? null;
            $date = date('Y-m-d');

            if ($habitId !== null && $status !== null) {
                if (!isset($_SESSION['user_id'])) {
                    echo json_encode(['success' => false, 'error' => 'not_authenticated']);
                    exit;
                }

                $success = $this->behaviorModel->toggleLog($habitId, $_SESSION['user_id'], $date, $status, $triggerReason);
                echo json_encode(['success' => $success]);
                exit;
            }

            echo json_encode(['success' => false, 'error' => 'invalid_input']);
            exit;
        }
    }

    /**
     * Delete a negative habit completely
     */
    public function deleteHabit($id) {
        if (!isset($_SESSION['user_id'])) return redirect('/behavior');
        
        $db = \Core\Database::getInstance()->getConnection();
        $stmt = $db->prepare("DELETE FROM behavior_habits WHERE id = ? AND user_id = ?");
        $stmt->execute([$id, $_SESSION['user_id']]);
        
        return redirect('/behavior');
    }

    /**
     * Store new habit
     */
    public function storeHabit() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SESSION['user_id'])) {
            $name = trim($_POST['name'] ?? '');
            $category = trim($_POST['category'] ?? 'General');
            $severity = $_POST['severity'] ?? 'medium';
            $intensity = (int)($_POST['intensity'] ?? 1);
            $habitType = $_POST['habit_type'] ?? 'break'; // Added for build vs break
            $id = isset($_POST['habit_id']) ? (int)$_POST['habit_id'] : null;
            
            if ($name) {
                $db = \Core\Database::getInstance()->getConnection();
                if ($id) {
                    $stmt = $db->prepare("UPDATE behavior_habits SET name=?, habit_type=?, category=?, severity=?, intensity=? WHERE id=? AND user_id=?");
                    $stmt->execute([$name, $habitType, $category, $severity, $intensity, $id, $_SESSION['user_id']]);
                } else {
                    $stmt = $db->prepare("INSERT INTO behavior_habits (user_id, name, habit_type, category, severity, intensity) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$_SESSION['user_id'], $name, $habitType, $category, $severity, $intensity]);
                }
            }
        }
        return redirect('/behavior');
    }
}
