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

class HabitsController extends \Core\Controller {

    public function index() {
        $model  = $this->model('Habits/Models/HabitModel');
        $habits = $model->getHabitsWithStatus($this->userId);

        // Batch streals calculation (Performance Optimization)
        $streaks = $model->getBatchStreaks($this->userId);
        foreach ($habits as $h) {
            $h->streak = $streaks[$h->id] ?? 0;
        }

        // Behavior Intelligence
        $biService = $this->service('BehaviorIntelligenceService');
        $disciplineScore = $biService->getUnifiedDisciplineScore($this->userId);
        $identityNarrative = $biService->getIdentityNarrative($disciplineScore);

        // Fetch recent logs in one single query to eliminate N+1
        $recentLogs = $model->getRecentLogsAssoc($this->userId, 7);

        $this->view('Habits/Views/index', [
            'title'      => 'تتبع العادات | OTIS',
            'habits'     => $habits,
            'recentLogs' => $recentLogs,
            'disciplineScore' => $disciplineScore,
            'identityNarrative' => $identityNarrative
        ]);
    }

    public function store() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { abort(404); }
        verify_csrf_token($_POST['csrf_token'] ?? '');

        $model = $this->model('Habits/Models/HabitModel');
        $model->addHabit($this->userId, [
            'name'               => sanitize_input($_POST['name'] ?? ''),
            'icon'               => sanitize_input($_POST['icon'] ?? 'fa-star'),
            'habit_type'         => sanitize_input($_POST['habit_type'] ?? 'build'),
            'identity_statement' => sanitize_input($_POST['identity_statement'] ?? ''),
            'intensity'          => (int)($_POST['intensity'] ?? 1),
            'color_hex'          => sanitize_input($_POST['color_hex'] ?? '#0d6efd'),
            'impact_category'    => sanitize_input($_POST['impact_category'] ?? 'general'),
            'impact_amount'      => (float)($_POST['impact_amount'] ?? 0),
            'target_value'       => (float)($_POST['target_value'] ?? 0),
            'unit'               => sanitize_input($_POST['unit'] ?? '')
        ]);

        set_flash_message('habits', 'تم إضافة العادة بنجاح! 🎯', 'success');
        redirect('/habits');
    }

    // AJAX
    public function checkin() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->jsonError('Method not allowed', 405);
        }
        
        $data    = json_decode(file_get_contents('php://input'), true);
        $habitId = (int)($data['habit_id'] ?? 0);
        $undo    = (bool)($data['undo'] ?? false);
        $token   = $data['csrf_token'] ?? '';

        if (!verify_csrf_token($token)) {
            $this->jsonError('Invalid CSRF token');
        }

        if (!$habitId) {
            $this->jsonError('Habit ID missing');
        }

        $model = $this->model('Habits/Models/HabitModel');
        
        // Ownership & Safety Check
        if ($undo) {
            $model->undoCheckin($this->userId, $habitId);
            $model->logImpact($habitId, $this->userId, true);
            $model->syncToCalendar($habitId, $this->userId, true);
        } else {
            $model->checkin($this->userId, $habitId);
            $model->logImpact($habitId, $this->userId, false);
            $model->syncToCalendar($habitId, $this->userId, false);
        }

        // Stats for addictive feedback
        $streak = $model->getStreak($this->userId, $habitId);
        $biService = $this->service('BehaviorIntelligenceService');
        $newScore = $biService->getUnifiedDisciplineScore($this->userId);
        
        $messages = [
            "رائع! انضباطك يزداد قوة 🔥",
            "خطوة أخرى نحو هويتك الجديدة 🎯",
            "استمر، أنت تصنع الفارق اليوم ✨",
            "إنجاز يُحسب لك! ممتاز 👏"
        ];

        $this->jsonResponse([
            'success' => true, 
            'streak' => $streak,
            'newScore' => $newScore,
            'message' => $messages[array_rand($messages)]
        ]);
    }

    // AJAX
    public function delete() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false]); exit;
        }
        $data    = json_decode(file_get_contents('php://input'), true);
        $habitId = (int)($data['habit_id'] ?? 0);

        if (!$habitId) {
            echo json_encode(['success' => false]); exit;
        }

        $model = $this->model('Habits/Models/HabitModel');
        $model->softDelete($habitId, $this->userId);
        echo json_encode(['success' => true]);
        exit;
    }
}
