<?php
// backend/controllers/ResumeController.php
require_once __DIR__ . '/../models/Resume.php';
require_once __DIR__ . '/../utils/Auth.php';

class ResumeController {
    private $resumeModel;

    public function __construct() {
        $this->resumeModel = new Resume();
    }

    public function save() {
        Auth::requireLogin();
        $userId = Auth::getUserId();
        $data = json_decode(file_get_contents("php://input"), true);
        
        if (!isset($data['resume_data']) || !isset($data['template'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields']);
            return;
        }

        $resumeData = $data['resume_data'];
        $template = htmlspecialchars($data['template']);
        $atsScore = isset($data['ats_score']) ? intval($data['ats_score']) : 0;
        $jobDescription = isset($data['job_description']) ? htmlspecialchars($data['job_description']) : '';
        
        if (isset($data['resume_id']) && $data['resume_id']) {
            $result = $this->resumeModel->update($data['resume_id'], $userId, $resumeData, $template, $atsScore, $jobDescription);
        } else {
            $result = $this->resumeModel->save($userId, $resumeData, $template, $atsScore, $jobDescription);
        }
        
        if ($result) {
            echo json_encode(['success' => true]);
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to save resume']);
        }
    }

    public function list() {
        Auth::requireLogin();
        $userId = Auth::getUserId();
        $resumes = $this->resumeModel->findByUser($userId);
        echo json_encode(['resumes' => $resumes]);
    }

    public function get() {
        Auth::requireLogin();
        $userId = Auth::getUserId();
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing resume ID']);
            return;
        }
        
        $resume = $this->resumeModel->findById($id, $userId);
        if ($resume) {
            echo json_encode(['resume' => $resume]);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Resume not found']);
        }
    }

    public function getLast() {
        Auth::requireLogin();
        $userId = Auth::getUserId();
        $resume = $this->resumeModel->getLastResume($userId);
        echo json_encode(['resume' => $resume]);
    }

    public function generate() {
        Auth::requireLogin();
        $data = json_decode(file_get_contents("php://input"), true);
        
        // Mock AI generation
        $result = [];
        
        if (isset($data['summary']) && $data['summary']) {
            $result['summary'] = "Professional " . $data['summary'] . " Experienced professional with proven track record of delivering exceptional results. Strong leadership and communication skills.";
        } else {
            $result['summary'] = "Results-driven professional with extensive experience in the industry. Committed to excellence and continuous improvement. Strong analytical and problem-solving abilities.";
        }
        
        if (isset($data['experience']) && is_array($data['experience'])) {
            $result['experience'] = [];
            foreach ($data['experience'] as $exp) {
                if (isset($exp['description'])) {
                    $bulletPoints = explode('.', $exp['description']);
                    $enhanced = [];
                    foreach ($bulletPoints as $point) {
                        if (trim($point)) {
                            $enhanced[] = "• " . trim($point) . " with measurable outcomes.";
                        }
                    }
                    if (empty($enhanced)) {
                        $enhanced = ["• Successfully managed key responsibilities", "• Achieved significant improvements in operational efficiency"];
                    }
                    $exp['description'] = implode("\n", $enhanced);
                }
                $result['experience'][] = $exp;
            }
        } else {
            $result['experience'] = [];
        }
        
        echo json_encode(['success' => true, 'data' => $result]);
    }
}
?>