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

class MonthlyplanController extends \Core\Controller {

    private function getMonthlyModel() {
        return $this->model('Monthlyplan/Models/MonthlyplanModel');
    }

    public function index() {
        $userId = $this->userId ?? 1;
        
        // Allowed to view previous/next months via ?m=YYYY-MM
        $monthKey = $_GET['m'] ?? date('Y-m');
        
        $model = $this->getMonthlyModel();
        $plan  = $model->getOrCreatePlan($userId, $monthKey);
        
        // SYNC DYNAMIC GOALS
        $model->syncAutomatedGoals($userId, $plan->id, $monthKey);
        
        $categories = $model->getCategories($userId);
        // Fetch goals
        $goals = $model->getGoals($plan->id);

        // Calculate Strategic Controls
        $monthlyScore = $model->getMonthlyScore($goals, count($categories));
        $insights = $model->getStrategicInsights($userId, $plan->id, $monthKey, $goals);

        $this->view('Monthlyplan/Views/index', [
            'title' => 'خطة الشهر | ' . date('F Y', strtotime($monthKey . '-01')),
            'plan'  => $plan,
            'goals' => $goals,
            'categories' => $categories,
            'currentMonth' => $monthKey,
            'monthlyScore' => $monthlyScore,
            'insights' => $insights
        ]);
    }

    public function addGoal() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $userId = $this->userId ?? 1;
            $monthKey = $input['month'] ?? date('Y-m');

            $model = $this->getMonthlyModel();
            $plan  = $model->getOrCreatePlan($userId, $monthKey);

            $model->addGoal($plan->id, [
                'category_id' => (int)$input['category_id'],
                'title' => $input['title'],
                'target_value' => (int)$input['target_value'],
                'integration_type' => $input['integration_type'] ?? 'manual'
            ]);

            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function deleteGoal() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $this->userId ?? 1;
            
            $model = $this->getMonthlyModel();
            $db = \Core\Database::getInstance();
            $planId = $db->query("SELECT plan_id FROM monthly_goals WHERE id = ?", [$input['id']])->fetchColumn();
            
            // Basic ownership verification
            $planUser = $db->query("SELECT user_id FROM monthly_plans WHERE id = ?", [$planId])->fetchColumn();
            if ($planUser == $userId) {
                $model->deleteGoal($input['id'], $planId);
            }
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function updateProgress() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $this->userId ?? 1;
            
            $model = $this->getMonthlyModel();
            $db = \Core\Database::getInstance();
            $planId = $db->query("SELECT plan_id FROM monthly_goals WHERE id = ?", [$input['id']])->fetchColumn();
            
            // Ownership validation
            $planUser = $db->query("SELECT user_id FROM monthly_plans WHERE id = ?", [$planId])->fetchColumn();
            if ($planUser == $userId) {
                $model->updateManualProgress($input['id'], $planId, (int)$input['progress']);
                // auto-mark complete
                $target = $db->query("SELECT target_value FROM monthly_goals WHERE id = ?", [$input['id']])->fetchColumn();
                if ((int)$input['progress'] >= $target && $target > 0) {
                    $db->query("UPDATE monthly_goals SET status = 'completed' WHERE id = ?", [$input['id']]);
                } else {
                    $db->query("UPDATE monthly_goals SET status = 'active' WHERE id = ?", [$input['id']]);
                }
            }
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function addCategory() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $userId = $this->userId ?? 1;
            $model = $this->getMonthlyModel();
            
            $newId = $model->addCategory($userId, [
                'name' => $input['name'],
                'icon' => $input['icon'] ?? 'fa-circle',
                'color_theme' => $input['color_theme'] ?? 'primary'
            ]);
            
            echo json_encode(['success' => true, 'cat' => ['id' => $newId, 'name' => $input['name'], 'icon' => $input['icon'] ?? 'fa-circle', 'color_theme' => $input['color_theme'] ?? 'primary']]);
            exit;
        }
    }

    public function deleteCategory() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $this->userId ?? 1;
            
            $model = $this->getMonthlyModel();
            $model->deleteCategory($userId, $input['id']);
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function togglePrimaryGoal() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $this->userId ?? 1;
            
            $model = $this->getMonthlyModel();
            $db = \Core\Database::getInstance();
            $planId = $db->query("SELECT plan_id FROM monthly_goals WHERE id = ?", [$input['id']])->fetchColumn();
            
            $planUser = $db->query("SELECT user_id FROM monthly_plans WHERE id = ?", [$planId])->fetchColumn();
            if ($planUser == $userId) {
                $model->setPrimaryGoal($input['id'], $planId);
            }
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function saveReflection() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
            $userId = $this->userId ?? 1;
            
            $model = $this->getMonthlyModel();
            $model->saveReflection($input['plan_id'], $userId, [
                'worked' => $input['worked'],
                'failed' => $input['failed'],
                'why'    => $input['why']
            ]);
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    public function carryOverGoals() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $userId = $this->userId ?? 1;
            $monthKey = $input['month'] ?? date('Y-m'); // current month
            
            $model = $this->getMonthlyModel();
            $db = \Core\Database::getInstance();
            
            // Get previous month plan
            $prevMonth = date('Y-m', strtotime($monthKey . '-01 -1 month'));
            $prevPlan = $db->query("SELECT id FROM monthly_plans WHERE user_id = ? AND month_key = ?", [$userId, $prevMonth])->fetch(\PDO::FETCH_OBJ);
            
            if ($prevPlan) {
                // Get incomplete goals from previous month
                $incompleteGoals = $db->query("SELECT * FROM monthly_goals WHERE plan_id = ? AND status != 'completed'", [$prevPlan->id])->fetchAll(\PDO::FETCH_OBJ);
                
                if (!empty($incompleteGoals)) {
                    $currentPlan = $model->getOrCreatePlan($userId, $monthKey);
                    foreach ($incompleteGoals as $ig) {
                        // Insert into current plan
                        $model->addGoal($currentPlan->id, [
                            'category_id' => $ig->category_id,
                            'title' => $ig->title,
                            'target_value' => $ig->target_value,
                            'integration_type' => $ig->integration_type,
                            'integration_ref' => $ig->integration_ref,
                            'difficulty' => $ig->difficulty ?? 'medium'
                        ]);
                    }
                }
            }
            
            echo json_encode(['success' => true]);
            exit;
        }
    }
}
